Beispiel #1
0
int Interface::UserInvoke(JNIEnv *jniEnv, Handle<Object> target, int opIdx, jobjectArray jArgs, jobject *jResult) {
  HandleScope scope;
  TryCatch tryCatch;
  Operation *op = operations->addr(opIdx);
  int result = OK;
  for(int i = 0; result == OK && i < op->argCount; i++) {
      result = conv->ToV8Value(jniEnv, jniEnv->GetObjectArrayElement(jArgs, i), op->argTypes[i], &op->vArgs[i]);
  }
  if(result == OK) {
    Handle<Value> vRes;
    if(target->IsFunction() && parent == 0 && operations->getLength() == 1) {
      /* invoke as function if target is a function, and interface delcares only one operation */
      vRes = (Handle<Function>::Cast(target))->Call(target, op->argCount, op->vArgs);
    } else {
      /* locate the method and invoke that */
      Handle<Value> vMethod = target->Get(op->name);
      if(!vMethod.IsEmpty() && vMethod->IsFunction()) {
        vRes = Handle<Function>::Cast(vMethod)->Call(target, op->argCount, op->vArgs);
      }
    }
    if(!vRes.IsEmpty() && op->type != TYPE_UNDEFINED) {
      jobject ob;
      result = conv->ToJavaObject(jniEnv, vRes, op->type, &ob);
      if(result == OK) {
        *jResult = ob;
      }
    }
  }
  if(tryCatch.HasCaught()) {
    result = ErrorJS;
    tryCatch.Reset();
  }
  return result;
}
Beispiel #2
0
// parse string returned by $self->to_js() into function
void
V8Context::fixup_prototype(Handle<Object> prototype) {
    Handle<Value> val = prototype->Get(string_to_js);

    if (val.IsEmpty() || !val->IsFunction())
        return;

    TryCatch try_catch;

    Handle<Value> to_js = Handle<Function>::Cast(val)->Call(context->Global(), 0, NULL);
    Handle<Script> script = Script::Compile(to_js->ToString());

    if (try_catch.HasCaught()) {
        set_perl_error(try_catch);
    } else {
        Handle<Value> val = script->Run();

        if (val.IsEmpty() || !val->IsFunction()) {
            set_perl_error(try_catch);
        }
        else {
            prototype->Set(string_to_js, val);
        }
    }
}
Beispiel #3
0
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);
}
Beispiel #4
0
Handle<Value> ScriptMatch::_callGetMatchFeatureDetails(const ConstOsmMapPtr& map) const
{
  Isolate* current = v8::Isolate::GetCurrent();
  EscapableHandleScope handleScope(current);
  Context::Scope context_scope(_script->getContext(current));

  Handle<Object> plugin =
    Handle<Object>::Cast(
      _script->getContext(current)->Global()->Get(String::NewFromUtf8(current, "plugin")));
  Handle<Value> value = plugin->Get(String::NewFromUtf8(current, "getMatchFeatureDetails"));
  Handle<Function> func = Handle<Function>::Cast(value);
  Handle<Value> jsArgs[3];

  if (func.IsEmpty() || func->IsFunction() == false)
  {
    throw IllegalArgumentException("getMatchFeatureDetails must be a valid function.");
  }

  Handle<Object> mapObj = OsmMapJs::create(map);

  int argc = 0;
  jsArgs[argc++] = mapObj;
  jsArgs[argc++] = ElementJs::New(map->getElement(_eid1));
  jsArgs[argc++] = ElementJs::New(map->getElement(_eid2));

  TryCatch trycatch;
  Handle<Value> result = func->Call(plugin, argc, jsArgs);
  HootExceptionJs::checkV8Exception(result, trycatch);

  return handleScope.Escape(result);
}
IOBasicTypes::LongBufferSizeType ObjectByteWriterWithPosition::Write(const IOBasicTypes::Byte* inBuffer,IOBasicTypes::LongBufferSizeType inBufferSize)
{
    HandleScope handle;
    
    Handle<Object> anArray = Array::New((int)inBufferSize);
    for(int i=0;i<(int)inBufferSize;++i)
        anArray->Set(Number::New(i),Number::New(inBuffer[i]));
    
    Handle<Value> value = mObject->Get(String::New("write"));
    if(value->IsUndefined() || !value->IsFunction())
    {
		ThrowException(Exception::TypeError(String::New("write is not a function, it should be you know...")));
        return 0;
    }
    Handle<Function> func = Handle<Function>::Cast(value);
    
    Handle<Value> args[1];
    args[0] = anArray;
    
    Handle<Value> result = func->Call(mObject, 1, args);
    if(result.IsEmpty())
    {
		ThrowException(Exception::TypeError(String::New("wrong return value. it's empty. return the number of written characters")));
		return 0;
    }
    else if(result->IsNumber())
    {
        return result->ToNumber()->Uint32Value();
    }
    else
    {
		ThrowException(Exception::TypeError(String::New("wrong return value. write should return the number of written characters")));
		return 0;
    }
}
Beispiel #6
0
Handle<Value> ScriptMatch::_call(const ConstOsmMapPtr& map, Handle<Object> plugin)
{
  HandleScope handleScope;
  Context::Scope context_scope(_script->getContext());

  plugin =
    Handle<Object>::Cast(_script->getContext()->Global()->Get(String::New("plugin")));
  Handle<v8::Value> value = plugin->Get(String::New("matchScore"));
  Handle<v8::Function> func = v8::Handle<v8::Function>::Cast(value);
  Handle<Value> jsArgs[3];

  if (func.IsEmpty() || func->IsFunction() == false)
  {
    throw IllegalArgumentException("matchScore must be a valid function.");
  }

  Handle<Object> mapObj = OsmMapJs::create(map);

  int argc = 0;
  jsArgs[argc++] = mapObj;
  jsArgs[argc++] = ElementJs::New(map->getElement(_eid1));
  jsArgs[argc++] = ElementJs::New(map->getElement(_eid2));

  TryCatch trycatch;
  Handle<Value> result = func->Call(plugin, argc, jsArgs);
  HootExceptionJs::checkV8Exception(result, trycatch);

  return handleScope.Close(result);
}
Beispiel #7
0
/* static */
void V8Runtime::bootstrap(Local<Object> global)
{
	EventEmitter::Initialize();
	krollGlobalObject = Persistent<Object>::New(Object::New());

	DEFINE_METHOD(krollGlobalObject, "log", krollLog);
	DEFINE_METHOD(krollGlobalObject, "binding", KrollBindings::getBinding);
	DEFINE_TEMPLATE(krollGlobalObject, "EventEmitter", EventEmitter::constructorTemplate);

	krollGlobalObject->Set(String::NewSymbol("runtime"), String::New("v8"));

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

	TryCatch tryCatch;
	Handle<Value> result = V8Util::executeString(KrollBindings::getMainSource(), String::New("kroll.js"));

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

	Handle<Function> mainFunction = Handle<Function>::Cast(result);
	Local<Value> args[] = { Local<Value>::New(krollGlobalObject) };
	mainFunction->Call(global, 1, args);

	if (tryCatch.HasCaught()) {
		V8Util::reportException(tryCatch, true);
		LOGE(TAG, "Caught exception while bootstrapping Kroll");
	}
}
Beispiel #8
0
    int V8Scope::type( const char *field ){
        V8_SIMPLE_HEADER
        Handle<Value> v = get( field );
        if ( v->IsNull() )
            return jstNULL;
        if ( v->IsUndefined() )
            return Undefined;
        if ( v->IsString() )
            return String;
        if ( v->IsFunction() )
            return Code;
        if ( v->IsArray() )
            return Array;
        if ( v->IsBoolean() )
            return Bool;
        if ( v->IsInt32() )
            return NumberInt;
        if ( v->IsNumber() )
            return NumberDouble;
        if ( v->IsExternal() ){
            uassert( 10230 ,  "can't handle external yet" , 0 );
            return -1;
        }
        if ( v->IsDate() )
            return Date;
        if ( v->IsObject() )
            return Object;

        throw UserException( 12509, (string)"don't know what this is: " + field );
    }
