void test_Exception() { HandleScope handle_scope; Persistent<Context> context = Context::New(); Handle<Script> script = Script::New(String::New("function foo(x) { throw x; };")); Context::Scope scope(context); TryCatch trycatch; Handle<Value> v = script->Run(); do_check_true(!v.IsEmpty()); do_check_true(!trycatch.HasCaught()); Handle<Function> fn = context->Global()->Get(String::NewSymbol("foo")).As<Function>(); do_check_true(!fn.IsEmpty()); Local<Value> args[1] = { Integer::New(4) }; v = fn->Call(context->Global(), 1, args); do_check_true(v.IsEmpty()); do_check_true(trycatch.HasCaught()); Handle<Value> exn = trycatch.Exception(); do_check_true(exn->IsInt32()); do_check_eq(exn->Int32Value(), 4); context.Dispose(); }
/* * This is meant to run one time when the match creator is initialized. */ void customScriptInit() { Context::Scope context_scope(_script->getContext()); HandleScope handleScope; Persistent<Object> plugin = getPlugin(); Handle<String> initStr = String::New("init"); if (plugin->Has(initStr) == false) { throw HootException("Error finding 'init' function."); } Handle<v8::Value> value = plugin->Get(initStr); if (value->IsFunction() == false) { throw HootException("init is not a function."); } Handle<v8::Function> func = v8::Handle<v8::Function>::Cast(value); Handle<Value> jsArgs[1]; int argc = 0; HandleScope scope; assert(_map.get()); OsmMapPtr copiedMap(new OsmMap(_map)); jsArgs[argc++] = OsmMapJs::create(copiedMap); func->Call(plugin, argc, jsArgs); //this is meant to have been set externally in a js rules file _searchRadius = getNumber(plugin, "searchRadius", -1.0, 15.0); }
MatchCreator::Description ScriptMatchCreator::_getScriptDescription(QString path) const { MatchCreator::Description result; result.experimental = true; shared_ptr<PluginContext> script(new PluginContext()); HandleScope handleScope; Context::Scope context_scope(script->getContext()); script->loadScript(path, "plugin"); Persistent<Object> plugin = ScriptMatchVisitor::getPlugin(script); Handle<String> descriptionStr = String::New("description"); if (plugin->Has(descriptionStr)) { Handle<v8::Value> value = plugin->Get(descriptionStr); result.description = toCpp<QString>(value); } Handle<String> experimentalStr = String::New("experimental"); if (plugin->Has(experimentalStr)) { Handle<v8::Value> value = plugin->Get(experimentalStr); result.experimental = toCpp<bool>(value); } QFileInfo fi(path); result.className = (QString::fromStdString(className()) + "," + fi.fileName()).toStdString(); return result; }
/* * Class: org_appcelerator_kroll_runtime_v8_V8Runtime * Method: nativeRunModule * Signature: (Ljava/lang/String;Ljava/lang/String;)V */ JNIEXPORT void JNICALL Java_org_appcelerator_kroll_runtime_v8_V8Runtime_nativeRunModule (JNIEnv *env, jobject self, jstring source, jstring filename, jobject activityProxy) { ENTER_V8(V8Runtime::globalContext); titanium::JNIScope jniScope(env); if (moduleObject.IsEmpty()) { moduleObject = Persistent<Object>::New( V8Runtime::krollGlobalObject->Get(String::New("Module"))->ToObject()); runModuleFunction = Persistent<Function>::New( Handle<Function>::Cast(moduleObject->Get(String::New("runModule")))); } Handle<Value> jsSource = TypeConverter::javaStringToJsString(source); Handle<Value> jsFilename = TypeConverter::javaStringToJsString(filename); Handle<Value> jsActivity = TypeConverter::javaObjectToJsValue(activityProxy); Handle<Value> args[] = { jsSource, jsFilename, jsActivity }; TryCatch tryCatch; runModuleFunction->Call(moduleObject, 3, args); if (tryCatch.HasCaught()) { V8Util::openJSErrorDialog(tryCatch); V8Util::reportException(tryCatch, true); } }
TEST(ImageResourceTest, SuccessfulRevalidationSvg) { KURL url(ParsedURLString, "http://127.0.0.1:8000/foo"); ImageResource* imageResource = ImageResource::create(ResourceRequest(url)); Persistent<MockImageResourceClient> client = new MockImageResourceClient(imageResource); receiveResponse(imageResource, url, "image/svg+xml", svgImage()); EXPECT_FALSE(imageResource->errorOccurred()); ASSERT_TRUE(imageResource->hasImage()); EXPECT_FALSE(imageResource->getImage()->isNull()); EXPECT_EQ(1, client->imageChangedCount()); EXPECT_TRUE(client->notifyFinishedCalled()); EXPECT_FALSE(imageResource->getImage()->isBitmapImage()); EXPECT_EQ(200, imageResource->getImage()->width()); EXPECT_EQ(200, imageResource->getImage()->height()); imageResource->setRevalidatingRequest(ResourceRequest(url)); ResourceResponse response; response.setURL(url); response.setHTTPStatusCode(304); imageResource->responseReceived(response, nullptr); EXPECT_FALSE(imageResource->errorOccurred()); ASSERT_TRUE(imageResource->hasImage()); EXPECT_FALSE(imageResource->getImage()->isNull()); EXPECT_EQ(1, client->imageChangedCount()); EXPECT_TRUE(client->notifyFinishedCalled()); EXPECT_FALSE(imageResource->getImage()->isBitmapImage()); EXPECT_EQ(200, imageResource->getImage()->width()); EXPECT_EQ(200, imageResource->getImage()->height()); }
TEST(ImageResourceTest, DecodedDataRemainsWhileHasClients) { ImageResource* cachedImage = ImageResource::create(ResourceRequest()); cachedImage->setStatus(Resource::Pending); Persistent<MockImageResourceClient> client = new MockImageResourceClient(cachedImage); // Send the image response. cachedImage->responseReceived(ResourceResponse(KURL(), "multipart/x-mixed-replace", 0, nullAtom, String()), nullptr); Vector<unsigned char> jpeg = jpegImage(); cachedImage->responseReceived(ResourceResponse(KURL(), "image/jpeg", jpeg.size(), nullAtom, String()), nullptr); cachedImage->appendData(reinterpret_cast<const char*>(jpeg.data()), jpeg.size()); cachedImage->finish(); ASSERT_FALSE(cachedImage->errorOccurred()); ASSERT_TRUE(cachedImage->hasImage()); ASSERT_FALSE(cachedImage->getImage()->isNull()); ASSERT_TRUE(client->notifyFinishedCalled()); // The prune comes when the ImageResource still has clients. The image should not be deleted. cachedImage->prune(); ASSERT_TRUE(cachedImage->hasClientsOrObservers()); ASSERT_TRUE(cachedImage->hasImage()); ASSERT_FALSE(cachedImage->getImage()->isNull()); // The ImageResource no longer has clients. The image should be deleted by prune. client->removeAsClient(); cachedImage->prune(); ASSERT_FALSE(cachedImage->hasClientsOrObservers()); ASSERT_FALSE(cachedImage->hasImage()); ASSERT_TRUE(cachedImage->getImage()->isNull()); }
void test_obj_setprop() { HandleScope handle_scope; Persistent<Context> context = Context::New(); Context::Scope context_scope(context); Handle<Object> obj = Object::New(); Handle<String> k = String::New("someprop"); Handle<String> v = String::New("somevalue"); obj->Set(k, v); Handle<Value> v2 = obj->Get(k); String::AsciiValue vs(v); String::AsciiValue vs2(v2); do_check_eq(vs.length(), vs2.length()); do_check_eq(0, strcmp(*vs,*vs2)); context.Dispose(); }
void Init (Handle<Object> target) { initQueues(); freeThreadsQueue= nuQueue(-3); //闲置线程队列的 id为 -3 freeJobsQueue= nuQueue(-4); //闲置任务队列的id 为-4 HandleScope scope; //static bool IsActive () //将返回当前V8的运行实例是否加锁 useLocker= v8::Locker::IsActive(); target->Set(String::NewSymbol("create"), FunctionTemplate::New(Create)->GetFunction()); target->Set(String::NewSymbol("createPool"), Script::Compile(String::New(kCreatePool_js))->Run()->ToObject()); //target->Set(String::NewSymbol("JASON"), Script::Compile(String::New(kJASON_js))->Run()->ToObject()); //设置js访问线程id的属性名为‘id’ id_symbol= Persistent<String>::New(String::NewSymbol("id")); //定义 threadTemplate 的一些属性 threadTemplate= Persistent<ObjectTemplate>::New(ObjectTemplate::New()); threadTemplate->SetInternalFieldCount(1); threadTemplate->Set(id_symbol, Integer::New(0)); threadTemplate->Set(String::NewSymbol("eval"), FunctionTemplate::New(Eval)); //threadTemplate->Set(String::NewSymbol("load"), FunctionTemplate::New(Load)); threadTemplate->Set(String::NewSymbol("emit"), FunctionTemplate::New(processEmit)); threadTemplate->Set(String::NewSymbol("destroy"), FunctionTemplate::New(Destroy)); }
// initialize a JS wrapper around this object void NodeFSEvents::Initialize(Handle<Object> target) { HandleScope scope; emit_sym = NODE_PSYMBOL("emit"); change_sym = NODE_PSYMBOL("fsevent"); Local<FunctionTemplate> t = FunctionTemplate::New(NodeFSEvents::New); constructor_template = Persistent<FunctionTemplate>::New(t); constructor_template->InstanceTemplate()->SetInternalFieldCount(1); constructor_template->SetClassName(String::NewSymbol("FSEvents")); Local<Function> constructor = constructor_template->GetFunction(); constructor->Set(String::New("kFSEventStreamEventFlagNone"), Integer::New(0x00000000)); constructor->Set(String::New("kFSEventStreamEventFlagMustScanSubDirs"), Integer::New(0x00000001)); constructor->Set(String::New("kFSEventStreamEventFlagUserDropped"), Integer::New(0x00000002)); constructor->Set(String::New("kFSEventStreamEventFlagKernelDropped"), Integer::New(0x00000004)); constructor->Set(String::New("kFSEventStreamEventFlagEventIdsWrapped"), Integer::New(0x00000008)); constructor->Set(String::New("kFSEventStreamEventFlagHistoryDone"), Integer::New(0x00000010)); constructor->Set(String::New("kFSEventStreamEventFlagRootChanged"), Integer::New(0x00000020)); constructor->Set(String::New("kFSEventStreamEventFlagMount"), Integer::New(0x00000040)); constructor->Set(String::New("kFSEventStreamEventFlagUnmount"), Integer::New(0x00000080)); constructor->Set(String::New("kFSEventStreamEventFlagItemCreated"), Integer::New(0x00000100)); constructor->Set(String::New("kFSEventStreamEventFlagItemRemoved"), Integer::New(0x00000200)); constructor->Set(String::New("kFSEventStreamEventFlagItemInodeMetaMod"), Integer::New(0x00000400)); constructor->Set(String::New("kFSEventStreamEventFlagItemRenamed"), Integer::New(0x00000800)); constructor->Set(String::New("kFSEventStreamEventFlagItemModified"), Integer::New(0x00001000)); constructor->Set(String::New("kFSEventStreamEventFlagItemFinderInfoMod"), Integer::New(0x00002000)); constructor->Set(String::New("kFSEventStreamEventFlagItemChangeOwner"), Integer::New(0x00004000)); constructor->Set(String::New("kFSEventStreamEventFlagItemXattrMod"), Integer::New(0x00008000)); constructor->Set(String::New("kFSEventStreamEventFlagItemIsFile"), Integer::New(0x00010000)); constructor->Set(String::New("kFSEventStreamEventFlagItemIsDir"), Integer::New(0x00020000)); constructor->Set(String::New("kFSEventStreamEventFlagItemIsSymlink"), Integer::New(0x00040000)); target->Set(String::NewSymbol("FSEvents"), constructor); }
Handle<Value> HashTable::Put(const Arguments& args) { HandleScope scope; HashTable *obj = ObjectWrap::Unwrap<HashTable>(args.This()); Local<Value> key = Local<Value>(args[0]); Local<Value> value = Local<Value>(args[1]); String::AsciiValue keyStr(key); MapType::const_iterator itr = obj->map.find(std::string(*keyStr)); //overwriting an existing value if(itr != obj->map.end()) { Persistent<Value> oldValue = itr->second; oldValue.Dispose(); //release the handle to the GC } Persistent<Value> persistent = Persistent<Value>::New(value); obj->map.insert(std::pair<std::string, Persistent<Value> >(std::string(*keyStr), persistent)); //Return undefined return scope.Close(Local<Value>()); }
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 NovaNode::DoneWithSuspectCallback(Persistent<Value> suspect, void *paramater) { Suspect *s = static_cast<Suspect*>(paramater); delete s; suspect.ClearWeak(); suspect.Dispose(); suspect.Clear(); }
extern "C" Handle<Value> execute_string(Persistent<Context> context, const char* s, bool* is_exception) { // Create a stack-allocated handle scope. HandleScope handle_scope; // Enter the created context for compiling and // running the hello world script. Context::Scope context_scope(context); // Create a string containing the JavaScript source code. Handle<String> source = String::New(s); // Compile it Handle<Script> script = Script::Compile(source); // try-catch handler TryCatch trycatch; // Run it Persistent<Value> result = Persistent<Value>::New(script->Run()); // Script->Run() returns an empty handle if the code threw an exception if (result.IsEmpty()) { *is_exception = true; Handle<Value> exception = trycatch.Exception(); // String::AsciiValue exception_str(exception); return Persistent<Value>::New(exception); } return result; }
void test_BasicCall() { HandleScope handle_scope; Handle<ObjectTemplate> templ = ObjectTemplate::New(); Handle<FunctionTemplate> fnT = v8::FunctionTemplate::New(AddOne); templ->Set("AddOne", fnT); Persistent<Context> context = Context::New(NULL, templ); Context::Scope context_scope(context); Local<Value> addone = context->Global()->Get(String::New("AddOne")); do_check_true(!addone.IsEmpty()); do_check_true(!addone->IsUndefined()); do_check_true(addone->IsObject()); do_check_true(addone->IsFunction()); Local<Function> fn = addone.As<Function>(); do_check_eq(fn, fnT->GetFunction()); Local<Number> n = Number::New(0.5); Handle<Value> args[] = { n }; Local<Value> v = fn->Call(context->Global(), 1, args); do_check_true(!v.IsEmpty()); do_check_true(v->IsNumber()); Local<Number> n2 = v->ToNumber(); do_check_eq(n2->Value(), 1.5); context.Dispose(); }
void test_WriteAscii() { HandleScope handle_scope; Persistent<Context> context = Context::New(); Context::Scope context_scope(context); char TEST_STRING[] = "this is a UTF-8 test! This is pi: π"; int TEST_LENGTH = strlen(TEST_STRING); Handle<String> str = String::New(TEST_STRING); char* buf = new char[TEST_LENGTH * 2]; // Iterate over the entire string and use it as the start. int EXPECTED_LENGTH = TEST_LENGTH - 1; // We should drop the UTF-8 char. for (int start = 0; start < TEST_LENGTH; start++) { // Fill the buffer with 'a' to ensure there are no NULLs to start with. fill_string(buf, 'a', TEST_LENGTH * 2); int copied = str->WriteAscii(buf, start, TEST_LENGTH * 2); do_check_eq(copied, EXPECTED_LENGTH - start); do_check_eq(strlen(buf), EXPECTED_LENGTH - start); } delete[] buf; context.Dispose(); }
void ScanHelper_initOnLoad(Handle<Object> target) { Persistent<Object> scanObj = Persistent<Object>(Object::New()); Persistent<String> scanKey = Persistent<String>(String::NewSymbol("Scan")); target->Set(scanKey, scanObj); DEFINE_JS_FUNCTION(scanObj, "create", DBScanHelper_wrapper); Persistent<Object> ScanHelper = Persistent<Object>(Object::New()); Persistent<Object> ScanFlags = Persistent<Object>(Object::New()); scanObj->Set(Persistent<String>(String::NewSymbol("helper")), ScanHelper); scanObj->Set(Persistent<String>(String::NewSymbol("flags")), ScanFlags); WRAP_CONSTANT(ScanFlags, SF_TupScan); WRAP_CONSTANT(ScanFlags, SF_DiskScan); WRAP_CONSTANT(ScanFlags, SF_OrderBy); WRAP_CONSTANT(ScanFlags, SF_OrderByFull); WRAP_CONSTANT(ScanFlags, SF_Descending); WRAP_CONSTANT(ScanFlags, SF_ReadRangeNo); WRAP_CONSTANT(ScanFlags, SF_MultiRange); WRAP_CONSTANT(ScanFlags, SF_KeyInfo); DEFINE_JS_INT(ScanHelper, "table_record", SCAN_TABLE_RECORD); DEFINE_JS_INT(ScanHelper, "index_record", SCAN_INDEX_RECORD); DEFINE_JS_INT(ScanHelper, "lock_mode", SCAN_LOCK_MODE); DEFINE_JS_INT(ScanHelper, "bounds", SCAN_BOUNDS); DEFINE_JS_INT(ScanHelper, "flags", SCAN_OPTION_FLAGS); DEFINE_JS_INT(ScanHelper, "batch_size", SCAN_OPTION_BATCH_SIZE); DEFINE_JS_INT(ScanHelper, "parallel", SCAN_OPTION_PARALLELISM); DEFINE_JS_INT(ScanHelper, "filter_code", SCAN_FILTER_CODE); }
TEST(ImageResourceTest, CancelOnDetach) { KURL testURL(ParsedURLString, "http://www.test.com/cancelTest.html"); URLTestHelpers::registerMockedURLLoad(testURL, "cancelTest.html", "text/html"); ResourceFetcher* fetcher = ResourceFetcher::create(ImageResourceTestMockFetchContext::create()); // Emulate starting a real load. ImageResource* cachedImage = ImageResource::create(ResourceRequest(testURL)); cachedImage->setIdentifier(createUniqueIdentifier()); fetcher->startLoad(cachedImage); memoryCache()->add(cachedImage); Persistent<MockImageResourceClient> client = new MockImageResourceClient(cachedImage); EXPECT_EQ(Resource::Pending, cachedImage->getStatus()); // The load should still be alive, but a timer should be started to cancel the load inside removeClient(). client->removeAsClient(); EXPECT_EQ(Resource::Pending, cachedImage->getStatus()); EXPECT_NE(reinterpret_cast<Resource*>(0), memoryCache()->resourceForURL(testURL)); // Trigger the cancel timer, ensure the load was cancelled and the resource was evicted from the cache. blink::testing::runPendingTasks(); EXPECT_EQ(Resource::LoadError, cachedImage->getStatus()); EXPECT_EQ(reinterpret_cast<Resource*>(0), memoryCache()->resourceForURL(testURL)); Platform::current()->getURLLoaderMockFactory()->unregisterURL(testURL); }
/* called by the Java environment for objects that have been finalized */ void Conv::releaseV8Handle(JNIEnv *jniEnv, Persistent<Object> val, int type) { HandleScope scope; Handle<String> sHiddenKey; Interface *interface = 0; ArrayType *arr = 0; if(type == -1) { sHiddenKey = sObjectHiddenKey; } else if(isArray(type)) { arrayConv->GetRefsForComponentType(jniEnv, getComponentType(type), &arr); sHiddenKey = arr->getHiddenKey(); } else if(isInterface(type)) { interface = env->getInterface(getClassId(type)); sHiddenKey = interface->getHiddenKey(); } //LOGV("releaseV8Handle; interface = %p; getting hidden value; sHiddenKey = %p\n", interface, sHiddenKey); if(!sHiddenKey.IsEmpty()) { Local<Value> hiddenVal = val->GetHiddenValue(sHiddenKey); if(!hiddenVal.IsEmpty() && !hiddenVal->IsUndefined()) { jobject extRef = (jobject)External::Unwrap(hiddenVal); Conv::deleteGlobalRef(jniEnv, extRef); val->DeleteHiddenValue(sHiddenKey); if(interface) { while((interface = interface->getParent())) { val->DeleteHiddenValue(interface->getHiddenKey()); } } } } val.Dispose(); }
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>(); }
void Query::Initialize(Handle<Object> target) { HandleScope scope; constructor = Persistent<FunctionTemplate>::New(FunctionTemplate::New(Query::New)); constructor->InstanceTemplate()->SetInternalFieldCount(1); constructor->SetClassName(String::NewSymbol("Query")); target->Set(String::NewSymbol("Query"),constructor->GetFunction()); }
/* * Class: org_appcelerator_kroll_runtime_v8_V8Runtime * Method: nativeInit * Signature: (Lorg/appcelerator/kroll/runtime/v8/V8Runtime;)J */ JNIEXPORT void JNICALL Java_org_appcelerator_kroll_runtime_v8_V8Runtime_nativeInit(JNIEnv *env, jobject self, jboolean useGlobalRefs, jint debuggerPort, jboolean DBG) { HandleScope scope; titanium::JNIScope jniScope(env); // Log all uncaught V8 exceptions. V8::AddMessageListener(logV8Exception); V8::SetCaptureStackTraceForUncaughtExceptions(true); JavaObject::useGlobalRefs = useGlobalRefs; V8Runtime::debuggerEnabled = debuggerPort >= 0; V8Runtime::DBG = DBG; V8Runtime::javaInstance = env->NewGlobalRef(self); JNIUtil::initCache(); Persistent<Context> context = Persistent<Context>::New(Context::New()); context->Enter(); V8Runtime::globalContext = context; V8Runtime::bootstrap(context->Global()); if (V8Runtime::debuggerEnabled) { jclass v8RuntimeClass = env->FindClass("org/appcelerator/kroll/runtime/v8/V8Runtime"); dispatchDebugMessage = env->GetMethodID(v8RuntimeClass, "dispatchDebugMessages", "()V"); Debug::SetDebugMessageDispatchHandler(dispatchHandler); Debug::EnableAgent("titanium", debuggerPort, true); } LOG_HEAP_STATS(TAG); }
TEST(RawResourceTest, RevalidationSucceededForResourceWithoutBody) { Resource* resource = RawResource::create(ResourceRequest("data:text/html,"), Resource::Raw); ResourceResponse response; response.setHTTPStatusCode(200); resource->responseReceived(response, nullptr); resource->finish(); memoryCache()->add(resource); // Simulate a successful revalidation. resource->setRevalidatingRequest(ResourceRequest("data:text/html,")); Persistent<DummyClient> client = new DummyClient; resource->addClient(client); ResourceResponse revalidatingResponse; revalidatingResponse.setHTTPStatusCode(304); resource->responseReceived(revalidatingResponse, nullptr); EXPECT_FALSE(resource->isCacheValidator()); EXPECT_EQ(200, resource->response().httpStatusCode()); EXPECT_EQ(nullptr, resource->resourceBuffer()); EXPECT_EQ(memoryCache()->resourceForURL(KURL(ParsedURLString, "data:text/html,")), resource); memoryCache()->remove(resource); resource->removeClient(client); EXPECT_FALSE(resource->hasClientsOrObservers()); EXPECT_FALSE(client->called()); EXPECT_EQ(0u, client->data().size()); }
TEST(ImageResourceTest, CancelOnDetach) { KURL testURL(ParsedURLString, "http://www.test.com/cancelTest.html"); ScopedRegisteredURL scopedRegisteredURL(testURL); ResourceFetcher* fetcher = ResourceFetcher::create(ImageResourceTestMockFetchContext::create()); // Emulate starting a real load. ImageResource* cachedImage = ImageResource::create(ResourceRequest(testURL)); cachedImage->setIdentifier(createUniqueIdentifier()); fetcher->startLoad(cachedImage); memoryCache()->add(cachedImage); Persistent<MockImageResourceClient> client = new MockImageResourceClient(cachedImage); EXPECT_EQ(Resource::Pending, cachedImage->getStatus()); // The load should still be alive, but a timer should be started to cancel the // load inside removeClient(). client->removeAsClient(); EXPECT_EQ(Resource::Pending, cachedImage->getStatus()); EXPECT_TRUE(memoryCache()->resourceForURL(testURL)); // Trigger the cancel timer, ensure the load was cancelled and the resource // was evicted from the cache. blink::testing::runPendingTasks(); EXPECT_EQ(Resource::LoadError, cachedImage->getStatus()); EXPECT_FALSE(memoryCache()->resourceForURL(testURL)); }
void test_obj_propexn() { HandleScope handle_scope; Persistent<Context> context = Context::New(); Context::Scope context_scope(context); Handle<Object> obj = Object::New(); obj->SetAccessor(String::New("myprop"), ReadExn, WriteExn); Local<Object> global = context->Global(); global->Set(String::New("testobj"), obj); Handle<String> source = String::New("var n = 0;" "try { testobj.myprop; } catch (e) { n += e; };" "try { testobj.myprop = (n+9); } catch (e) { n += e; }; n"); // Compile the source code. Handle<Script> script = Script::Compile(source); TryCatch trycatch; // Run the script to get the result. Handle<Value> result = script->Run(); do_check_false(result.IsEmpty()); do_check_true(result->IsInt32()); do_check_false(trycatch.HasCaught()); JSInt32 i = result->Int32Value(); do_check_eq(13, i); context.Dispose(); }
TEST(ImageResourceTest, FailedRevalidationSvgToSvg) { KURL url(ParsedURLString, "http://127.0.0.1:8000/foo"); ImageResource* imageResource = ImageResource::create(ResourceRequest(url)); Persistent<MockImageResourceClient> client = new MockImageResourceClient(imageResource); receiveResponse(imageResource, url, "image/svg+xml", svgImage()); EXPECT_FALSE(imageResource->errorOccurred()); ASSERT_TRUE(imageResource->hasImage()); EXPECT_FALSE(imageResource->getImage()->isNull()); EXPECT_EQ(client->imageChangedCount(), 1); EXPECT_TRUE(client->notifyFinishedCalled()); EXPECT_FALSE(imageResource->getImage()->isBitmapImage()); EXPECT_EQ(200, imageResource->getImage()->width()); EXPECT_EQ(200, imageResource->getImage()->height()); imageResource->setRevalidatingRequest(ResourceRequest(url)); receiveResponse(imageResource, url, "image/svg+xml", svgImage2()); EXPECT_FALSE(imageResource->errorOccurred()); ASSERT_TRUE(imageResource->hasImage()); EXPECT_FALSE(imageResource->getImage()->isNull()); EXPECT_EQ(2, client->imageChangedCount()); EXPECT_TRUE(client->notifyFinishedCalled()); EXPECT_FALSE(imageResource->getImage()->isBitmapImage()); EXPECT_EQ(300, imageResource->getImage()->width()); EXPECT_EQ(300, imageResource->getImage()->height()); }
void test_obj_defprop() { HandleScope handle_scope; Persistent<Context> context = Context::New(); Context::Scope context_scope(context); Handle<Object> obj = Object::New(); Handle<Value> data = Integer::New(2); obj->SetAccessor(String::New("myprop"), ReadTestVal, WriteTestVal, data); Local<Object> global = context->Global(); global->Set(String::New("testobj"), obj); Handle<String> source = String::New("var n = testobj.myprop; testobj.myprop = (n+9); testobj.myprop"); // Compile the source code. Handle<Script> script = Script::Compile(source); // Run the script to get the result. Handle<Value> result = script->Run(); do_check_true(!result.IsEmpty()); do_check_true(result->IsInt32()); JSInt32 i = result->Int32Value(); do_check_eq(12, i); context.Dispose(); }
bool isMatchCandidate(ConstElementPtr e) { Context::Scope context_scope(_script->getContext()); HandleScope handleScope; Persistent<Object> plugin = getPlugin(); Handle<String> isMatchCandidateStr = String::New("isMatchCandidate"); if (plugin->Has(isMatchCandidateStr) == false) { throw HootException("Error finding 'isMatchCandidate' function."); } Handle<v8::Value> value = plugin->Get(isMatchCandidateStr); if (value->IsFunction() == false) { throw HootException("isMatchCandidate is not a function."); } Handle<v8::Function> func = v8::Handle<v8::Function>::Cast(value); Handle<Value> jsArgs[2]; int argc = 0; jsArgs[argc++] = OsmMapJs::create(_map); jsArgs[argc++] = ElementJs::New(e); Handle<Value> f = func->Call(plugin, argc, jsArgs); return f->BooleanValue(); }
int v8main(char *js) { // Create a new context. static Persistent<Context> context = Context::New(); // Create a stack-allocated handle scope. HandleScope handle_scope; // Enter the created context for compiling and // running the hello world script. Context::Scope context_scope(context); // Create a string containing the JavaScript source code. Handle<String> source = String::New( js ); //"'Hello' + ', World!'"); // Compile the source code. Handle<Script> script = Script::Compile(source); // Run the script to get the result. Handle<Value> result = script->Run(); // Dispose the persistent context. context.Dispose(); // Convert the result to an ASCII string and print it. String::AsciiValue ascii(result); if(*ascii){ printf("%s\n", *ascii); } return 0; }
extern "C" void Java_io_neft_Native_renderer_1callAnimationFrame(JNIEnv * env, jobject obj) { using namespace renderer; // enter isolate Isolate* isolate = JS::GetIsolate(); Locker locker(isolate); Isolate::Scope isolate_scope(isolate); HandleScope handle_scope(isolate); // get local context and enter it Local<Context> context = Local<Context>::New(isolate, JS::GetContext()); Context::Scope context_scope(context); // call all registered functions const int length = animationFrameCalls.size(); for (int i = 0; i < length; i++){ Persistent<Function, CopyablePersistentTraits<Function>> func = animationFrameCalls[i]; // get local function Local<Function> localFunc = Local<Function>::New(isolate, func); // call function localFunc->Call(context->Global(), 0, NULL); // clear persistent func.Reset(); } // remove called functions animationFrameCalls.erase(animationFrameCalls.begin(), animationFrameCalls.begin() + length); }
TEST(LinkLoaderTest, Preconnect) { struct { const char* href; CrossOriginAttributeValue crossOrigin; const bool shouldLoad; const bool isHTTPS; const bool isCrossOrigin; } cases[] = { {"http://example.com/", CrossOriginAttributeNotSet, true, false, false}, {"https://example.com/", CrossOriginAttributeNotSet, true, true, false}, {"http://example.com/", CrossOriginAttributeAnonymous, true, false, true}, {"//example.com/", CrossOriginAttributeNotSet, true, false, false}, {"http://example.com/", CrossOriginAttributeNotSet, false, false, false}, }; // Test the cases with a single header for (const auto& testCase : cases) { std::unique_ptr<DummyPageHolder> dummyPageHolder = DummyPageHolder::create(IntSize(500, 500)); Persistent<MockLinkLoaderClient> loaderClient = MockLinkLoaderClient::create(testCase.shouldLoad); LinkLoader* loader = LinkLoader::create(loaderClient.get()); KURL hrefURL = KURL(KURL(ParsedURLStringTag(), String("http://example.com")), testCase.href); NetworkHintsMock networkHints; loader->loadLink(LinkRelAttribute("preconnect"), testCase.crossOrigin, String(), String(), String(), ReferrerPolicyDefault, hrefURL, dummyPageHolder->document(), networkHints); EXPECT_EQ(testCase.shouldLoad, networkHints.didPreconnect()); EXPECT_EQ(testCase.isHTTPS, networkHints.isHTTPS()); EXPECT_EQ(testCase.isCrossOrigin, networkHints.isCrossOrigin()); } }