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;
}
bool JSWrapper::execute( const char *scr, JSWrapperData *data, const char *fileName )
{
    HandleScope handle_scope( m_isolate );

    Local<String> source = String::NewFromUtf8( m_isolate, scr, NewStringType::kNormal ).ToLocalChecked();

    ScriptOrigin origin( v8::String::NewFromUtf8( m_isolate, fileName ? fileName : "Unknown" ) );
    MaybeLocal<Script> maybeScript = Script::Compile( m_context, source, &origin );

    bool success=false;

    if ( !maybeScript.IsEmpty() )
    {
        Local<Script> script = maybeScript.ToLocalChecked();        
        MaybeLocal<Value> maybeResult = script->Run(m_context);

        if ( !maybeResult.IsEmpty() )
        {
            Local<Value> result = maybeResult.ToLocalChecked();

            if ( data )
            {
                if ( result->IsNumber() )
                    data->setNumber( result->ToNumber()->Value() );
                else
                if ( result->IsString() )
                {
                    String::Utf8Value utf8( result );
                    data->setString( *utf8 );
                } else
                if ( result->IsBoolean() )
                    data->setBoolean( result->ToBoolean()->Value() );
                else                
                if ( result->IsObject() )
                    data->setObject( new JSWrapperObject( m_isolate, result->ToObject() ) );
                else
                if ( result->IsNull() )
                    data->setNull();
                else data->setUndefined();
            }

            success=true;
        } 
    }

    return success;
}
jstring JNIV8Object::jniToString(JNIEnv *env, jobject obj) {
    JNIV8Object_PrepareJNICall(JNIV8Object, Object, nullptr);
    MaybeLocal<String> maybeLocal = localRef->ToString(context);
    if(maybeLocal.IsEmpty()) {
        engine->forwardV8ExceptionToJNI(&try_catch);
        return nullptr;
    }
    return JNIV8Marshalling::v8string2jstring(maybeLocal.ToLocalChecked());
}
Exemple #4
0
static Local<Value> getPropertyForProxy(Isolate* isolate, Local<Name> property, Local<Object> proxy)
{
    // Call getProperty on the Proxy to get the property.
    // We define this method in JavaScript on the Proxy prototype.
    Local<Value> getProperty = proxy->Get(STRING_NEW(isolate, "getProperty"));
    if (!getProperty.IsEmpty() && getProperty->IsFunction()) {
        Local<Value> argv[1] = { property };
        MaybeLocal<Value> value = getProperty.As<Function>()->Call(isolate->GetCurrentContext(), proxy, 1, argv);
        if (value.IsEmpty()) {
            return Undefined(isolate);
        }
        return value.ToLocalChecked();
    }

    LOGE(TAG, "Unable to lookup Proxy.prototype.getProperty");
    return Undefined(isolate);
}
jobject JNIV8Object::jniGetV8FieldWithReturnType(JNIEnv *env, jobject obj, jstring name, jint flags, jint type, jclass returnType) {
    JNIV8Object_PrepareJNICall(JNIV8Object, Object, nullptr);

    JNIV8JavaValue arg = JNIV8Marshalling::valueWithClass(type, returnType, (JNIV8MarshallingFlags)flags);

    MaybeLocal<Value> valueRef = localRef->Get(context, JNIV8Marshalling::jstring2v8string(name));
    if(valueRef.IsEmpty()) {
        ptr->getEngine()->forwardV8ExceptionToJNI(&try_catch);
        return nullptr;
    }

    jvalue jval;
    memset(&jval, 0, sizeof(jvalue));
    JNIV8MarshallingError res = JNIV8Marshalling::convertV8ValueToJavaValue(env, valueRef.ToLocalChecked(), arg, &jval);
    if(res != JNIV8MarshallingError::kOk) {
        std::string strFieldName = JNIWrapper::jstring2string(name);
        switch(res) {
            default:
            case JNIV8MarshallingError::kWrongType:
                ThrowJNICastError("wrong type for field '" + strFieldName + "'");
                break;
            case JNIV8MarshallingError::kUndefined:
                ThrowJNICastError("field '" + strFieldName + "' must not be undefined");
                break;
            case JNIV8MarshallingError::kNotNullable:
                ThrowJNICastError("field '" + strFieldName + "' is not nullable");
                break;
            case JNIV8MarshallingError::kNoNaN:
                ThrowJNICastError("field '" + strFieldName + "' must not be NaN");
                break;
            case JNIV8MarshallingError::kVoidNotNull:
                ThrowJNICastError("field '" + strFieldName + "' can only be null or undefined");
                break;
            case JNIV8MarshallingError::kOutOfRange:
                ThrowJNICastError("assigned value '"+
                                  JNIV8Marshalling::v8string2string(valueRef.ToLocalChecked()->ToString(context).ToLocalChecked())+"' is out of range for field '" + strFieldName + "'");
                break;
        }
        return nullptr;
    }

    return jval.l;
}
JNIEXPORT jobject JNICALL
Java_org_appcelerator_kroll_runtime_v8_V8Object_nativeCallProperty
	(JNIEnv* env, jclass clazz, jlong ptr, jstring propertyName, jobjectArray args)
{
	HandleScope scope(V8Runtime::v8_isolate);
	JNIScope jniScope(env);

	Local<Value> jsPropertyName = TypeConverter::javaStringToJsString(V8Runtime::v8_isolate, env, propertyName);

	titanium::Proxy* proxy = (titanium::Proxy*) ptr;
	Local<Object> object = proxy->handle(V8Runtime::v8_isolate);
	Local<Value> property = object->Get(jsPropertyName);
	if (!property->IsFunction()) {
		return JNIUtil::undefinedObject;
	}

	int argc = 0;
	Local<Value>* argv = NULL;
	if (args) {
		argv = TypeConverter::javaObjectArrayToJsArguments(V8Runtime::v8_isolate, args, &argc);
	}

	TryCatch tryCatch(V8Runtime::v8_isolate);
	Local<Function> function = property.As<Function>();
	MaybeLocal<Value> returnValue = function->Call(V8Runtime::v8_isolate->GetCurrentContext(), object, argc, argv);

	if (argv) {
		delete[] argv;
	}

	if (tryCatch.HasCaught()) {
		V8Util::openJSErrorDialog(V8Runtime::v8_isolate, tryCatch);
		V8Util::reportException(V8Runtime::v8_isolate, tryCatch);
		return JNIUtil::undefinedObject;
	} else if (returnValue.IsEmpty()) {
		return JNIUtil::undefinedObject;
	}

	bool isNew;
	return TypeConverter::jsValueToJavaObject(V8Runtime::v8_isolate, env, returnValue.ToLocalChecked(), &isNew);
}
Exemple #7
0
void constructor(const FunctionCallbackInfo<Value> &args)
{
    if (args.IsConstructCall()) {
        Local<Object> options = args[0]->ToObject();
        int port = options->Get(String::NewFromUtf8(args.GetIsolate(), "port"))->ToInteger()->Value();
        String::Utf8Value path(options->Get(String::NewFromUtf8(args.GetIsolate(), "path")));
        int keepAliveTime = options->Get(String::NewFromUtf8(args.GetIsolate(), "keepAliveTime"))->ToInteger()->Value();
        int keepAliveInterval = options->Get(String::NewFromUtf8(args.GetIsolate(), "keepAliveInterval"))->ToInteger()->Value();
        int keepAliveRetry = options->Get(String::NewFromUtf8(args.GetIsolate(), "keepAliveRetry"))->ToInteger()->Value();

        MaybeLocal<Value> perMessageDeflate = options->Get(String::NewFromUtf8(args.GetIsolate(), "perMessageDeflate"));
        bool usePerMessageDeflate = true;
        static string strPerMessageDeflate = "permessage-deflate";
        if (perMessageDeflate.ToLocalChecked()->IsObject()) {
            Local<Array> propertyNames = perMessageDeflate.ToLocalChecked()->ToObject()->GetPropertyNames();
            for (int i = 0; i < propertyNames->Length(); i++) {
                String::Utf8Value keyName(propertyNames->Get(i));
                MaybeLocal<Value> optionalValue = perMessageDeflate.ToLocalChecked()->ToObject()->Get(propertyNames->Get(i));
                if (!(optionalValue.ToLocalChecked()->IsBoolean() && !optionalValue.ToLocalChecked()->BooleanValue())) {
                    strPerMessageDeflate += "; " + camelCaseToUnderscore(string(*keyName, keyName.length()));

                    if (!optionalValue.IsEmpty() && !optionalValue.ToLocalChecked()->IsBoolean()) {
                        String::Utf8Value valueString(optionalValue.ToLocalChecked()->ToString());
                        strPerMessageDeflate += "=" + string(*valueString, valueString.length());
                    }
                }
            }
        }
        else if(perMessageDeflate.ToLocalChecked()->IsBoolean()) {
            usePerMessageDeflate = perMessageDeflate.ToLocalChecked()->BooleanValue();
        }

        MaybeLocal<Value> ssl = options->Get(String::NewFromUtf8(args.GetIsolate(), "ssl"));
        static string certPath, keyPath, caPath, ciphers;
        static bool rejectUnauthorized = true;
        if (!ssl.IsEmpty()) {
            Local<Object> sslOptions = ssl.ToLocalChecked()->ToObject();
            certPath = getString(args.GetIsolate(), sslOptions, "cert");
            keyPath = getString(args.GetIsolate(), sslOptions, "key");
            caPath = getString(args.GetIsolate(), sslOptions, "ca");
            ciphers = getString(args.GetIsolate(), sslOptions, "ciphers");
            rejectUnauthorized = sslOptions->Get(String::NewFromUtf8(args.GetIsolate(), "rejectUnauthorized"))->BooleanValue();
        }

#ifdef VERBOSE_SERVER
        cout << "Using port = " << port << ", path = " << string(*path, path.length())
             << ", keepAliveTime = " << keepAliveTime << ", keepAliveInterval = "
             << keepAliveInterval << ", keepAliveRetry = " << keepAliveRetry << endl;

        if (usePerMessageDeflate) {
            cout << "Using perMessageDeflate:" << endl << strPerMessageDeflate << endl;
        }
#endif

        lws::Server *server;
        try {
            server = new lws::Server(port, string(*path, path.length()).c_str(), keepAliveTime, keepAliveRetry,
                                     keepAliveInterval, usePerMessageDeflate, strPerMessageDeflate.c_str(),
                                     certPath.c_str(), keyPath.c_str(), caPath.c_str(), ciphers.c_str(), rejectUnauthorized);
        }
        catch (...) {
            server = nullptr;
        }

        args.This()->SetAlignedPointerInInternalField(0, server);
        args.GetReturnValue().Set(args.This());
    }
}
jobject JNIV8Object::jniGetV8Fields(JNIEnv *env, jobject obj, jboolean ownOnly, jint flags, jint type, jclass returnType) {
    JNIV8Object_PrepareJNICall(JNIV8Object, Object, nullptr);

    JNIV8JavaValue arg = JNIV8Marshalling::valueWithClass(type, returnType, (JNIV8MarshallingFlags)flags);

    MaybeLocal<Array> maybeArrayRef = ownOnly ? localRef->GetOwnPropertyNames(context) : localRef->GetPropertyNames(context);
    if(maybeArrayRef.IsEmpty()) {
        ptr->getEngine()->forwardV8ExceptionToJNI(&try_catch);
        return nullptr;
    }

    Local<Array> arrayRef = maybeArrayRef.ToLocalChecked();
    Local<Value> valueRef;
    Local<String> keyRef;

    jobject strObj;
    // we are only using the .l member of the jvalue; so one memset is enough!
    jvalue jval = {0};
    memset(&jval, 0, sizeof(jvalue));

    jobject result = env->NewObject(_jniHashMap.clazz, _jniHashMap.initId);
    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;
        }
        keyRef = valueRef->ToString(isolate);

        maybeValueRef = localRef->Get(context, keyRef);
        if(!maybeValueRef.ToLocal<Value>(&valueRef)) {
            ptr->getEngine()->forwardV8ExceptionToJNI(&try_catch);
            return nullptr;
        }

        JNIV8MarshallingError res = JNIV8Marshalling::convertV8ValueToJavaValue(env, valueRef, arg, &jval);
        if(res != JNIV8MarshallingError::kOk) {
            std::string strPropertyName = JNIV8Marshalling::v8string2string(keyRef);
            switch(res) {
                default:
                case JNIV8MarshallingError::kWrongType:
                    ThrowJNICastError("wrong type for value of '" + strPropertyName + "'");
                    break;
                case JNIV8MarshallingError::kUndefined:
                    ThrowJNICastError("value of '" + strPropertyName + "' must not be undefined");
                    break;
                case JNIV8MarshallingError::kNotNullable:
                    ThrowJNICastError("value of '" + strPropertyName + "' is not nullable");
                    break;
                case JNIV8MarshallingError::kNoNaN:
                    ThrowJNICastError("value of '" + strPropertyName + "' must not be NaN");
                    break;
                case JNIV8MarshallingError::kVoidNotNull:
                    ThrowJNICastError("value of '" + strPropertyName + "' can only be null or undefined");
                    break;
                case JNIV8MarshallingError::kOutOfRange:
                    ThrowJNICastError("value '"+
                                      JNIV8Marshalling::v8string2string(valueRef->ToString(context).ToLocalChecked())+"' is out of range for property '" + strPropertyName + "'");
                    break;
            }
            return nullptr;
        }

        strObj = JNIV8Marshalling::v8string2jstring(keyRef);
        env->CallObjectMethod(result,
                              _jniHashMap.putId,
                              strObj,
                              jval.l
        );
        env->DeleteLocalRef(jval.l);
        env->DeleteLocalRef(strObj);
    }

    return result;
}
JNIEXPORT jboolean JNICALL
Java_org_appcelerator_kroll_runtime_v8_V8Object_nativeFireEvent
	(JNIEnv *env, jobject jEmitter, jlong ptr, jobject jsource, jlong sourcePtr, jstring event, jobject data, jboolean bubble, jboolean reportSuccess, jint code, jstring errorMessage)
{
	HandleScope scope(V8Runtime::v8_isolate);
	JNIScope jniScope(env);

	Local<Value> jsEvent = TypeConverter::javaStringToJsString(V8Runtime::v8_isolate, env, event);

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

	Local<Object> emitter;
	if (ptr != 0) {
		titanium::Proxy* proxy = (titanium::Proxy*) ptr;
		emitter = proxy->handle(V8Runtime::v8_isolate);
	} else {
		emitter = TypeConverter::javaObjectToJsValue(V8Runtime::v8_isolate, env, jEmitter).As<Object>();
	}

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

	Local<Object> source;
	if ((jsource == NULL) || (jsource == jEmitter)) {
		source = emitter;
	} else if (sourcePtr != 0) {
		titanium::Proxy* proxy = (titanium::Proxy*) sourcePtr;
		source = proxy->handle(V8Runtime::v8_isolate);
	} else {
		source = TypeConverter::javaObjectToJsValue(V8Runtime::v8_isolate, env, jsource).As<Object>();
	}

	Local<Function> fireEvent = fireEventValue.As<Function>();

	Local<Object> jsData = TypeConverter::javaHashMapToJsValue(V8Runtime::v8_isolate, env, data);

	jsData->Set(NEW_SYMBOL(V8Runtime::v8_isolate, "bubbles"), TypeConverter::javaBooleanToJsBoolean(V8Runtime::v8_isolate, bubble));

	jsData->Set(NEW_SYMBOL(V8Runtime::v8_isolate, "source"), source);

	if (reportSuccess || code != 0) {
		jsData->Set(NEW_SYMBOL(V8Runtime::v8_isolate, "success"), TypeConverter::javaBooleanToJsBoolean(V8Runtime::v8_isolate, code == 0));
		jsData->Set(NEW_SYMBOL(V8Runtime::v8_isolate, "code"), TypeConverter::javaIntToJsNumber(V8Runtime::v8_isolate, code));
	}

	if (errorMessage != NULL) {
		jsData->Set(NEW_SYMBOL(V8Runtime::v8_isolate, "error"), TypeConverter::javaStringToJsString(V8Runtime::v8_isolate, env, errorMessage));
	}

	TryCatch tryCatch(V8Runtime::v8_isolate);
	Local<Value> args[] = { jsEvent, jsData };
	MaybeLocal<Value> result = fireEvent->Call(V8Runtime::v8_isolate->GetCurrentContext(), emitter, 2, args);

	if (tryCatch.HasCaught()) {
		V8Util::openJSErrorDialog(V8Runtime::v8_isolate, tryCatch);
		V8Util::reportException(V8Runtime::v8_isolate, tryCatch);
	} else if (result.IsEmpty()) {
		return JNI_FALSE;
	} else if (result.ToLocalChecked()->IsTrue()) {
		return JNI_TRUE;
	}
	return JNI_FALSE;
}