ClrFuncInvokeContext::ClrFuncInvokeContext(Handle<v8::Value> callbackOrSync) : _this(0), callback(0), uv_edge_async(0)
{
    static MonoClassField* field;
    static MonoClassField* syncField;

    if (!field)
        field = mono_class_get_field_from_name(GetClrFuncInvokeContextClass(), "native");
    if (!syncField)
        syncField = mono_class_get_field_from_name(GetClrFuncInvokeContextClass(), "Sync");

    MonoObject* obj = mono_object_new(mono_domain_get(), GetClrFuncInvokeContextClass());

    ClrFuncInvokeContext* thisPointer = this;
    mono_field_set_value(obj, field, &thisPointer);
    this->_this = mono_gchandle_new(obj, FALSE); // released in destructor

    DBG("ClrFuncInvokeContext::ClrFuncInvokeContext");
    if (callbackOrSync->IsFunction())
    {
        this->callback = new Persistent<Function>(); // released in destructor
        *(this->callback) = Persistent<Function>::New(Handle<Function>::Cast(callbackOrSync));
        this->Sync(FALSE);
    }
    else 
    {
        this->Sync(callbackOrSync->BooleanValue());
    }
}
Beispiel #10
0
void Susi::JS::Engine::RegisterProcessor(const v8::FunctionCallbackInfo<v8::Value>& args) {
	if (args.Length() < 2) return;
	Handle<Value> callbackValue = args[1];
	if(callbackValue->IsFunction()){
		Handle<Value> topicValue = args[0];
		std::string topic{Susi::JS::Engine::convertFromJS(topicValue).toString()};
		std::shared_ptr<Persistent<Function>> jsCallback{new Persistent<Function>(Isolate::GetCurrent(),Handle<Function>::Cast(callbackValue))};
		Susi::Events::Processor callback = [jsCallback](Susi::Events::EventPtr event){
			Local<Function> func = Local<Function>::New(Isolate::GetCurrent(),*jsCallback);
			Handle<Value> callbackArguments[1];
			callbackArguments[0] = Susi::JS::Engine::convertFromCPP(event->toAny());
			TryCatch trycatch;
			auto res = func->Call(func,1,callbackArguments);
			if (res.IsEmpty()) {
				Handle<Value> exception = trycatch.Exception();
				String::Utf8Value exception_str(exception);
				std::cout<<*exception_str<<std::endl;
			}
		};
		long id = Susi::JS::engine->susi_client.subscribe(topic,callback);
		args.GetReturnValue().Set((double)id);
	}else{
		args.GetReturnValue().Set(false);
	}
}
JNIEXPORT void JNICALL
Java_org_appcelerator_kroll_runtime_v8_V8Object_nativeSetWindow
	(JNIEnv *env, jobject javaKrollWindow, jlong ptr, jobject javaWindow)
{
	ENTER_V8(V8Runtime::globalContext);
	titanium::JNIScope jniScope(env);

	Handle<Object> jsKrollWindow;
	if (ptr != 0) {
		jsKrollWindow = Persistent<Object>((Object *) ptr);
	} else {
		jsKrollWindow = TypeConverter::javaObjectToJsValue(env, javaKrollWindow)->ToObject();
	}

	Handle<Value> setWindowValue = jsKrollWindow->Get(String::New("setWindow"));
	if (!setWindowValue->IsFunction()) {
		return;
	}

	Handle<Function> setWindow = Handle<Function>::Cast(setWindowValue->ToObject());

	Handle<Value> jsWindow = TypeConverter::javaObjectToJsValue(env, javaWindow);

	TryCatch tryCatch;
	if (!jsWindow->IsNull()) {
		Handle<Value> args[] = { jsWindow };
		setWindow->Call(jsKrollWindow, 1, args);
	}

	if (tryCatch.HasCaught()) {
		V8Util::openJSErrorDialog(tryCatch);
		V8Util::reportException(tryCatch);
	}
}
  /*
   * 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);
  }
  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();
  }
void key::Window::setOnWindowResize(Handle<Value> value) {
	HandleScope handle_scope;
	if (value->IsFunction()) {
		auto func = Handle<Function>::Cast(value);
		this->onWindowResize = Persistent<Function>::New(func);
	} else
		cout << "Warning! Tried to set non-function as onWindowResize event callback!" << endl;
}
Beispiel #15
0
int Conv::GetNaturalType(Handle<Object> val) {
  if(val.IsEmpty()) return TYPE_INVALID;
  if(val->IsDate()) return TYPE_DATE;
  if(val->IsFunction()) return TYPE_FUNCTION;
  if(val->IsArray()) return TYPE_ARRAY;
  if(val->IsObject()) return TYPE_OBJECT;
  return TYPE_INVALID;
}
Beispiel #16
0
bool
WeechatJsV8::functionExists(const char *function)
{
    Context::Scope context_scope(this->context);

    Handle<Object> global = this->context->Global();
    Handle<Value> value = global->Get(String::New(function));
    return value->IsFunction();
}
Beispiel #17
0
	void setPersistentFunc(Persistent<Function>& pf,Handle<Value>& v){
		if(v->IsFunction()){
			if(!pf.IsEmpty()) pf.Dispose();
			pf = Persistent<Function>::New(Handle<Function>::Cast(v));
		}else if(v->IsNull()||v->IsUndefined()){
			if(pf.IsEmpty()) return;
			pf.Dispose();
			pf.Clear();
		}
	}
Beispiel #18
0
static Local<Value> ConstructError(const char *name, Handle<String> message) {
  // XXX: this probably isn't correct in all cases
  Handle<Context> ctx = Context::GetCurrent();
  Handle<Object> global = ctx->Global();
  Handle<Value> ctor = global->Get(String::New(name));
  if (ctor.IsEmpty() || !ctor->IsFunction())
    return Local<Value>();
  Handle<Function> fn = ctor.As<Function>();
  Handle<Value> args[] = { Handle<Value>(message) };
  return Local<Value>::New(fn->NewInstance(1, args));
}
int NativeTCPSocketObject::setAcceptedCallback(TiObject* obj, void* userContext)
{
    Handle<Value> value = obj->getValue();
    if (value->IsFunction())
    {
        TiTCPSocketObject* context = (TiTCPSocketObject*)userContext;
        Handle<Object> source = Handle<Object>::Cast(context->getValue());
        TiV8Event* acceptEvent = TiV8Event::createEvent(tetACCEPTED, Handle<Function>::Cast(value), source);
        setEventHandler(tetACCEPTED, acceptEvent);
        events_[tetACCEPTED]->container->setV8ValueProperty("socket", context->getValue());
        acceptEvent->release();
        return NATIVE_ERROR_OK;
    }
    return NATIVE_ERROR_INVALID_ARG;
}
JNIEXPORT jboolean JNICALL
Java_org_appcelerator_kroll_runtime_v8_V8Object_nativeFireEvent
	(JNIEnv *env, jobject jEmitter, jlong ptr, jstring event, jobject data)
{
	ENTER_V8(V8Runtime::globalContext);
	JNIScope jniScope(env);

	Handle<Value> jsEvent = TypeConverter::javaStringToJsString(event);

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

	Handle<Object> emitter;
	if (ptr != 0) {
		emitter = Persistent<Object>((Object *) ptr);
	} else {
		emitter = TypeConverter::javaObjectToJsValue(jEmitter)->ToObject();
	}

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

	Handle<Function> fireEvent = Handle<Function>::Cast(fireEventValue->ToObject());

	Handle<Value> jsData = TypeConverter::javaObjectToJsValue(data);
	Handle<Value> result;

	TryCatch tryCatch;
	if (jsData->IsNull()) {
		Handle<Value> args[] = { jsEvent };
		result = fireEvent->Call(emitter, 1, args);
	} else {
		Handle<Value> args[] = { jsEvent, jsData };
		result = fireEvent->Call(emitter, 2, args);
	}

	if (tryCatch.HasCaught()) {
		V8Util::openJSErrorDialog(tryCatch);
		V8Util::reportException(tryCatch);
	} else if (result->IsTrue()) {
		return JNI_TRUE;
	}
	return JNI_FALSE;
}
ClrFuncInvokeContext::ClrFuncInvokeContext(Handle<v8::Value> callbackOrSync)
{
    DBG("ClrFuncInvokeContext::ClrFuncInvokeContext");
    if (callbackOrSync->IsFunction())
    {
        this->callback = new Persistent<Function>;
        *(this->callback) = Persistent<Function>::New(Handle<Function>::Cast(callbackOrSync));
        this->Sync = false;
    }
    else 
    {
        this->Sync = callbackOrSync->BooleanValue();
    }

    this->uv_edge_async = NULL;
}
void CallJSFunction(JavaScriptCompiler &jsc,  
		    JavaScriptSource *source,
		    const char *name)
{
	HandleScope scope(jsc.GetIsolate());
	Local<Context> ctx = Local<Context>::New(jsc.GetIsolate(), source->ctx_);
	Context::Scope context_scope(ctx);
	Handle<Value> rewriteFuncValue = ctx->Global()->Get(String::NewSymbol(name));
	if (!rewriteFuncValue.IsEmpty() && rewriteFuncValue->IsFunction()) {
		const int argc = 0;
		Handle<Function> initFunc = Handle<Function>::Cast(rewriteFuncValue);
		Handle<Value> ret = initFunc->Call(ctx->Global(), argc, NULL);
		String::AsciiValue ascii(ret);
		ASSERT_STREQ("OK", *ascii);
	}
}
Beispiel #23
0
int Conv::ToJavaString(JNIEnv *jniEnv, Handle<Value> val, jstring *jVal) {
  Handle<String> vString;
  Handle<Value> empty, vRes;
  jstring ob;
  char buf[64];
  switch(GetNaturalType(val)) {
    default: {
      if(val->IsObject()) {
        /* call ToString() in javascript */
        Handle<Object> oVal = val->ToObject();
        Handle<Value> vToString = oVal->Get(sToString);
        if(!vToString.IsEmpty() && vToString->IsFunction()) {
          Handle<Function> fToString = Handle<Function>::Cast(vToString);
          vRes = fToString->CallAsFunction(oVal, 0, &empty);
          if(!vRes.IsEmpty() && (vRes->IsString() || vRes->IsStringObject())) {
            return ToJavaString(jniEnv, vRes->ToString(), jVal);
          }
        }
      }
      return ErrorType;
    }
    case TYPE_UNDEFINED:
    case TYPE_NULL:
      *jVal = 0;
      return OK;
    case TYPE_BOOL:
      return ToJavaString(jniEnv, (val->BooleanValue() ? "true" : "false"), jVal);
    case TYPE_INT:
      sprintf(buf, "%d", val->Int32Value());
      return ToJavaString(jniEnv, buf, jVal);
    case TYPE_LONG:
      sprintf(buf, "%lld", val->IntegerValue());
      return ToJavaString(jniEnv, buf, jVal);
    case TYPE_DOUBLE:
      sprintf(buf, "%g", val->NumberValue());
      return ToJavaString(jniEnv, buf, jVal);
    case TYPE_STRING:
      return ToJavaString(jniEnv, val->ToString(), (jstring *)jVal);
  }
  if(ob) {
    *jVal = ob;
    return OK;
  }
  if(jniEnv->ExceptionCheck())
    jniEnv->ExceptionClear();
  return ErrorVM;
}
Beispiel #24
0
ClrFuncInvokeContext::ClrFuncInvokeContext(Handle<v8::Value> callbackOrSync)
{
    DBG("ClrFuncInvokeContext::ClrFuncInvokeContext");
    if (callbackOrSync->IsFunction())
    {
        this->callback = new Persistent<Function>;
        Local<Function> callbackOrSyncFunction = Handle<Function>::Cast(callbackOrSync);
        (this->callback)->Reset(Isolate::GetCurrent(), callbackOrSyncFunction);
        this->Sync = false;
    }
    else
    {
        this->Sync = callbackOrSync->BooleanValue();
    }

    this->uv_edge_async = NULL;
}
TEST(JavaScriptCompiler, Load) {
	JavaScriptCompiler jsc;
	jsc.Load(DRAGON_TEST_PATH, "testJavaScriptCompiler/subdir");
        SourceMap &source= jsc.GetSource();
        JavaScriptSource *source1 = source["1"];

	HandleScope scope(jsc.GetIsolate());
	Local<Context> ctx = Local<Context>::New(jsc.GetIsolate(), source1->ctx_);
	Context::Scope context_scope(ctx);
	Handle<Value> rewriteFuncValue = ctx->Global()->Get(String::NewSymbol("test1"));
	if (!rewriteFuncValue.IsEmpty() && rewriteFuncValue->IsFunction()) {
		const int argc = 0;
		Handle<Function> initFunc = Handle<Function>::Cast(rewriteFuncValue);
		Handle<Value> ret = initFunc->Call(ctx->Global(), argc, NULL);
		String::AsciiValue ascii(ret);
		ASSERT_STREQ("OK1", *ascii);
	}
}
Beispiel #26
0
void
test_obj_getprop()
{
  HandleScope handle_scope;

  Persistent<Context> context = Context::New();

  Context::Scope context_scope(context);

  Handle<Object> obj = Object::New();

  Handle<Value> k = String::New("toString");
  Handle<Value> v = obj->Get(k);

  do_check_true(v->IsFunction());

  context.Dispose();
}
Beispiel #27
0
    ScriptingFunction V8Scope::_createFunction( const char * raw ){
        
        string code = raw;
        if ( code.find( "function" ) == string::npos ){
            if ( code.find( "\n" ) == string::npos && 
                 code.find( "return" ) == string::npos &&
                 ( code.find( ";" ) == string::npos || code.find( ";" ) == code.size() - 1 ) ){
                code = "return " + code;
            }
            code = "function(){ " + code + "}";
        }
        
        int num = _funcs.size() + 1;

        string fn;
        {
            stringstream ss;
            ss << "_funcs" << num;
            fn = ss.str();
        }
        
        code = fn + " = " + code;

        TryCatch try_catch;
        Handle<Script> script = v8::Script::Compile( v8::String::New( code.c_str() ) , 
                                                     v8::String::New( fn.c_str() ) );
        if ( script.IsEmpty() ){
            _error = (string)"compile error: " + toSTLString( &try_catch );
            log() << _error << endl;
            return 0;
        }
        
        Local<Value> result = script->Run();
        if ( result.IsEmpty() ){
            _error = (string)"compile error: " + toSTLString( &try_catch );
            log() << _error << endl;
            return 0;
        }        
        
        Handle<Value> f = _global->Get( v8::String::New( fn.c_str() ) );
        uassert( "not a func" , f->IsFunction() );
        _funcs.push_back( f );
        return num;
    }
