int Conv::ToJavaMap(JNIEnv *jniEnv, Handle<Value> val, int componentType, jobject *jVal) { Local<Object> oVal; Local<Array> aPropertyNames; if(val.IsEmpty() || val->IsNull() || val->IsUndefined()) { *jVal = 0; return OK; } if(!val->IsObject()) return ErrorType; oVal = val->ToObject(); aPropertyNames = oVal->GetOwnPropertyNames(); int len = aPropertyNames->Length(); jobject ob = jniEnv->NewObject(mapClass, mapCtor); if(ob) { int res = OK; for(int i = 0; i < len; i++) { Local<String> key = Local<String>::Cast(aPropertyNames->Get(i)); jstring jKey; jobject item; res = ToJavaString(jniEnv, key, &jKey); if(res != OK) break; res = ToJavaObject(jniEnv, oVal->Get(key), componentType, &item); if(res != OK) break; jniEnv->CallObjectMethod(ob, mapPut, jKey, item); } } if(ob) { *jVal = ob; return OK; } if(jniEnv->ExceptionCheck()) jniEnv->ExceptionClear(); return ErrorVM; }
/* static */ Handle<Value> MemoryObject::createSubBuffer(const Arguments& args) { HandleScope scope; MemoryObject *mo = ObjectWrap::Unwrap<MemoryObject>(args.This()); cl_mem_flags flags = args[0]->NumberValue(); if (flags != CL_BUFFER_CREATE_TYPE_REGION) return ThrowException(Exception::Error(String::New("CL_INVALID_VALUE"))); RegionWrapper region; Local<Object> obj = args[1]->ToObject(); region.origin = obj->Get(String::New("origin"))->NumberValue(); region.size = obj->Get(String::New("size"))->NumberValue(); MemoryObjectWrapper *mw = 0; cl_int ret = mo->getMemoryObjectWrapper()->createSubBuffer(flags, region, &mw); if (ret != CL_SUCCESS) { WEBCL_COND_RETURN_THROW(CL_INVALID_VALUE); WEBCL_COND_RETURN_THROW(CL_INVALID_BUFFER_SIZE); WEBCL_COND_RETURN_THROW(CL_INVALID_HOST_PTR); WEBCL_COND_RETURN_THROW(CL_MEM_OBJECT_ALLOCATION_FAILURE); WEBCL_COND_RETURN_THROW(CL_OUT_OF_RESOURCES); WEBCL_COND_RETURN_THROW(CL_OUT_OF_HOST_MEMORY); return ThrowException(Exception::Error(String::New("UNKNOWN ERROR"))); } return scope.Close(MemoryObject::New(mw)->handle_); }
TEST_F(JSDeviceTest, getEndpoints) { EndpointID endpointId1{20}; EndpointID endpointId2{21}; ZEndpoint endpoint1{NwkAddr {1}, endpointId1, 30, 31, 32, {ClusterID {50}}, {ClusterID {51}}}; ZEndpoint endpoint2{NwkAddr {1}, endpointId2, 30, 31, 32, {ClusterID {60}}, {ClusterID {61}}}; ZDevice zDevice{extAddress, NwkAddr(1), 0, {endpoint1, endpoint2}}; V8_SETUP Local<Object> objectEndpoint1 = Object::New(isolate); Local<Object> objectEndpoint2 = Object::New(isolate); EXPECT_CALL(*zDevices, exists(extAddress)).WillOnce(Return(true)); EXPECT_CALL(*zDevices, getDevice(extAddress)).WillOnce(Return(&zDevice)); EXPECT_CALL(*jsEndpoint, createInstance(isolate, extAddress, endpointId1)).WillOnce( Return(objectEndpoint1)); EXPECT_CALL(*jsEndpoint, createInstance(isolate, extAddress, endpointId2)).WillOnce( Return(objectEndpoint2)); v8::Local<v8::Value> result = runScript(creatingZDeviceScript + "a.getEndpoints();"); ASSERT_THAT(result.IsEmpty(), false); ASSERT_THAT(result->IsArray(), true); Local<Array> array = result.As<Array>(); ASSERT_THAT(array->Length(), 2); ASSERT_THAT(array->Get(0)->IsObject(), true); ASSERT_THAT(array->Get(1)->IsObject(), true); Local<Object> jszEndpoint0 = array->Get(0).As<Object>(); Local<Object> jszEndpoint1 = array->Get(1).As<Object>(); ASSERT_THAT(jszEndpoint0->GetIdentityHash(), Eq(objectEndpoint1->GetIdentityHash())); ASSERT_THAT(jszEndpoint1->GetIdentityHash(), Eq(objectEndpoint2->GetIdentityHash())); }
static Handle<Value> New(const Arguments& args) { v8::HandleScope scope; Local<Object> options = args[0]->ToObject(); //TODO: Enable passing of config options for most params. Start with the three below. v8::String::AsciiValue hmmValue(options->Get(String::NewSymbol("hmm"))); v8::String::AsciiValue lmValue(options->Get(String::NewSymbol("lm"))); v8::String::AsciiValue dictValue(options->Get(String::NewSymbol("dict"))); v8::String::AsciiValue samprateValue(options->Get(String::NewSymbol("samprate"))); v8::String::AsciiValue nfftValue(options->Get(String::NewSymbol("nfft"))); PocketSphinx* instance = new PocketSphinx(); cmd_ln_t* config = cmd_ln_init(NULL, ps_args(), TRUE, "-hmm", *hmmValue, "-lm", *lmValue, "-dict", *dictValue, "-samprate", *samprateValue, "-nfft", *nfftValue, NULL); instance->m_ps = ps_init(config); instance->Wrap(args.This()); return scope.Close(args.This()); }
Handle<Value> AppjsSchemeHandler::NodeCallback(const Arguments& args) { HandleScope scope; AppjsSchemeHandler* me = static_cast<AppjsSchemeHandler *>(UnwrapObject(args.Data())); AutoLock lock_scope(me); me->status_ = args[0]->NumberValue(); me->status_text_ = V8StringToChar(args[1]->ToString()); me->mime_type_ = V8StringToChar(args[2]->ToString()); me->data_ = node::Buffer::Data(args[4]->ToObject()); me->data_length_ = node::Buffer::Length(args[4]->ToObject()); Local<Object> headerSets = args[3]->ToObject(); Local<Array> names = Local<Array>::Cast(headerSets->Get(String::NewSymbol("names"))); Local<Array> headers = Local<Array>::Cast(headerSets->Get(String::NewSymbol("headers"))); for(int i = 0; i < names->Length(); i++) { me->headers_.insert( std::pair<CefString,CefString>( V8StringToChar(names->Get(i)), V8StringToChar(headers->Get(i)) ) ); } me->callback_->HeadersAvailable(); return args.This(); }
void ClientHandler::OnBeforeClose(CefRefPtr<CefBrowser> browser) { REQUIRE_UI_THREAD(); // There is a bug in CEF for Linux I think that there is no window object // when the code reaches here. #if not defined(__LINUX__) const int argc = 1; Handle<Object> handle = this->GetV8WindowHandle(browser); Handle<Value> argv[argc] = {String::New("close")}; node::MakeCallback(handle,"emit",argc,argv); #endif if (m_BrowserHwnd == browser->GetWindowHandle()) { // Free the browser pointer so that the browser can be destroyed m_Browser = NULL; Local<Object> global = Context::GetCurrent()->Global(); Local<Object> process = global->Get(String::NewSymbol("process"))->ToObject(); Local<Object> emitter = Local<Object>::Cast(process->Get(String::NewSymbol("AppjsEmitter"))); const int argc = 1; Handle<Value> argv[argc] = {String::New("exit")}; node::MakeCallback(emitter,"emit",argc,argv); DoClose(browser); } }
// Initializes commentary data, reading it from the language.dat file // void commentary::init_commentary(Handle<Object> languageDat) { HandleScope scope; // Read languageDat line by line, updating the // commentary database // const Local<Array> props = languageDat->GetOwnPropertyNames(); const uint32_t length = props->Length(); Local<String> key; Local<Array> value; Local<String> event, comment; char strKey[64]; char strValue[128]; for (uint32_t i=0 ; i<length ; ++i) { key = props->Get(i)->ToString(); value = Local<Array>::Cast(languageDat->Get(key)); event = value->Get(0)->ToString(); comment = value->Get(1)->ToString(); // Add line to the commentary database // comm_data[toAscii(event, strKey)].push_back(toAscii(comment, strValue)); } }
Handle<Value> WrappedScript::CreateContext(const Arguments& args) { HandleScope scope; Persistent<Context> context = Context::New(NULL, WrappedContext::global_template); WrappedContext *wrappedContext = new WrappedContext(context); Local<Object> global = context->Global(); // Allow current context access to newly created context's objects. context->SetSecurityToken(Context::GetCurrent()->GetSecurityToken()); // If a sandbox is provided initial the new context's global with it. if (args.Length() > 0) { Local<Object> sandbox = args[0]->ToObject(); Local<Array> keys = sandbox->GetPropertyNames(); for (uint32_t i = 0; i < keys->Length(); i++) { Handle<String> key = keys->Get(Integer::New(i))->ToString(); Handle<Value> value = sandbox->Get(key); if (value == sandbox) { value = global; } global->Set(key, value); } } return scope.Close(global); }
Handle<Value> WrappedScript::CreateContext(const Arguments& args) { HandleScope scope; Local<Object> context = WrappedContext::NewInstance(); WrappedContext *wrappedContext = NativeObject::Unwrap<WrappedContext>(context); if (args.Length() > 0) { Local<Object> sandbox = args[0]->ToObject(); Local<Array> keys = sandbox->GetPropertyNames(); for (uint32_t i = 0; i < keys->Length(); i++) { Handle<String> key = keys->Get(Integer::New(i))->ToString(); Handle<Value> value = sandbox->Get(key); if (value == sandbox) { value = context; } context->Set(key, value); } if (args.Length() > 1 && args[1]->IsFunction()) { wrappedContext->SetInitCallback(Persistent<Function>::New(Handle<Function>::Cast(args[1]))); } } wrappedContext->GetV8Context()->SetSecurityToken( Context::GetCurrent()->GetSecurityToken()); return scope.Close(context); }
void Server::FireEvent(std::string name, const int argc, Local<Value> argv[] ){ Locker v8Locker(isolate); Isolate::Scope isoscope(isolate); HandleScope hs(isolate); Local<Context> ctx = Local<Context>::New(isolate, context); Context::Scope cs(ctx); TryCatch try_catch; JS_Object global(ctx->Global()); Local<Object> serverjs = global.getObject("$server"); Local<Value> fire = serverjs->Get(String::NewFromUtf8(isolate, "fire")); Local<Function> fn = Local<Function>::Cast(fire); if (name == "ScriptInit"){ Local<Value> check = serverjs->Get(String::NewFromUtf8(isolate, "checkPlayers")); Local<Function> cpfn = Local<Function>::Cast(check); cpfn->Call(serverjs, 0, NULL); } Local<Value> *args = new Local<Value>[argc + 1]; args[0] = String::NewFromUtf8(isolate, name.c_str()); if (argc > 0){ for (int i = 0; i < argc; i++){ args[i + 1] = argv[i]; } } fn->Call(serverjs, argc + 1, args); delete[] args; if (try_catch.HasCaught()){ Utils::PrintException(&try_catch); } }
/* Generic constructor wrapper. * args[0]: row buffer * args[1]: array of blob & text column values * args.Data(): mapData holding the record and ColumnHandlers * args.This(): VO built from the mapping-specific InstanceTemplate */ Handle<Value> nroConstructor(const Arguments &args) { HandleScope scope; if(args.IsConstructCall()) { /* Unwrap record from mapData */ Local<Object> mapData = args.Data()->ToObject(); const Record * record = unwrapPointer<const Record *>(mapData->Get(0)->ToObject()); /* Unwrap Column Handlers from mapData */ ColumnHandlerSet * handlers = unwrapPointer<ColumnHandlerSet *>(mapData->Get(1)->ToObject()); /* Build NdbRecordObject */ NdbRecordObject * nro = new NdbRecordObject(record, handlers, args[0], args[1]); /* Wrap for JavaScript */ wrapPointerInObject<NdbRecordObject *>(nro, nroEnvelope, args.This()); freeFromGC(nro, args.This()); } else { ThrowException(Exception::Error(String::New("must be a called as constructor"))); } return args.This(); }
bool ClientHandler::DoClose(CefRefPtr<CefBrowser> browser) { REQUIRE_UI_THREAD(); if (!browser->IsPopup() && m_BrowserHwnd == browser->GetWindowHandle()) { Local<Object> global = Context::GetCurrent()->Global(); Local<Object> process = global->Get(String::NewSymbol("process"))->ToObject(); Local<Object> emitter = Local<Object>::Cast(process->Get(String::NewSymbol("AppjsEmitter"))); Handle<Value> exitArgv[1] = {String::New("exit")}; node::MakeCallback(emitter,"emit",1,exitArgv); m_Browser = NULL; m_BrowserHwnd = NULL; CloseMainWindow(); // Return true here so that we can skip closing the browser window // in this pass. (It will be destroyed due to the call to close // the parent above.) return true; } // A popup browser window is not contained in another window, so we can let // these windows close by themselves. return false; }
/* JS QueryOperation.create(ndbRootProjection, keyBuffer, depth) */ void createQueryOperation(const Arguments & args) { DEBUG_MARKER(UDEB_DEBUG); REQUIRE_ARGS_LENGTH(3); Isolate * isolate = Isolate::GetCurrent(); int size = args[2]->Int32Value(); QueryOperation * queryOperation = new QueryOperation(size); const NdbQueryOperationDef * root, * current; Local<Value> v; Local<Object> spec = args[0]->ToObject(); setRowBuffers(queryOperation, spec); current = root = createTopLevelQuery(queryOperation, spec, args[1]->ToObject()); while(! (v = spec->Get(GET_KEY(K_next)))->IsNull()) { spec = v->ToObject(); current = createNextLevel(queryOperation, spec, current); assert(current->getOpNo() == spec->Get(GET_KEY(K_depth))->Uint32Value()); setRowBuffers(queryOperation, spec); } queryOperation->prepare(root); args.GetReturnValue().Set(QueryOperation_Wrapper(queryOperation)); }
void Msg_Struct::build_buffer_map(const Field_Info &field_info, Block_Buffer &buffer, Isolate* isolate, v8::Local<v8::Value> value) { if (!value->IsMap()) { LOG_ERROR("field_name:%s is not map, struct_name:%s", field_info.field_name.c_str(), struct_name().c_str()); buffer.write_uint16(0); return; } Local<Map> map = Local<Map>::Cast(value); int16_t len = map->Size(); buffer.write_uint16(len); Local<Array> array = map->AsArray(); //index N is the Nth key and index N + 1 is the Nth value. if(is_struct(field_info.field_type)) { for (int i = 0; i < len * 2; i = i + 2) { Local<Value> element = array->Get(isolate->GetCurrentContext(), i + 1).ToLocalChecked(); build_buffer_struct(field_info, buffer, isolate, element); } } else { Field_Info key_info; key_info.field_label = "args"; key_info.field_type = field_info.key_type; key_info.field_name = field_info.key_name; for (int i = 0; i < len * 2; i = i + 2) { Local<Value> key = array->Get(isolate->GetCurrentContext(), i).ToLocalChecked(); Local<Value> element = array->Get(isolate->GetCurrentContext(), i + 1).ToLocalChecked(); build_buffer_struct(key_info, buffer, isolate, key); build_buffer_struct(field_info, buffer, isolate, element); } } }
Handle<Value> NodeCuda::Function::LaunchKernel(const Arguments& args) { HandleScope scope; Function *pfunction = ObjectWrap::Unwrap<Function>(args.This()); Local<Array> gridDim = Local<Array>::Cast(args[0]); unsigned int gridDimX = gridDim->Get(0)->Uint32Value(); unsigned int gridDimY = gridDim->Get(1)->Uint32Value(); unsigned int gridDimZ = gridDim->Get(2)->Uint32Value(); Local<Array> blockDim = Local<Array>::Cast(args[1]); unsigned int blockDimX = blockDim->Get(0)->Uint32Value(); unsigned int blockDimY = blockDim->Get(1)->Uint32Value(); unsigned int blockDimZ = blockDim->Get(2)->Uint32Value(); Local<Object> buf = args[2]->ToObject(); char *pbuffer = Buffer::Data(buf); size_t bufferSize = Buffer::Length(buf); void *cuExtra[] = { CU_LAUNCH_PARAM_BUFFER_POINTER, pbuffer, CU_LAUNCH_PARAM_BUFFER_SIZE, &bufferSize, CU_LAUNCH_PARAM_END }; CUresult error = cuLaunchKernel(pfunction->m_function, gridDimX, gridDimY, gridDimZ, blockDimX, blockDimY, blockDimZ, 0, 0, NULL, cuExtra); return scope.Close(Number::New(error)); }
void prepare_import_results(Local<Value> returned_value, sass_context_wrapper* ctx_w) { NanScope(); if (returned_value->IsArray()) { Handle<Array> array = Handle<Array>::Cast(returned_value); ctx_w->imports = sass_make_import_list(array->Length()); for (size_t i = 0; i < array->Length(); ++i) { Local<Value> value = array->Get(i); if (!value->IsObject()) continue; Local<Object> object = Local<Object>::Cast(value); char* path = create_string(object->Get(NanNew<String>("file"))); char* contents = create_string(object->Get(NanNew<String>("contents"))); ctx_w->imports[i] = sass_make_import_entry(path, (!contents || contents[0] == '\0') ? 0 : strdup(contents), 0); } } else if (returned_value->IsObject()) { ctx_w->imports = sass_make_import_list(1); Local<Object> object = Local<Object>::Cast(returned_value); char* path = create_string(object->Get(NanNew<String>("file"))); char* contents = create_string(object->Get(NanNew<String>("contents"))); ctx_w->imports[0] = sass_make_import_entry(path, (!contents || contents[0] == '\0') ? 0 : strdup(contents), 0); } else { ctx_w->imports = sass_make_import_list(1); ctx_w->imports[0] = sass_make_import_entry(ctx_w->file, 0, 0); } }
/** * @details This is the asynchronous method used to generate a mapserv * response. The response is a javascript object literal with the following * properties: * * - `data`: a `Buffer` object representing the response body * - `headers`: the HTTP headers as an object literal * * `args` should contain the following parameters: * * @param env A javascript object literal containing the CGI environment * variables which will direct the mapserv response. * * @param body The optional string or buffer object representing the body of an * HTTP request. * * @param callback A function that is called on error or when the * resource has been created. It should have the signature * `callback(err, resource)`. */ Handle<Value> Map::MapservAsync(const Arguments& args) { HandleScope scope; string body; Local<Object> env; Local<Function> callback; switch (args.Length()) { case 2: ASSIGN_OBJ_ARG(0, env); ASSIGN_FUN_ARG(1, callback); break; case 3: ASSIGN_OBJ_ARG(0, env); if (args[1]->IsString()) { body = *String::Utf8Value(args[1]->ToString()); } else if (Buffer::HasInstance(args[1])) { Local<Object> buffer = args[1]->ToObject(); body = string(Buffer::Data(buffer), Buffer::Length(buffer)); } else if (!args[1]->IsNull() && !args[1]->IsUndefined()) { THROW_CSTR_ERROR(TypeError, "Argument 1 must be one of a string; buffer; null; undefined"); } ASSIGN_FUN_ARG(2, callback); break; default: THROW_CSTR_ERROR(Error, "usage: Map.mapserv(env, [body], callback)"); } Map* self = ObjectWrap::Unwrap<Map>(args.This()); MapBaton *baton = new MapBaton(); baton->request.data = baton; baton->self = self; baton->callback = Persistent<Function>::New(callback); baton->map = self->map; baton->error = NULL; baton->body = body; // Convert the environment object to a `std::map` const Local<Array> properties = env->GetPropertyNames(); const uint32_t length = properties->Length(); for (uint32_t i = 0; i < length; ++i) { const Local<Value> key = properties->Get(i); const Local<Value> value = env->Get(key); baton->env.insert(pair<string, string>(string(*String::Utf8Value(key->ToString())), string(*String::Utf8Value(value->ToString()))) ); } self->Ref(); // increment reference count so map is not garbage collected uv_queue_work(uv_default_loop(), &baton->request, MapservWork, (uv_after_work_cb) MapservAfter); return Undefined(); }
Handle<Value> TypedArray::New(GDALDataType type, unsigned int length) { NanEscapableScope(); Handle<Value> val; Handle<Function> constructor; Local<Object> global = NanGetCurrentContext()->Global(); const char *name; switch(type) { case GDT_Byte: name = "Uint8Array"; break; case GDT_Int16: name = "Int16Array"; break; case GDT_UInt16: name = "Uint16Array"; break; case GDT_Int32: name = "Int32Array"; break; case GDT_UInt32: name = "Uint32Array"; break; case GDT_Float32: name = "Float32Array"; break; case GDT_Float64: name = "Float64Array"; break; default: NanThrowError("Unsupported array type"); return NanEscapeScope(NanUndefined()); } // make ArrayBuffer val = global->Get(NanNew("ArrayBuffer")); if(val.IsEmpty() || !val->IsFunction()) { NanThrowError("Error getting ArrayBuffer constructor"); return NanEscapeScope(NanUndefined()); } constructor = val.As<Function>(); Local<Value> size = NanNew<Integer>(length * GDALGetDataTypeSize(type) / 8); Local<Value> array_buffer = constructor->NewInstance(1, &size); if(array_buffer.IsEmpty() || !array_buffer->IsObject()) { NanThrowError("Error allocating ArrayBuffer"); return NanEscapeScope(NanUndefined()); } // make TypedArray val = global->Get(NanNew(name)); if(val.IsEmpty() || !val->IsFunction()) { NanThrowError("Error getting typed array constructor"); return NanEscapeScope(NanUndefined()); } constructor = val.As<Function>(); Local<Object> array = constructor->NewInstance(1, &array_buffer); if(array.IsEmpty() || !array->IsObject()) { NanThrowError("Error creating TypedArray"); return NanEscapeScope(NanUndefined()); } return NanEscapeScope(array); }
Handle<Value> xhr_send(const Arguments &args) { LOGFN("calling xhr send"); String::Utf8Value arg0(args[0]); String::Utf8Value arg1(args[1]); const char *method = ToCString(arg0); const char *url = ToCString(arg1); bool async = args[2]->BooleanValue(); const char *data = NULL; String::Utf8Value arg3(args[3]); data = ToCString(arg3); int state = args[4]->Int32Value(); int id = args[5]->Int32Value(); request_header *headers = NULL; if(!args[6].IsEmpty() && !args[6]->IsUndefined() && !args[6]->IsNull()) { Local<Object> requestHeadersObj = args[6]->ToObject(); Local<Array> requestHeaderNames = requestHeadersObj->GetPropertyNames(); int length = requestHeaderNames->Get(STRING_CACHE_length)->Int32Value(); for (int i = 0; i < length; i++) { request_header * rh = (request_header*) malloc(sizeof(request_header)); Local<Value> prop = requestHeaderNames->Get(i); String::Utf8Value header(prop); String::Utf8Value value(requestHeadersObj->Get(prop)); int hLen = strlen(ToCString(header)) + 1; rh->header = (char *) malloc(hLen); strlcpy(rh->header, ToCString(header), hLen); int vLen = strlen(ToCString(value)) + 1; rh->value = (char *) malloc(vLen); strlcpy(rh->value, ToCString(value), vLen); HASH_ADD(hh, headers, header, strlen(rh->header)+1, rh); } } xhr req; req.id = id; req.method = method; req.url = url; req.data = data; req.async = async; req.state = state; req.request_headers = headers; xhr_send(&req); if(headers != NULL) { request_header *currentHeader, *tmp; HASH_ITER(hh, headers, currentHeader, tmp) { HASH_DEL(headers, currentHeader); free(currentHeader->header); free(currentHeader->value); free(currentHeader); }
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(); }
bool PointJsToC(v8::Handle<Value> value,cs::Twin* r){ HandleScope store; if(!value->IsObject()) return false; Local<Object> vObj = value->ToObject(); Local<Value> vx = vObj->Get(String::New("x")); if(vx->IsUndefined()) return false; Local<Value> vy = vObj->Get(String::New("y")); if(vy->IsUndefined()) return false; r->x = vx->Int32Value(); r->y = vy->Int32Value(); return true; }
void ShowToast(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = Isolate::GetCurrent(); HandleScope scope(isolate); if (args.Length() < 2){ isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "show() requires an object and function argument"))); return; } Local<Object> o = args[0].As<Object>(); WCHAR* title = NULL; WCHAR* msg = NULL; char* img = NULL; Local<String> titleKey = String::NewFromUtf8(isolate, "title"); Local<String> msgKey = String::NewFromUtf8(isolate, "subtitle"); Local<String> imgKey = String::NewFromUtf8(isolate, "imageUri"); if (o->Has(titleKey)){ String::Utf8Value v (o->Get(titleKey)->ToString()); size_t len = strlen(*v) + 1; title = new WCHAR[len]; swprintf(title, len, L"%S", *v); } if (o->Has(msgKey)){ String::Utf8Value v(o->Get(msgKey)->ToString()); size_t len = strlen(*v) + 1; msg = new WCHAR[len]; swprintf(msg, len, L"%S", *v); } if (o->Has(imgKey)){ String::Utf8Value v(o->Get(imgKey)->ToString()); size_t len = strlen(*v) + 1; img = new char[len]; sprintf(img, "%s", *v); } if (title == NULL && msg == NULL){ return; } Local<Function> cbFn = args[1].As<Function>(); WindowsToastNotification* wtn = new WindowsToastNotification(); wtn->ShowNotification(title, msg, img, cbFn); DELETE_IF(title); DELETE_IF(msg); DELETE_IF(img); }
Handle<Value> ODBCResult::FetchAll(const Arguments& args) { DEBUG_PRINTF("ODBCResult::FetchAll\n"); HandleScope scope; ODBCResult* objODBCResult = ObjectWrap::Unwrap<ODBCResult>(args.Holder()); uv_work_t* work_req = (uv_work_t *) (calloc(1, sizeof(uv_work_t))); fetch_work_data* data = (fetch_work_data *) calloc(1, sizeof(fetch_work_data)); Local<Function> cb; data->fetchMode = objODBCResult->m_fetchMode; if (args.Length() == 1 && args[0]->IsFunction()) { cb = Local<Function>::Cast(args[0]); } else if (args.Length() == 2 && args[0]->IsObject() && args[1]->IsFunction()) { cb = Local<Function>::Cast(args[1]); Local<Object> obj = args[0]->ToObject(); if (obj->Has(OPTION_FETCH_MODE) && obj->Get(OPTION_FETCH_MODE)->IsInt32()) { data->fetchMode = obj->Get(OPTION_FETCH_MODE)->ToInt32()->Value(); } } else { return ThrowException(Exception::TypeError( String::New("ODBCResult::FetchAll(): 1 or 2 arguments are required. The last argument must be a callback function.") )); } data->rows = Persistent<Array>::New(Array::New()); data->errorCount = 0; data->count = 0; data->objError = Persistent<Object>::New(Object::New()); data->cb = Persistent<Function>::New(cb); data->objResult = objODBCResult; work_req->data = data; uv_queue_work(uv_default_loop(), work_req, UV_FetchAll, (uv_after_work_cb)UV_AfterFetchAll); data->objResult->Ref(); return scope.Close(Undefined()); }
static void setFeatures(Sample* s, Local<Object>& features) { //Local<Array> featureNames = features->GetOwnPropertyNames(); Local<Array> featureNames = Nan::GetOwnPropertyNames(features).ToLocalChecked(); int featureCount = featureNames->Length(); int i; for(i = 0; i < featureCount; ++i) { // FIXME: verify that this is an integer Local<Integer> n = featureNames->Get(i)->ToInteger(); // FIXME: verify that this is a number Local<Number> v = features->Get(n->Value())->ToNumber(); s->xCodes[n->Value()] = v->Value(); } }
Handle<Value> App::On(const Arguments& args) { HandleScope scope; Local<Object> global = Context::GetCurrent()->Global(); Local<Object> process = global->Get(String::NewSymbol("process"))->ToObject(); Local<Object> Emitter = Local<Object>::Cast(process->Get(String::NewSymbol("AppjsEmitter"))); Local<Function> On = Local<Function>::Cast(Emitter->Get(String::NewSymbol("on"))); Handle<Value> argv[2] = { args[0] , args[1] }; On->Call(Emitter, 2, argv); return scope.Close(args.This()); }
Susi::Util::Any Susi::JS::Engine::convertFromJS(Handle<Value> jsVal){ if(jsVal->IsArray()){ Susi::Util::Any::Array result; auto obj = jsVal->ToObject(); const Local<Array> props = obj->GetPropertyNames(); const uint32_t length = props->Length(); for (uint32_t i=0 ; i<length ; ++i){ const Local<Value> key = props->Get(i); const Local<Value> value = obj->Get(key); result.push_back(Susi::JS::Engine::convertFromJS(value)); } return result; } if(jsVal->IsObject()){ Susi::Util::Any result = Susi::Util::Any::Object{}; auto obj = jsVal->ToObject(); const Local<Array> props = obj->GetPropertyNames(); const uint32_t length = props->Length(); for (uint32_t i=0 ; i<length ; ++i){ const Local<Value> key = props->Get(i); const Local<Value> value = obj->Get(key); String::Utf8Value keyStr(key); result[std::string(*keyStr)] = Susi::JS::Engine::convertFromJS(value); } return result; } if(jsVal->IsString()){ String::Utf8Value val(jsVal); Susi::Util::Any result{std::string(*val)}; return result; } if(jsVal->IsNumber()){ Susi::Util::Any result{jsVal->ToNumber()->Value()}; return result; } if(jsVal->IsBoolean()){ Susi::Util::Any result{jsVal->ToBoolean()->Value()}; return result; } if(jsVal->IsNativeError()){ String::Utf8Value val(jsVal); Susi::Util::Any result{std::string(*val)}; return result; } if(jsVal->IsUndefined()){ Susi::Util::Any result; return result; } return Susi::Util::Any{"type not known"}; }
void handleException(TryCatch& tc) { Logging::log(Logging::ERROR, "V8 exception:\r\n"); HandleScope handleScope; Handle<Object> exception = tc.Exception()->ToObject(); String::AsciiValue exception_str(exception); Logging::log(Logging::ERROR, " : %s\r\n", *exception_str); /* Handle<Array> names = exception->GetPropertyNames(); for (unsigned int i = 0; i < names->Length(); i++) { std::string strI = Utility::toString((int)i); Logging::log(Logging::ERROR, " %d : %s : %s\r\n", i, *(v8::String::Utf8Value(names->Get(String::New(strI.c_str()))->ToString())), *(v8::String::Utf8Value(exception->Get(names->Get(String::New(strI.c_str()))->ToString())->ToString())) ); } */ Local<Message> message = tc.Message(); Logging::log(Logging::ERROR, "Message: Get: %s\r\n", *(v8::String::Utf8Value( message->Get() ))); Logging::log(Logging::ERROR, "Message: GetSourceLine: %s\r\n", *(v8::String::Utf8Value( message->GetSourceLine() ))); Logging::log(Logging::ERROR, "Message: GetScriptResourceName: %s\r\n", *(v8::String::Utf8Value( message->GetScriptResourceName()->ToString() ))); Logging::log(Logging::ERROR, "Message: GetLineNumber: %d\r\n", message->GetLineNumber() ); Local<Value> stackTrace = tc.StackTrace(); if (!stackTrace.IsEmpty()) { Logging::log(Logging::ERROR, "Stack trace: %s\r\n", *(v8::String::Utf8Value( stackTrace->ToString() ))); printf("\r\n\r\n^Stack trace^: %s\r\n", *(v8::String::Utf8Value( stackTrace->ToString() ))); } else Logging::log(Logging::ERROR, "No stack trace available in C++ handler (see above for possible in-script stack trace)\r\n"); #ifdef SERVER std::string clientMessage = *(v8::String::Utf8Value( message->Get() )); clientMessage += " - "; clientMessage += *(v8::String::Utf8Value( message->GetSourceLine() )); ServerSystem::fatalMessageToClients(clientMessage); #endif // assert(0); throw ScriptException("Bad!"); }
bson encodeObject(const Local<Value> element) { HandleScope scope; bson_buffer bb; bson_buffer_init(&bb); Local<Object> object = element->ToObject(); Local<Array> properties = object->GetPropertyNames(); for (int i = 0; i < properties->Length(); i++) { // get the property name and value Local<Value> prop_name = properties->Get(Integer::New(i)); Local<Value> prop_val = object->Get(prop_name->ToString()); // convert the property name to a c string String::Utf8Value n(prop_name); const char *pname = ToCString(n); // append property using appropriate appender if (prop_val->IsString()) { encodeString(&bb, pname, prop_val); } else if (prop_val->IsInt32()) { encodeInteger(&bb, pname, prop_val); } else if (prop_val->IsNumber()) { encodeNumber(&bb, pname, prop_val); } else if (prop_val->IsBoolean()) { encodeBoolean(&bb, pname, prop_val); } else if (prop_val->IsArray()) { encodeArray(&bb, pname, prop_val); } else if (prop_val->IsObject() && ObjectID::constructor_template->HasInstance(prop_val)) { encodeObjectID(&bb, pname, prop_val); } else if (prop_val->IsObject()) { bson bson(encodeObject(prop_val)); bson_append_bson(&bb, pname, &bson); bson_destroy(&bson); } } bson bson; bson_from_buffer(&bson, &bb); return bson; }
void ContactsPersonProxy::_setEmail(void* userContext, Handle<Value> value) { ContactsPersonProxy *obj = (ContactsPersonProxy*) userContext; if(!value->IsObject()) return; Handle<Object> emailObject = value->ToObject(); Local<Array> emailProperties = emailObject->GetPropertyNames(); for(int i = 0, len = emailProperties->Length(); i < len; i++) { Local<String> allEmailsKey = emailProperties->Get(i)->ToString(); Local<Value> allEmailsValue = emailObject->Get(allEmailsKey); AttributeSubKind::Type subKind = AttributeSubKind::Other; QString allEmailsKeyString = titanium::V8ValueToQString(allEmailsKey).toLower(); if(allEmailsKeyString == "work") { subKind = AttributeSubKind::Work; } else if(allEmailsKeyString == "personal") { subKind = AttributeSubKind::Personal; } else if(allEmailsKeyString == "home") { subKind = AttributeSubKind::Home; } if(!allEmailsValue->IsArray()) return; Local<Array> emails = Local<Array>::Cast(allEmailsValue); for(int i = 0, len = emails->Length(); i < len; i++) { Local<Value> emailValue = emails->Get(Number::New(i)); if(emailValue->IsString() || emailValue->IsNumber()) { obj->setContactDetails(AttributeKind::Email, subKind, emailValue); } else { // Something goes here, throw an error? } } } }
void JsVlcPlayer::callCallback( Callbacks_e callback, std::initializer_list<v8::Local<v8::Value> > list ) { using namespace v8; Isolate* isolate = Isolate::GetCurrent(); HandleScope scope( isolate ); std::vector<v8::Local<v8::Value> > argList; argList.reserve( list.size() ); argList.push_back( String::NewFromUtf8( isolate, callbackNames[callback], v8::String::kInternalizedString ) ); if( list.size() > 0 ) argList.insert( argList.end(), list ); if( !_jsCallbacks[callback].IsEmpty() ) { Local<Function> callbackFunc = Local<Function>::New( isolate, _jsCallbacks[callback] ); callbackFunc->Call( handle(), argList.size() - 1, argList.data() + 1 ); } Local<Object> eventEmitter = getEventEmitter(); Local<Function> emitFunction = v8::Local<v8::Function>::Cast( eventEmitter->Get( String::NewFromUtf8( isolate, "emit", v8::String::kInternalizedString ) ) ); emitFunction->Call( eventEmitter, argList.size(), argList.data() ); }