void BookWrap::Setter(uint32_t index, Local<Value> value, const PropertyCallbackInfo<Value>& info) { Isolate* isolate = info.GetIsolate(); HandleScope scope(isolate); BookWrap* bw = ObjectWrap::Unwrap<BookWrap>(info.This()); Book* b = bw->m_book; if (value->IsArray()) { if (index < b->size()) { Local<v8::Array> arr = Local<v8::Array>::Cast(value); if (arr->Length() == 3) { const String::Utf8Value firstname(arr->Get(0)->ToString()); const String::Utf8Value lastname(arr->Get(1)->ToString()); const time_t birthday = time_t(0.001*(*arr->Get(2))->NumberValue()); Person *p = (*b)[index]; p->firstname(*firstname); p->lastname(*lastname); p->birthday(birthday); } else { isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Three elements expected"))); info.GetReturnValue().SetUndefined(); return; } } if (index == b->size()) { Local<v8::Array> arr = Local<v8::Array>::Cast(value); if (arr->Length() == 3) { const String::Utf8Value firstname(arr->Get(0)->ToString()); const String::Utf8Value lastname(arr->Get(1)->ToString()); const time_t birthday = time_t(0.001*(*arr->Get(2))->NumberValue()); Person *p = new Person(); p->firstname(*firstname); p->lastname(*lastname); p->birthday(birthday); b->add(p); } else { isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Three elements expected"))); info.GetReturnValue().SetUndefined(); return; } } else { isolate->ThrowException(Exception::RangeError(String::NewFromUtf8(isolate, "Invalid index"))); info.GetReturnValue().SetUndefined(); return; } } else { isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Object expected"))); info.GetReturnValue().SetUndefined(); return; } info.GetReturnValue().SetUndefined(); }
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"}; }
// Check if a global appmetrics agent module is already loaded. // This is actually searching the module cache for a module with filepath // ending .../appmetrics/launcher.js static bool isGlobalAgentAlreadyLoaded(Handle<Object> module) { //Nan::HandleScope scope; Local<Object> cache = getRequireCache(module); Local<Array> props = cache->GetOwnPropertyNames(); if (props->Length() > 0) { for (uint32_t i=0; i<props->Length(); i++) { Local<Value> entry = props->Get(i); if (entry->IsString() && isAppMetricsFile("launcher.js", toStdString(entry->ToString()))) { return true; } } } return false; }
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? } } } }
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())); }
Handle<Value> TiTitaniumObject::_globalInclude(void*, TiObject*, const Arguments& args) { if (!args.Length()) { return Undefined(); } bool error = false; if (args[0]->IsArray()) { Local<Array> ids = Local<Array>::Cast(args[0]); uint32_t count = ids->Length(); string parentFolder = *String::Utf8Value(args[1]); for (uint32_t i = 0; i < count; i++) { string id = *String::Utf8Value(ids->Get(i)); Handle<Value> result = includeJavaScript(id, parentFolder, &error); if (error) return result; } } else { for (uint32_t i = 0; i < args.Length(); i++) { string id = *String::Utf8Value(args[i]); Handle<Value> result = includeJavaScript(id, rootFolder, &error); if (error) return result; } } return Undefined(); }
/* Set the shared PRU RAM to an input array * Takes an integer array as input, writes it to PRU shared memory * Not much error checking here, don't pass in large arrays or seg faults will happen * TODO: error checking and allow user to select range to set */ Handle<Value> setSharedRAM(const Arguments& args) { HandleScope scope; //Check we have a single argument if (args.Length() != 1) { ThrowException(Exception::TypeError(String::New("Wrong number of arguments"))); return scope.Close(Undefined()); } //Check that it's an array if (!args[0]->IsArray()) { ThrowException(Exception::TypeError(String::New("Argument must be array"))); return scope.Close(Undefined()); } //Get array Local<Array> a = Array::Cast(*args[0]); //Iterate over array for (unsigned int i = 0; i<a->Length(); i++) { //Get element and check it's numeric Local<Value> element = a->Get(i); if (!element->IsNumber()) { ThrowException(Exception::TypeError(String::New("Array must be integer"))); return scope.Close(Undefined()); } //Set corresponding memory bytes sharedMem_int[OFFSET_SHAREDRAM + i] = (unsigned int) element->NumberValue(); } //Return nothing return scope.Close(Undefined()); };
Ti::TiValue Ti::TiViewProxy::remove(Ti::TiValue value) { Ti::TiValue val; val.setUndefined(); Ti::TiViewProxy *childProxy = static_cast<Ti::TiViewProxy*>(value.toProxy()); if(!_childViewsProxies.contains(childProxy)) return val; Ti::TiView* childView = childProxy->getView(); Ti::TiView* thisView = getView(); childProxy->makeWeak(); thisView->remove(childView); _childViewsProxies.removeOne(childProxy); childProxy->_parentProxy = NULL; Local<Value> children = _jsObject->Get(String::New("children")); if(!children.IsEmpty() && !children->IsUndefined()) { Local<Array> array = Local<Array>::Cast(children); for(int i = 0, len = array->Length(); i < len; i++) { if(array->Get(i) == value.toJSValue()) { array->Delete(i); break; } } } return val; }
jsvalue JsEngine::WrappedFromV8(Handle<Object> obj) { jsvalue v; if (js_object_marshal_type == JSOBJECT_MARSHAL_TYPE_DYNAMIC) { v.type = JSVALUE_TYPE_WRAPPED; v.length = 0; // A Persistent<Object> is exactly the size of an IntPtr, right? // If not we're in deep deep trouble (on IA32 and AMD64 should be). // We should even cast it to void* because C++ doesn't allow to put // it in a union: going scary and scarier here. v.value.ptr = new Persistent<Object>(Persistent<Object>::New(obj)); } else { v.type = JSVALUE_TYPE_DICT; Local<Array> names = obj->GetOwnPropertyNames(); v.length = names->Length(); jsvalue* values = new jsvalue[v.length * 2]; if (values != NULL) { for(int i = 0; i < v.length; i++) { int indx = (i * 2); Local<Value> key = names->Get(i); values[indx] = AnyFromV8(key); values[indx+1] = AnyFromV8(obj->Get(key)); } v.value.arr = values; } } return v; }
static Handle<Value> waitForEvents(const Arguments& args) { if (!args[0]->IsArray()) ThrowException(Exception::Error(String::New("CL_INVALID_VALUE"))); Local<Array> eventsArray = Array::Cast(*args[0]); std::vector<const EventWrapper*> events; for (int i=0; i<eventsArray->Length(); i++) { Local<Object> obj = eventsArray->Get(i)->ToObject(); EventWrapper *e = ObjectWrap::Unwrap<Event>(obj)->getEventWrapper(); events.push_back(e); } cl_int ret = ContextWrapper::waitForEvents(events); if (ret != CL_SUCCESS) { WEBCL_COND_RETURN_THROW(CL_INVALID_VALUE); WEBCL_COND_RETURN_THROW(CL_INVALID_CONTEXT); WEBCL_COND_RETURN_THROW(CL_INVALID_EVENT); WEBCL_COND_RETURN_THROW(CL_EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST); 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 Undefined(); }
jobjectArray JNIV8Object::jniGetV8Keys(JNIEnv *env, jobject obj, jboolean ownOnly) { JNIV8Object_PrepareJNICall(JNIV8Object, Object, nullptr); MaybeLocal<Array> maybeArrayRef = ownOnly ? localRef->GetOwnPropertyNames(context) : localRef->GetPropertyNames(); if(maybeArrayRef.IsEmpty()) { ptr->getEngine()->forwardV8ExceptionToJNI(&try_catch); return nullptr; } Local<Array> arrayRef = maybeArrayRef.ToLocalChecked(); Local<Value> valueRef; jobjectArray result = nullptr; jstring string; std::string test; for(uint32_t i=0,n=arrayRef->Length(); i<n; i++) { MaybeLocal<Value> maybeValueRef = arrayRef->Get(context, i); if(!maybeValueRef.ToLocal<Value>(&valueRef)) { ptr->getEngine()->forwardV8ExceptionToJNI(&try_catch); return nullptr; } string = JNIV8Marshalling::v8string2jstring(valueRef->ToString(isolate)); if(!result) { result = env->NewObjectArray(n, _jniString.clazz, string); } else { env->SetObjectArrayElement(result, i, string); } env->DeleteLocalRef(string); } return result; }
static std::string toStdString(Local<String> s) { char *buf = new char[s->Length() + 1]; s->WriteUtf8(buf); std::string result(buf); delete[] buf; return result; }
void encodeArray(bson_buffer *bb, const char *name, const Local<Value> element) { Local<Array> a = Array::Cast(*element); bson_buffer *arr = bson_append_start_array(bb, name); for (int i = 0, l=a->Length(); i < l; i++) { Local<Value> val = a->Get(Number::New(i)); stringstream keybuf; string keyval; keybuf << i << endl; keybuf >> keyval; if (val->IsString()) { encodeString(arr, keyval.c_str(), val); } else if (val->IsInt32()) { encodeInteger(arr, keyval.c_str(), val); } else if (val->IsNumber()) { encodeNumber(arr, keyval.c_str(), val); } else if (val->IsBoolean()) { encodeBoolean(arr, keyval.c_str(), val); } else if (val->IsArray()) { encodeArray(arr, keyval.c_str(), val); } else if (val->IsObject()) { bson bson(encodeObject(val)); bson_append_bson(arr, keyval.c_str(), &bson); bson_destroy(&bson); } } bson_append_finish_object(arr); }
static void TitaniumCountlyAndroidMessaging_dispose() { HandleScope scope; if (bindingCache.IsEmpty()) { return; } Local<Array> propertyNames = bindingCache->GetPropertyNames(); uint32_t length = propertyNames->Length(); for (uint32_t i = 0; i < length; ++i) { String::Utf8Value binding(propertyNames->Get(i)); int bindingLength = binding.length(); titanium::bindings::BindEntry *extBinding = ::TitaniumCountlyAndroidMessagingBindings::lookupGeneratedInit(*binding, bindingLength); if (extBinding && extBinding->dispose) { extBinding->dispose(); } } bindingCache.Dispose(); bindingCache = Persistent<Object>(); }
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(); }
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); }
std::vector<uint8_t> JSZCluster::addArgument(v8::Local<v8::Value> value, const std::shared_ptr<ClusterCmdParamsBase> &cmdParam) { if (value->IsUint32()) { return cmdParam->getType().getRaw(value->ToUint32()->Value()); } if (value->IsInt32()) { return cmdParam->getType().getRaw(value->ToInt32()->Value()); } if (value->IsString()) { String::Utf8Value utf8Value(value); return cmdParam->getType().getRaw(*utf8Value); } if (value->IsArray()) { Local<Array> array = value.As<Array>(); std::vector<std::string> strArray; for (uint32_t index = 0; index < array->Length(); index++) { String::Utf8Value utf8Value(array->Get(index)); strArray.push_back(*utf8Value); } return cmdParam->getType().getRaw(strArray); } stringstream stream; stream << "To " << EXECUTE_CMD_BY_ID << " it is passed an invalid argument instead of type " << cmdParam->getZCLDataType(); throw JSException(stream.str()); }
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); }
void TargetCallback(Isolate* isolate, Persistent<Object>* target, WeakRef* arg) { HandleScope scope; if(!arg->target.IsNearDeath()) { return; } Local<Object> fnthis = Local<Object>::New(Isolate::GetCurrent(), arg->target); Handle<Value> argv[1]; argv[0] = fnthis; // invoke any listening callbacks Local<Array> callbacks = Local<Array>::New(Isolate::GetCurrent(), arg->callbacks); uint32_t len = callbacks->Length(); for (uint32_t i = 0; i < len; i++) { Handle<Function> cb = Handle<Function>::Cast(callbacks->Get(i)); TryCatch try_catch; cb->Call(fnthis, 1, argv); if (try_catch.HasCaught()) { ThrowException(String::New("TargetCallback")); } } arg->target.Dispose(); arg->target.Clear(); arg->callbacks.Dispose(); arg->callbacks.Clear(); }
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; }
BSONObj v8ToMongo( v8::Handle<v8::Object> o ){ BSONObjBuilder b; v8::Handle<v8::String> idName = String::New( "_id" ); if ( o->HasRealNamedProperty( idName ) ){ v8ToMongoElement( b , idName , "_id" , o->Get( idName ) ); } Local<v8::Array> names = o->GetPropertyNames(); for ( unsigned int i=0; i<names->Length(); i++ ){ v8::Local<v8::String> name = names->Get(v8::Integer::New(i) )->ToString(); if ( o->GetPrototype()->IsObject() && o->GetPrototype()->ToObject()->HasRealNamedProperty( name ) ) continue; v8::Local<v8::Value> value = o->Get( name ); const string sname = toSTLString( name ); if ( sname == "_id" ) continue; v8ToMongoElement( b , name , sname , value ); } return b.obj(); }
// 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)); } }
Local<String> V8EngineProxy::GetErrorMessage(TryCatch &tryCatch) { auto msg = tryCatch.Exception()->ToString(); auto stack = tryCatch.StackTrace(); bool showStackMsg = !stack.IsEmpty() && !stack->IsUndefined(); Local<String> stackStr; if (showStackMsg) { stackStr = stack->ToString(); // ... detect if the start of the stack message is the same as the exception message, then remove it (seems to happen when managed side returns an error) ... if (stackStr->Length() >= msg->Length()) { uint16_t* ss = new uint16_t[stackStr->Length() + 1]; stack->ToString()->Write(ss); auto subStackStr = NewSizedUString(ss, msg->Length()); auto stackPartStr = NewSizedUString(ss + msg->Length(), stackStr->Length() - msg->Length()); delete[] ss; if (msg->Equals(subStackStr)) stackStr = stackPartStr; } } msg = msg->Concat(msg, NewString("\r\n")); msg = msg->Concat(msg, NewString(" Line: ")); auto line = NewInteger(tryCatch.Message()->GetLineNumber())->ToString(); msg = msg->Concat(msg, line); msg = msg->Concat(msg, NewString(" Column: ")); auto col = NewInteger(tryCatch.Message()->GetStartColumn())->ToString(); msg = msg->Concat(msg, col); msg = msg->Concat(msg, NewString("\r\n")); if (showStackMsg) { msg = msg->Concat(msg, NewString(" Stack: ")); msg = msg->Concat(msg, stackStr); msg = msg->Concat(msg, NewString("\r\n")); } return msg; }
/** * @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(); }
int SerializePart(google::protobuf::Message *message, Handle<Object> subj) { NanScope(); // get a reflection const Reflection *r = message->GetReflection(); const Descriptor *d = message->GetDescriptor(); // build a list of required properties vector<string> required; for (int i = 0; i < d->field_count(); i++) { const FieldDescriptor *field = d->field(i); if (field->is_required()) required.push_back(field->name()); } // build a reflection // get properties of passed object Local<Array> properties = subj->GetPropertyNames(); uint32_t len = properties->Length(); // check that all required properties are present for (uint32_t i = 0; i < required.size(); i++) { Handle<String> key = String::New(required.at(i).c_str()); if (!subj->Has(key)) return -1; } for (uint32_t i = 0; i < len; i++) { Local<Value> property = properties->Get(i); Local<String> property_s = property->ToString(); if (*property_s == NULL) continue; String::Utf8Value temp(property); std::string propertyName = std::string(*temp); const FieldDescriptor *field = d->FindFieldByName(propertyName); if (field == NULL) continue; Local<Value> val = subj->Get(property); if (field->is_repeated()) { if (!val->IsArray()) continue; Handle<Array> array = val.As<Array>(); int len = array->Length(); for (int i = 0; i < len; i++) SerializeField(message, r, field, array->Get(i)); } else { SerializeField(message, r, field, val); } } return 0; }
SV* V8Context::object2blessed(Handle<Object> obj) { char package[128]; snprintf( package, 128, "%s%s::N%d", bless_prefix.c_str(), *String::AsciiValue(obj->Get(String::New("__perlPackage"))->ToString()), number ); HV *stash = gv_stashpv(package, 0); if (!stash) { Local<Object> prototype = obj->GetPrototype()->ToObject(); stash = gv_stashpv(package, GV_ADD); Local<Array> properties = prototype->GetPropertyNames(); for (int i = 0; i < properties->Length(); i++) { Local<String> name = properties->Get(i)->ToString(); Local<Value> property = prototype->Get(name); if (!property->IsFunction()) continue; Local<Function> fn = Local<Function>::Cast(property); CV *code = newXS(NULL, v8method, __FILE__); V8ObjectData *data = new V8FunctionData(this, fn, (SV*)code); GV* gv = (GV*)*hv_fetch(stash, *String::AsciiValue(name), name->Length(), TRUE); gv_init(gv, stash, *String::AsciiValue(name), name->Length(), GV_ADDMULTI); /* vivify */ my_gv_setsv(aTHX_ gv, (SV*)code); } } SV* rv = newSV(0); SV* sv = newSVrv(rv, package); V8ObjectData *data = new V8ObjectData(this, obj, sv); sv_setiv(sv, PTR2IV(data)); return rv; }
void V8BuilderPolicy::AppendToList(type const & var) { Nan::HandleScope scope; Local<Value> object(Nan::New(object_)); assert(object->IsArray()); Local<Array> arr = Local<Array>::Cast(object); arr->Set(arr->Length(), Nan::New(var)); }
static Handle<Value> createContext(const Arguments& args) { HandleScope scope; if (!args[0]->IsArray()) ThrowException(Exception::Error(String::New("CL_INVALID_VALUE"))); if (!args[1]->IsArray()) ThrowException(Exception::Error(String::New("CL_INVALID_VALUE"))); Local<Array> propertiesArray = Array::Cast(*args[0]); cl_context_properties *properties = new cl_context_properties[propertiesArray->Length()+1]; for (int i=0; i<propertiesArray->Length(); i+=2) { properties[i] = (cl_context_properties)propertiesArray->Get(i)->NumberValue(); Local<Object> obj = propertiesArray->Get(i+1)->ToObject(); Platform *p = ObjectWrap::Unwrap<Platform>(obj); properties[i+1] = (cl_context_properties)p->getPlatformWrapper()->getWrapped(); } properties[propertiesArray->Length()] = 0; Local<Array> deviceArray = Array::Cast(*args[1]); std::vector<DeviceWrapper*> devices; for (int i=0; i<deviceArray->Length(); i++) { Local<Object> obj = deviceArray->Get(i)->ToObject(); Device *d = ObjectWrap::Unwrap<Device>(obj); devices.push_back(d->getDeviceWrapper()); } ContextWrapper *cw = 0; cl_int ret = ContextWrapper::createContext (properties, devices, 0, 0, &cw); delete[] properties; if (ret != CL_SUCCESS) { WEBCL_COND_RETURN_THROW(CL_INVALID_PLATFORM); WEBCL_COND_RETURN_THROW(CL_INVALID_PROPERTY); WEBCL_COND_RETURN_THROW(CL_INVALID_VALUE); WEBCL_COND_RETURN_THROW(CL_INVALID_DEVICE); WEBCL_COND_RETURN_THROW(CL_DEVICE_NOT_AVAILABLE); 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(CLContext::New(cw)->handle_); }
Handle<Value> EnvWrap::open(const Arguments& args) { HandleScope scope; int rc; int flags = 0; // Get the wrapper EnvWrap *ew = ObjectWrap::Unwrap<EnvWrap>(args.This()); if (!ew->env) { ThrowException(Exception::Error(String::New("The environment is already closed."))); return Undefined(); } Local<Object> options = args[0]->ToObject(); Local<String> path = options->Get(String::NewSymbol("path"))->ToString(); rc = applyUint32Setting(&mdb_env_set_maxdbs, ew->env, options, 1, "maxDbs"); if (rc != 0) { ThrowException(Exception::Error(String::New(mdb_strerror(rc)))); return Undefined(); } rc = applyUint32Setting(&mdb_env_set_mapsize, ew->env, options, 10485760, "mapSize"); if (rc != 0) { ThrowException(Exception::Error(String::New(mdb_strerror(rc)))); return Undefined(); } // TODO: expose mdb_env_set_maxreaders // NOTE: MDB_FIXEDMAP is not exposed here since it is "highly experimental" + it is irrelevant for this use case // NOTE: MDB_NOTLS is not exposed here because it is irrelevant for this use case, as node will run all this on a single thread anyway setFlagFromValue(&flags, MDB_NOSUBDIR, "noSubdir", false, options); setFlagFromValue(&flags, MDB_RDONLY, "readOnly", false, options); setFlagFromValue(&flags, MDB_WRITEMAP, "useWritemap", false, options); setFlagFromValue(&flags, MDB_NOMETASYNC, "noMetaSync", false, options); setFlagFromValue(&flags, MDB_NOSYNC, "noSync", false, options); setFlagFromValue(&flags, MDB_MAPASYNC, "mapAsync", false, options); int l = path->Length(); char *cpath = new char[l + 1]; path->WriteAscii(cpath); cpath[l] = 0; // TODO: make file attributes configurable rc = mdb_env_open(ew->env, cpath, flags, 0664); if (rc != 0) { mdb_env_close(ew->env); ew->env = NULL; ThrowException(Exception::Error(String::New(mdb_strerror(rc)))); return Undefined(); } return Undefined(); }
void Ti::TiProxy::initWithObject(Handle<Object> obj) { HandleScope scope; Local<Array> props = obj->GetPropertyNames(); for(int i = 0, len = props->Length(); i < len; i++) { Local<String> key = props->Get(i)->ToString(); Local<Value> val = obj->Get(key); _jsObject->Set(key, val); } }