int NativeTCPSocketObject::setConnectedCallback(TiObject* obj, void* userContext)
{
    if (socketState_ != SOCKET_STATE_INITIALIZED)
    {
        throw NativeException(Native::Msg::Invalid_socket_state);
    }
    Handle<Value> value = obj->getValue();
    if (value->IsFunction())
    {
        TiTCPSocketObject* context = (TiTCPSocketObject*)userContext;
        Handle<Object> source = Handle<Object>::Cast(context->getValue());
        TiV8Event* connectEvent = TiV8Event::createEvent(tetCONNECTED, Handle<Function>::Cast(value), source);
        setEventHandler(tetCONNECTED, connectEvent);
        events_[tetCONNECTED]->container->setV8ValueProperty("socket", context->getValue());
        connectEvent->release();
        return NATIVE_ERROR_OK;
    }
    return NATIVE_ERROR_INVALID_ARG;
}
Beispiel #29
0
  ScriptMatchVisitor(const ConstOsmMapPtr& map, vector<const Match*>& result,
    ConstMatchThresholdPtr mt, boost::shared_ptr<PluginContext> script,
                     ElementCriterionPtr filter = ElementCriterionPtr()) :
    _map(map),
    _result(result),
    _mt(mt),
    _script(script),
    _filter(filter),
    _customSearchRadius(-1.0)
  {
    _neighborCountMax = -1;
    _neighborCountSum = 0;
    _elementsEvaluated = 0;
    _maxGroupSize = 0;
    _numElementsVisited = 0;
    _numMatchCandidatesVisited = 0;
    _taskStatusUpdateInterval = ConfigOptions().getTaskStatusUpdateInterval();

    Isolate* current = v8::Isolate::GetCurrent();
    HandleScope handleScope(current);
    Context::Scope context_scope(_script->getContext(current));
    Handle<Object> plugin = getPlugin();
    _candidateDistanceSigma = getNumber(plugin, "candidateDistanceSigma", 0.0, 1.0);

    //this is meant to have been set externally in a js rules file
    _customSearchRadius = getNumber(plugin, "searchRadius", -1.0, 15.0);
    LOG_VART(_customSearchRadius);

    Handle<Value> value = plugin->Get(toV8("getSearchRadius"));
    if (value->IsUndefined())
    {
      // pass
    }
    else if (value->IsFunction() == false)
    {
      throw HootException("getSearchRadius is not a function.");
    }
    else
    {
      _getSearchRadius.Reset(current, Handle<Function>::Cast(value));
    }
  }
  ScriptMatchVisitor(const ConstOsmMapPtr& map, vector<const Match*>& result,
    ConstMatchThresholdPtr mt, shared_ptr<PluginContext> script) :
    _map(map),
    _result(result),
    _mt(mt),
    _script(script),
    _searchRadius(-1.0)
  {
    _neighborCountMax = -1;
    _neighborCountSum = 0;
    _elementsEvaluated = 0;
    _maxGroupSize = 0;

    HandleScope handleScope;
    Context::Scope context_scope(_script->getContext());
    Handle<Object> plugin = getPlugin();
    _candidateDistanceSigma = getNumber(plugin, "candidateDistanceSigma", 0.0, 1.0);

    //this is meant to have been set externally in a js rules file
    _searchRadius = getNumber(plugin, "searchRadius", -1.0, 15.0);

    Handle<v8::Value> value = plugin->Get(toV8("getSearchRadius"));
    if (value->IsUndefined())
    {
      // pass
    }
    else if (value->IsFunction() == false)
    {
      throw HootException("getSearchRadius is not a function.");
    }
    else
    {
      _getSearchRadius = Persistent<Function>::New(Handle<Function>::Cast(value));
    }

    SmWorstCircularErrorVisitor v(*this);
    map->visitRo(v);
    _worstCircularError = v.getWorstCircularError();
  }