Ejemplo n.º 1
0
void Msg_Struct::build_buffer_arg(const Field_Info &field_info, Block_Buffer &buffer, Isolate* isolate, v8::Local<v8::Value> value) {
    if(field_info.field_type == "int8") {
        int8_t val = 0;
        if (value->IsInt32()) {
            val = value->Int32Value(isolate->GetCurrentContext()).FromJust();
        }
        buffer.write_int8(val);
    }
    else if(field_info.field_type == "int16") {
        int16_t val = 0;
        if (value->IsInt32()) {
            val = value->Int32Value(isolate->GetCurrentContext()).FromJust();
        }
        buffer.write_int16(val);
    }
    else if(field_info.field_type == "int32") {
        int32_t val = 0;
        if (value->IsInt32()) {
            val = value->Int32Value(isolate->GetCurrentContext()).FromJust();
        }
        buffer.write_int32(val);
    }
    else if(field_info.field_type == "int64") {
        int64_t val = 0;
        if (value->IsNumber()) {
            val = value->NumberValue(isolate->GetCurrentContext()).FromJust();
        }
        buffer.write_int64(val);
    }
    else if(field_info.field_type == "double") {
        double val = 0;
        if (value->IsNumber()) {
            val = value->NumberValue(isolate->GetCurrentContext()).FromJust();
        }
        buffer.write_double(val);
    }
    else if(field_info.field_type == "bool") {
        bool val = 0;
        if (value->IsBoolean()) {
            val = value->BooleanValue(isolate->GetCurrentContext()).FromJust();
        }
        buffer.write_bool(val);
    }
    else if(field_info.field_type == "string") {
        std::string val = "";
        if (value->IsString()) {
            String::Utf8Value str(value->ToString(isolate->GetCurrentContext()).ToLocalChecked());
            std::stringstream stream;
            stream << ToCString(str);
            val = stream.str();
        }
        buffer.write_string(val);
    }
    else {
        LOG_ERROR("Can not find the field_type:%s, struct_name:%s", field_info.field_type.c_str(), struct_name().c_str());
    }
}
Ejemplo n.º 2
0
void V8BiquadFilterNode::typeAttributeSetterCustom(v8::Local<v8::Value> value, const v8::PropertyCallbackInfo<void>& info)
{
    ExceptionState exceptionState(ExceptionState::SetterContext, "type", "BiquadFilterNode", info.Holder(), info.GetIsolate());
    BiquadFilterNode* impl = V8BiquadFilterNode::toNative(info.Holder());

    if (value->IsNumber()) {
        uint32_t type = toUInt32(value, exceptionState);
        if (exceptionState.throwIfNeeded())
            return;
        if (!impl->setType(type)) {
            exceptionState.throwTypeError("Illegal BiquadFilterNode type");
            exceptionState.throwIfNeeded();
        }
        return;
    }

    if (value->IsString()) {
        String type = toCoreString(value.As<v8::String>());
        if (type == "lowpass" || type == "highpass" || type == "bandpass" || type == "lowshelf" || type == "highshelf" || type == "peaking" || type == "notch" || type == "allpass") {
            impl->setType(type);
            return;
        }
    }

    exceptionState.throwTypeError("Illegal BiquadFilterNode type");
    exceptionState.throwIfNeeded();
}
Ejemplo n.º 3
0
void V8OscillatorNode::typeAccessorSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info)
{
    v8::Handle<v8::Object> holder = info.Holder();
    OscillatorNode* imp = V8OscillatorNode::toNative(holder);

#if ENABLE(LEGACY_WEB_AUDIO)    
    if (value->IsNumber()) {
        bool ok = false;
        uint32_t type = toUInt32(value, ok);
        if (!ok || !imp->setType(type))
            throwError(v8TypeError, "Illegal OscillatorNode type", info.GetIsolate());
        return;
    }
#endif

    if (value->IsString()) {
        String type = toWebCoreString(value);
        if (type == "sine" || type == "square" || type == "sawtooth" || type == "triangle") {
            imp->setType(type);
            return;
        }
    }
    
    throwError(v8TypeError, "Illegal OscillatorNode type", info.GetIsolate());
}
Ejemplo n.º 4
0
void convertV8ObjectToNPVariant(v8::Local<v8::Value> object, NPObject* owner, NPVariant* result)
{
    VOID_TO_NPVARIANT(*result);

    // It is really the caller's responsibility to deal with the empty handle case because there could be different actions to
    // take in different contexts.
    ASSERT(!object.IsEmpty());

    if (object.IsEmpty())
        return;

    if (object->IsNumber())
        DOUBLE_TO_NPVARIANT(object->NumberValue(), *result);
    else if (object->IsBoolean())
        BOOLEAN_TO_NPVARIANT(object->BooleanValue(), *result);
    else if (object->IsNull())
        NULL_TO_NPVARIANT(*result);
    else if (object->IsUndefined())
        VOID_TO_NPVARIANT(*result);
    else if (object->IsString()) {
        v8::Handle<v8::String> str = object->ToString();
        int length = str->Utf8Length() + 1;
        char* utf8Chars = reinterpret_cast<char*>(malloc(length));
        str->WriteUtf8(utf8Chars, length, 0, v8::String::HINT_MANY_WRITES_EXPECTED);
        STRINGN_TO_NPVARIANT(utf8Chars, length-1, *result);
    } else if (object->IsObject()) {
        DOMWindow* window = V8Proxy::retrieveWindow(V8Proxy::currentContext());
        NPObject* npobject = npCreateV8ScriptObject(0, v8::Handle<v8::Object>::Cast(object), window);
        if (npobject)
            _NPN_RegisterObject(npobject, owner);
        OBJECT_TO_NPVARIANT(npobject, *result);
    }
}
Ejemplo n.º 5
0
inline optional<double> toDouble(v8::Local<v8::Value> value) {
    Nan::HandleScope scope;
    if (!value->IsNumber()) {
        return {};
    }
    return value->NumberValue();
}
Ejemplo n.º 6
0
void V8PannerNode::panningModelAccessorSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info)
{
    PannerNode* imp = V8PannerNode::toNative(info.Holder());

#if ENABLE(LEGACY_WEB_AUDIO)    
    if (value->IsNumber()) {
        bool ok = false;
        uint32_t model = toUInt32(value, ok);
        ASSERT(ok);
        if (!imp->setPanningModel(model))
            throwError(v8TypeError, "Illegal panningModel", info.GetIsolate());
        return;
    }
#endif

    if (value->IsString()) {
        String model = toWebCoreString(value);
        if (model == "equalpower" || model == "HRTF" || model == "soundfield") {
            imp->setPanningModel(model);
            return;
        }
    }
    
    throwError(v8TypeError, "Illegal panningModel", info.GetIsolate());
}
Ejemplo n.º 7
0
void V8PannerNode::distanceModelAttrSetterCustom(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info)
{
    PannerNode* imp = V8PannerNode::toNative(info.Holder());

#if ENABLE(LEGACY_WEB_AUDIO)    
    if (value->IsNumber()) {
        bool ok = false;
        uint32_t model = toUInt32(value, ok);
        ASSERT(ok);
        if (!imp->setDistanceModel(model))
            throwError(v8TypeError, "Illegal distanceModel", info.GetIsolate());
        return;
    }
#endif

    if (value->IsString()) {
        String model = toWebCoreString(value);
        if (model == "linear" || model == "inverse" || model == "exponential") {
            imp->setDistanceModel(model);
            return;
        }
    }
    
    throwError(v8TypeError, "Illegal distanceModel", info.GetIsolate());
}
void V8BooleanOrStringOrUnrestrictedDouble::toImpl(v8::Isolate* isolate, v8::Local<v8::Value> v8Value, BooleanOrStringOrUnrestrictedDouble& impl, UnionTypeConversionMode conversionMode, ExceptionState& exceptionState) {
    if (v8Value.IsEmpty())
        return;

    if (conversionMode == UnionTypeConversionMode::Nullable && isUndefinedOrNull(v8Value))
        return;

    if (v8Value->IsBoolean()) {
        impl.setBoolean(v8Value.As<v8::Boolean>()->Value());
        return;
    }

    if (v8Value->IsNumber()) {
        double cppValue = toDouble(isolate, v8Value, exceptionState);
        if (exceptionState.hadException())
            return;
        impl.setUnrestrictedDouble(cppValue);
        return;
    }

    {
        V8StringResource<> cppValue = v8Value;
        if (!cppValue.prepare(exceptionState))
            return;
        impl.setString(cppValue);
        return;
    }
}
Ejemplo n.º 9
0
void convertV8ObjectToNPVariant(v8::Local<v8::Value> object, NPObject* owner, NPVariant* result)
{
    VOID_TO_NPVARIANT(*result);

    // It is really the caller's responsibility to deal with the empty handle case because there could be different actions to
    // take in different contexts.
    ASSERT(!object.IsEmpty());

    if (object.IsEmpty())
        return;

    if (object->IsInt32())
        INT32_TO_NPVARIANT(object->NumberValue(), *result);
    else if (object->IsNumber())
        DOUBLE_TO_NPVARIANT(object->NumberValue(), *result);
    else if (object->IsBoolean())
        BOOLEAN_TO_NPVARIANT(object->BooleanValue(), *result);
    else if (object->IsNull())
        NULL_TO_NPVARIANT(*result);
    else if (object->IsUndefined())
        VOID_TO_NPVARIANT(*result);
    else if (object->IsString()) {
        v8::String::Utf8Value utf8(object);
        char* utf8_chars = strdup(*utf8);
        STRINGN_TO_NPVARIANT(utf8_chars, utf8.length(), *result);
    } else if (object->IsObject()) {
        WebCore::DOMWindow* window = WebCore::V8Proxy::retrieveWindow(WebCore::V8Proxy::currentContext());
        NPObject* npobject = npCreateV8ScriptObject(0, v8::Handle<v8::Object>::Cast(object), window);
        if (npobject)
            _NPN_RegisterObject(npobject, owner);
        OBJECT_TO_NPVARIANT(npobject, *result);
    }
}
Ejemplo n.º 10
0
void V8OscillatorNode::typeAttributeSetterCustom(v8::Local<v8::Value> value, const v8::PropertyCallbackInfo<void>& info)
{
    ExceptionState exceptionState(ExceptionState::SetterContext, "type", "OscillatorNode", info.Holder(), info.GetIsolate());
    v8::Handle<v8::Object> holder = info.Holder();
    OscillatorNode* imp = V8OscillatorNode::toNative(holder);

    if (value->IsNumber()) {
        uint32_t type = toUInt32(value, exceptionState);
        if (exceptionState.throwIfNeeded())
            return;
        if (!imp->setType(type)) {
            exceptionState.throwTypeError("Illegal OscillatorNode type");
            exceptionState.throwIfNeeded();
        }
        return;
    }

    if (value->IsString()) {
        String type = toCoreString(value.As<v8::String>());
        if (type == "sine" || type == "square" || type == "sawtooth" || type == "triangle") {
            imp->setType(type);
            return;
        }
    }

    exceptionState.throwTypeError("Illegal OscillatorNode type");
    exceptionState.throwIfNeeded();
}
Ejemplo n.º 11
0
void V8PannerNode::distanceModelAttributeSetterCustom(v8::Local<v8::Value> value, const v8::PropertyCallbackInfo<void>& info)
{
    ExceptionState exceptionState(ExceptionState::SetterContext, "distanceModel", "PannerNode", info.Holder(), info.GetIsolate());
    PannerNode* impl = V8PannerNode::toNative(info.Holder());

    if (value->IsNumber()) {
        uint32_t model = toUInt32(value, exceptionState);
        if (exceptionState.throwIfNeeded())
            return;
        if (!impl->setDistanceModel(model)) {
            exceptionState.throwTypeError("Illegal distanceModel");
            exceptionState.throwIfNeeded();
        }
        return;
    }

    if (value->IsString()) {
        String model = toCoreString(value.As<v8::String>());
        if (model == "linear" || model == "inverse" || model == "exponential") {
            impl->setDistanceModel(model);
            return;
        }
    }

    exceptionState.throwTypeError("Illegal distanceModel");
    exceptionState.throwIfNeeded();
}
Ejemplo n.º 12
0
jobject v8ToJava(JNIEnv* env, v8::Local<v8::Value> arg) {
  if(arg->IsNull() || arg->IsUndefined()) {
    return NULL;
  }

  if(arg->IsArray()) {
    v8::Local<v8::Array> array = v8::Array::Cast(*arg);
    uint32_t arraySize = array->Length();
    jclass objectClazz = env->FindClass("java/lang/Object");
    jobjectArray result = env->NewObjectArray(arraySize, objectClazz, NULL);
    for(uint32_t i=0; i<arraySize; i++) {
      jobject val = v8ToJava(env, array->Get(i));
      env->SetObjectArrayElement(result, i, val);
    }
    return result;
  }

  if(arg->IsString()) {
    v8::String::AsciiValue val(arg->ToString());
    return env->NewStringUTF(*val);
  }

  if(arg->IsInt32() || arg->IsUint32()) {
    jint val = arg->ToInt32()->Value();
    jclass clazz = env->FindClass("java/lang/Integer");
    jmethodID constructor = env->GetMethodID(clazz, "<init>", "(I)V");
    return env->NewObject(clazz, constructor, val);
  }

  if(arg->IsNumber()) {
    jdouble val = arg->ToNumber()->Value();
    jclass clazz = env->FindClass("java/lang/Double");
    jmethodID constructor = env->GetMethodID(clazz, "<init>", "(D)V");
    return env->NewObject(clazz, constructor, val);
  }

  if(arg->IsBoolean()) {
    jboolean val = arg->ToBoolean()->Value();
    jclass clazz = env->FindClass("java/lang/Boolean");
    jmethodID constructor = env->GetMethodID(clazz, "<init>", "(Z)V");
    return env->NewObject(clazz, constructor, val);
  }

  if(arg->IsObject()) {
    v8::Local<v8::Object> obj = v8::Object::Cast(*arg);
    v8::String::AsciiValue constructorName(obj->GetConstructorName());
    if(strcmp(*constructorName, "JavaObject") == 0) {
      JavaObject* javaObject = node::ObjectWrap::Unwrap<JavaObject>(obj);
      return javaObject->getObject();
    }
  }

  // TODO: handle other arg types
  v8::String::AsciiValue typeStr(arg);
  printf("Unhandled type: %s\n", *typeStr);
  return NULL;
}
    static NativeType getNativeFloat(v8::Local<v8::Value> js)
    {
        if (!js->IsNumber())
        {
            throw std::runtime_error("float");
        }

        return static_cast<NativeType>(js->NumberValue());
    }
    static NativeType getNativeSigned(v8::Local<v8::Value> js)
    {
        if (!js->IsNumber())
        {
            throw std::runtime_error("signed integer");
        }

        return static_cast<NativeType>(js->IntegerValue());
    }
Ejemplo n.º 15
0
void SessionWrapper::setPageSize(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::PropertyCallbackInfo<void>& info)
{
	SessionHolder* pSessionHolder = Wrapper::unwrapNative<SessionHolder>(info);
	if (value->IsNumber())
	{
		pSessionHolder->setPageSize(value->Uint32Value());
	}
	else
	{
		returnException(info, std::string("invalid pageSize argument"));
	}
}
Ejemplo n.º 16
0
inline optional<Value> toValue(v8::Local<v8::Value> value) {
    if (value->IsFalse()) {
        return { false };
    } else if (value->IsTrue()) {
        return { true };
    } else if (value->IsString()) {
        return { std::string(*Nan::Utf8String(value)) };
    } else if (value->IsUint32()) {
        return { std::uint64_t(value->Uint32Value()) };
    } else if (value->IsInt32()) {
        return { std::int64_t(value->Int32Value()) };
    } else if (value->IsNumber()) {
        return { value->NumberValue() };
    } else {
        return {};
    }
}
Ejemplo n.º 17
0
// static
CJS_Value::Type CJS_Value::GetValueType(v8::Local<v8::Value> value) {
  if (value.IsEmpty())
    return VT_unknown;
  if (value->IsString())
    return VT_string;
  if (value->IsNumber())
    return VT_number;
  if (value->IsBoolean())
    return VT_boolean;
  if (value->IsDate())
    return VT_date;
  if (value->IsObject())
    return VT_object;
  if (value->IsNull())
    return VT_null;
  if (value->IsUndefined())
    return VT_undefined;
  return VT_unknown;
}
Ejemplo n.º 18
0
void ConvertV8ObjectToNPVariant(v8::Local<v8::Value> object, NPObject *owner,
                                NPVariant* result) {
  VOID_TO_NPVARIANT(*result);

  // It is really the caller's responsibility to deal with the empty handle
  // case because there could be different actions to take in different
  // contexts.
  ASSERT(!object.IsEmpty());

  if (object.IsEmpty()) return;

  if (object->IsNumber()) {
    DOUBLE_TO_NPVARIANT(object->NumberValue(), *result);

  } else if (object->IsBoolean()) {
    BOOLEAN_TO_NPVARIANT(object->BooleanValue(), *result);

  } else if (object->IsNull()) {
    NULL_TO_NPVARIANT(*result);

  } else if (object->IsUndefined()) {
    VOID_TO_NPVARIANT(*result);

  } else if (object->IsString()) {
    v8::Handle<v8::String> str = object->ToString();
    uint16_t *buf = new uint16_t[str->Length()+1];
    str->Write(buf);
    std::string utf8 = WideToUTF8(reinterpret_cast<wchar_t*>(buf));
    char* utf8_chars = strdup(utf8.c_str());
    STRINGN_TO_NPVARIANT(utf8_chars, utf8.length(), *result);
    delete[] buf;

  } else if (object->IsObject()) {
    WebCore::DOMWindow* window = WebCore::V8Proxy::retrieveWindow();
    NPObject* npobject = NPN_CreateScriptObject(
        0, v8::Handle<v8::Object>::Cast(object), window);
    if (npobject) {
      _NPN_RegisterObject(npobject, owner);
    }
    OBJECT_TO_NPVARIANT(npobject, *result);
  }
}
void V8SVGLength::valueAttrSetterCustom(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::PropertyCallbackInfo<void>& info)
{
    SVGPropertyTearOff<SVGLength>* wrapper = V8SVGLength::toNative(info.Holder());
    if (wrapper->isReadOnly()) {
        setDOMException(NoModificationAllowedError, info.GetIsolate());
        return;
    }

    if (!isUndefinedOrNull(value) && !value->IsNumber() && !value->IsBoolean()) {
        throwTypeError(info.GetIsolate());
        return;
    }

    SVGLength& imp = wrapper->propertyReference();
    ExceptionState es(info.GetIsolate());
    SVGLengthContext lengthContext(wrapper->contextElement());
    imp.setValue(static_cast<float>(value->NumberValue()), lengthContext, es);
    if (es.throwIfNeeded())
        return;
    wrapper->commitChange();
}
void V8SVGLength::valueAccessorSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info)
{
    INC_STATS("DOM.SVGLength.value._set");
    SVGPropertyTearOff<SVGLength>* wrapper = V8SVGLength::toNative(info.Holder());
    if (wrapper->role() == AnimValRole) {
        V8Proxy::setDOMException(NO_MODIFICATION_ALLOWED_ERR);
        return;
    }

    if (!isUndefinedOrNull(value) && !value->IsNumber() && !value->IsBoolean()) {
        V8Proxy::throwTypeError();
        return;
    }

    SVGLength& imp = wrapper->propertyReference();
    ExceptionCode ec = 0;
    imp.setValue(static_cast<float>(value->NumberValue()), wrapper->contextElement(), ec);
    if (UNLIKELY(ec))
        V8Proxy::setDOMException(ec);
    else
        wrapper->commitChange();
}
Ejemplo n.º 21
0
void _appendValue(exlib::string& str, v8::Local<v8::Value>& v, bool mysql)
{
    bool bNumber = v->IsNumber() || v->IsNumberObject();

    if (bNumber) {
        v8::String::Utf8Value s1(v);
        str.append(*s1, s1.length());
    } else {
        exlib::string s;
        str += '\'';

        if (v->IsDate()) {
            date_t d = v;
            d.sqlString(s);
        } else {
            v8::String::Utf8Value s1(v);
            _escape(*s1, s1.length(), mysql, s);
        }
        str.append(s);

        str += '\'';
    }
}
void V8BiquadFilterNode::typeAttributeSetterCustom(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::PropertyCallbackInfo<void>& info)
{
    BiquadFilterNode* imp = V8BiquadFilterNode::toNative(info.Holder());

    if (value->IsNumber()) {
        bool ok = false;
        uint32_t type = toUInt32(value, ok);
        ASSERT(ok);
        if (!imp->setType(type))
            throwTypeError("Illegal BiquadFilterNode type", info.GetIsolate());
        return;
    }

    if (value->IsString()) {
        String type = toWebCoreString(value);
        if (type == "lowpass" || type == "highpass" || type == "bandpass" || type == "lowshelf" || type == "highshelf" || type == "peaking" || type == "notch" || type == "allpass") {
            imp->setType(type);
            return;
        }
    }

    throwTypeError("Illegal BiquadFilterNode type", info.GetIsolate());
}
Ejemplo n.º 23
0
PJsonVal TNodeJsUtil::GetObjJson(const v8::Local<v8::Value>& Val, const bool IgnoreFunc) {
	AssertR(!Val->IsExternal(), "TNodeJsUtil::GetObjJson: Cannot parse v8::External!");

	if (Val->IsObject()) {
		// if we aren't ignoring functions and the object is a function
		// then throw an exception
		EAssertR(IgnoreFunc || !Val->IsFunction(), "TNodeJsUtil::GetObjJson: Cannot parse functions!");

		// parse the object
		if (Val->IsFunction()) {
			return TJsonVal::New();
		}
		else if (Val->IsBooleanObject()) {
			v8::Local<v8::BooleanObject> BoolObj = v8::Local<v8::BooleanObject>::Cast(Val);
			return TJsonVal::NewBool(BoolObj->ValueOf());
		}
		else if (Val->IsNumberObject()) {
			return TJsonVal::NewNum(Val->NumberValue());
		}
		else if (Val->IsStringObject() || Val->IsRegExp() || Val->IsDate()) {
			return TJsonVal::NewStr(TStr(*v8::String::Utf8Value(Val->ToString())));
		}
		else if (Val->IsArray()) {
			PJsonVal JsonArr = TJsonVal::NewArr();

			v8::Array* Arr = v8::Array::Cast(*Val);
			for (uint i = 0; i < Arr->Length(); i++) {
				if (!IgnoreFunc || !Arr->Get(i)->IsFunction()) {
					JsonArr->AddToArr(GetObjJson(Arr->Get(i), IgnoreFunc));
				}
			}

			return JsonArr;
		}
		else {	// general object with fields
			PJsonVal JsonVal = TJsonVal::NewObj();
			v8::Local<v8::Object> Obj = Val->ToObject();

			v8::Local<v8::Array> FldNmV = Obj->GetOwnPropertyNames();
			for (uint i = 0; i < FldNmV->Length(); i++) {
				const TStr FldNm(*v8::String::Utf8Value(FldNmV->Get(i)->ToString()));

				v8::Local<v8::Value> FldVal = Obj->Get(FldNmV->Get(i));

				if (!IgnoreFunc || !FldVal->IsFunction()) {
					JsonVal->AddToObj(FldNm, GetObjJson(FldVal, IgnoreFunc));
				}
			}

			return JsonVal;
		}
	}
	else {	// primitive
		if (Val->IsUndefined()) {
			return TJsonVal::New();
		}
		else if (Val->IsNull()) {
			return TJsonVal::NewNull();
		}
		else if (Val->IsBoolean()) {
			return TJsonVal::NewBool(Val->BooleanValue());
		}
		else if (Val->IsNumber()) {
			return TJsonVal::NewNum(Val->NumberValue());
		}
		else if (Val->IsString()) {
			return TJsonVal::NewStr(TStr(*v8::String::Utf8Value(Val->ToString())));
		}
		else {
			// TODO check for v8::Symbol
			throw TExcept::New("TNodeJsUtil::GetObjJson: Unknown v8::Primitive type!");
		}
	}
}
Ejemplo n.º 24
0
jobject TypeConverter::jsValueToJavaObject(JNIEnv *env, v8::Local<v8::Value> jsValue, bool *isNew)
{
	if (jsValue->IsNumber()) {
		*isNew = true;
		if (jsValue->IsInt32()) {
			jint javaInt = TypeConverter::jsNumberToJavaInt(jsValue->ToNumber());
			return env->NewObject(JNIUtil::integerClass, JNIUtil::integerInitMethod, javaInt);
		}
		jdouble javaDouble = TypeConverter::jsNumberToJavaDouble(jsValue->ToNumber());
		return env->NewObject(JNIUtil::doubleClass, JNIUtil::doubleInitMethod, javaDouble);

	} else if (jsValue->IsBoolean()) {
		jboolean javaBoolean = TypeConverter::jsBooleanToJavaBoolean(jsValue->ToBoolean());
		*isNew = true;
		return env->NewObject(JNIUtil::booleanClass, JNIUtil::booleanInitMethod, javaBoolean);

	} else if (jsValue->IsString()) {
		*isNew = true;
		return TypeConverter::jsStringToJavaString(env, jsValue->ToString());

	} else if (jsValue->IsDate()) {
		Local<Date> date = Local<Date>::Cast<Value>(jsValue);
		return TypeConverter::jsDateToJavaDate(env, date);

	} else if (jsValue->IsArray()) {
		*isNew = true;
		return TypeConverter::jsArrayToJavaArray(env, v8::Handle<v8::Array>::Cast(jsValue));

	} else if (jsValue->IsFunction()) {
		*isNew = true;
		return TypeConverter::jsObjectToJavaFunction(env, jsValue->ToObject());

	} else if (jsValue->IsObject()) {
		v8::Handle<v8::Object> jsObject = jsValue->ToObject();
		if (JavaObject::isJavaObject(jsObject)) {
			*isNew = JavaObject::useGlobalRefs ? false : true;
			JavaObject *javaObject = JavaObject::Unwrap<JavaObject>(jsObject);
			return javaObject->getJavaObject();
		} else {
			// Unwrap hyperloop JS wrappers to get native java proxy
			Handle<String> nativeString = String::New("$native");
			if (jsObject->HasOwnProperty(nativeString)) {
				v8::Local<v8::Value> nativeObject = jsObject->GetRealNamedProperty(nativeString);
				jsObject = nativeObject->ToObject();
				if (JavaObject::isJavaObject(jsObject)) {
					*isNew = JavaObject::useGlobalRefs ? false : true;
					JavaObject *javaObject = JavaObject::Unwrap<JavaObject>(jsObject);
					return javaObject->getJavaObject();
				}
			}

			v8::Handle<v8::Array> objectKeys = jsObject->GetOwnPropertyNames();
			int numKeys = objectKeys->Length();
			*isNew = true;
			jobject javaHashMap = env->NewObject(JNIUtil::hashMapClass, JNIUtil::hashMapInitMethod, numKeys);

			for (int i = 0; i < numKeys; i++) {
				v8::Local<v8::Value> jsObjectPropertyKey = objectKeys->Get((uint32_t) i);
				bool keyIsNew, valueIsNew;
				jobject javaObjectPropertyKey = TypeConverter::jsValueToJavaObject(env, jsObjectPropertyKey, &keyIsNew);
				v8::Local<v8::Value> jsObjectPropertyValue = jsObject->Get(jsObjectPropertyKey);
				jobject javaObjectPropertyValue = TypeConverter::jsValueToJavaObject(env, jsObjectPropertyValue, &valueIsNew);

				jobject result = env->CallObjectMethod(javaHashMap,
				                                       JNIUtil::hashMapPutMethod,
				                                       javaObjectPropertyKey,
				                                       javaObjectPropertyValue);
				env->DeleteLocalRef(result);

				if (keyIsNew) {
					env->DeleteLocalRef(javaObjectPropertyKey);
				}
				if (valueIsNew) {
					env->DeleteLocalRef(javaObjectPropertyValue);
				}
			}

			return javaHashMap;
		}
	}

	if (!jsValue->IsNull() && !jsValue->IsUndefined()) {
		LOGW(TAG, "jsValueToJavaObject returning null.");
	}
	return NULL;
}
Ejemplo n.º 25
0
jobject v8ToJava(JNIEnv* env, v8::Local<v8::Value> arg) {
  if(arg.IsEmpty() || arg->IsNull() || arg->IsUndefined()) {
    return NULL;
  }

  if(arg->IsArray()) {
    v8::Local<v8::Array> array = v8::Array::Cast(*arg);
    uint32_t arraySize = array->Length();
    jclass objectClazz = env->FindClass("java/lang/Object");
    jobjectArray result = env->NewObjectArray(arraySize, objectClazz, NULL);
    for(uint32_t i=0; i<arraySize; i++) {
      jobject val = v8ToJava(env, array->Get(i));
      env->SetObjectArrayElement(result, i, val);
    }
    return result;
  }

  if(arg->IsString()) {
    v8::String::Utf8Value val(arg->ToString());
    return env->NewStringUTF(*val);
  }

  if(arg->IsInt32() || arg->IsUint32()) {
    jint val = arg->ToInt32()->Value();
    jclass clazz = env->FindClass("java/lang/Integer");
    jmethodID constructor = env->GetMethodID(clazz, "<init>", "(I)V");
    return env->NewObject(clazz, constructor, val);
  }

  if(arg->IsNumber()) {
    jdouble val = arg->ToNumber()->Value();
    jclass clazz = env->FindClass("java/lang/Double");
    jmethodID constructor = env->GetMethodID(clazz, "<init>", "(D)V");
    return env->NewObject(clazz, constructor, val);
  }

  if(arg->IsBoolean()) {
    jboolean val = arg->ToBoolean()->Value();
    jclass clazz = env->FindClass("java/lang/Boolean");
    jmethodID constructor = env->GetMethodID(clazz, "<init>", "(Z)V");
    return env->NewObject(clazz, constructor, val);
  }

  if(arg->IsObject()) {
    v8::Local<v8::Object> obj = v8::Object::Cast(*arg);

    v8::Local<v8::Value> isJavaObject = obj->GetHiddenValue(v8::String::New(V8_HIDDEN_MARKER_JAVA_OBJECT));
    if(!isJavaObject.IsEmpty() && isJavaObject->IsBoolean()) {
      return v8ToJava_javaObject(env, obj);
    }

    v8::Local<v8::Value> isJavaLong = obj->GetHiddenValue(v8::String::New(V8_HIDDEN_MARKER_JAVA_LONG));
    if(!isJavaLong.IsEmpty() && isJavaLong->IsBoolean()) {
      return v8ToJava_javaLong(env, obj);
    }
  }

  // TODO: handle other arg types
  v8::String::AsciiValue typeStr(arg);
  printf("v8ToJava: Unhandled type: %s\n", *typeStr);
  return NULL;
}
Ejemplo n.º 26
0
void encodeValue(bson *bb, const char *name, v8::Local<v8::Value> element,
                 bool doJson)
{
    if (element.IsEmpty() || element->IsUndefined() || element->IsFunction())
        ;
    else if (element->IsNull())
        bson_append_null(bb, name);
    else if (element->IsDate())
        bson_append_date(bb, name, (bson_date_t) element->NumberValue());
    else if (element->IsBoolean())
        bson_append_bool(bb, name, element->IsTrue());
    else if (element->IsNumber() || element->IsNumberObject())
    {
        double value = element->NumberValue();
        int64_t num = (int64_t) value;

        if (value == (double) num)
        {
            if (num >= -2147483648ll && num <= 2147483647ll)
                bson_append_int(bb, name, (int) num);
            else
                bson_append_long(bb, name, num);
        }
        else
            bson_append_double(bb, name, value);
    }
    else if (element->IsArray())
        encodeArray(bb, name, element);
    else if (element->IsRegExp())
    {
        v8::Local<v8::RegExp> re = v8::Local<v8::RegExp>::Cast(element);
        v8::Local<v8::String> src = re->GetSource();
        v8::RegExp::Flags flgs = re->GetFlags();
        char flgStr[4];
        char *p = flgStr;

        if (flgs & v8::RegExp::kIgnoreCase)
            *p++ = 'i';
        if (flgs & v8::RegExp::kGlobal)
            *p++ = 'g';
        if (flgs & v8::RegExp::kMultiline)
            *p++ = 'm';

        *p = 0;

        bson_append_regex(bb, name, *v8::String::Utf8Value(src), flgStr);
    }
    else if (element->IsObject())
    {
        {
            obj_ptr<Int64> num = (Int64 *)Int64_base::getInstance(element);

            if (num)
            {
                if (num->m_num >= -2147483648ll && num->m_num <= 2147483647ll)
                    bson_append_int(bb, name, (int) num->m_num);
                else
                    bson_append_long(bb, name, num->m_num);
                return;
            }
        }

        {
            obj_ptr<Buffer_base> buf = Buffer_base::getInstance(element);

            if (buf)
            {
                std::string strBuf;

                buf->toString(strBuf);
                bson_append_binary(bb, name, BSON_BIN_BINARY, strBuf.c_str(),
                                   (int) strBuf.length());

                return;
            }
        }

        {
            obj_ptr<MongoID> oid = (MongoID *) MongoID_base::getInstance(
                                       element);

            if (oid)
            {
                bson_append_oid(bb, name, &oid->m_id);
                return;
            }
        }

        encodeObject(bb, name, element, doJson);
    }
    else
    {
        v8::String::Utf8Value v(element);
        bson_append_string(bb, name, ToCString(v));
    }
}
Ejemplo n.º 27
0
std::unique_ptr<protocol::Value> toProtocolValue(v8::Local<v8::Context> context, v8::Local<v8::Value> value, int maxDepth)
{
    if (value.IsEmpty()) {
        NOTREACHED();
        return nullptr;
    }

    if (!maxDepth)
        return nullptr;
    maxDepth--;

    if (value->IsNull() || value->IsUndefined())
        return protocol::Value::null();
    if (value->IsBoolean())
        return protocol::FundamentalValue::create(value.As<v8::Boolean>()->Value());
    if (value->IsNumber())
        return protocol::FundamentalValue::create(value.As<v8::Number>()->Value());
    if (value->IsString())
        return protocol::StringValue::create(toProtocolString(value.As<v8::String>()));
    if (value->IsArray()) {
        v8::Local<v8::Array> array = value.As<v8::Array>();
        std::unique_ptr<protocol::ListValue> inspectorArray = protocol::ListValue::create();
        uint32_t length = array->Length();
        for (uint32_t i = 0; i < length; i++) {
            v8::Local<v8::Value> value;
            if (!array->Get(context, i).ToLocal(&value))
                return nullptr;
            std::unique_ptr<protocol::Value> element = toProtocolValue(context, value, maxDepth);
            if (!element)
                return nullptr;
            inspectorArray->pushValue(std::move(element));
        }
        return std::move(inspectorArray);
    }
    if (value->IsObject()) {
        std::unique_ptr<protocol::DictionaryValue> jsonObject = protocol::DictionaryValue::create();
        v8::Local<v8::Object> object = v8::Local<v8::Object>::Cast(value);
        v8::Local<v8::Array> propertyNames;
        if (!object->GetPropertyNames(context).ToLocal(&propertyNames))
            return nullptr;
        uint32_t length = propertyNames->Length();
        for (uint32_t i = 0; i < length; i++) {
            v8::Local<v8::Value> name;
            if (!propertyNames->Get(context, i).ToLocal(&name))
                return nullptr;
            // FIXME(yurys): v8::Object should support GetOwnPropertyNames
            if (name->IsString()) {
                v8::Maybe<bool> hasRealNamedProperty = object->HasRealNamedProperty(context, v8::Local<v8::String>::Cast(name));
                if (!hasRealNamedProperty.IsJust() || !hasRealNamedProperty.FromJust())
                    continue;
            }
            v8::Local<v8::String> propertyName;
            if (!name->ToString(context).ToLocal(&propertyName))
                continue;
            v8::Local<v8::Value> property;
            if (!object->Get(context, name).ToLocal(&property))
                return nullptr;
            std::unique_ptr<protocol::Value> propertyValue = toProtocolValue(context, property, maxDepth);
            if (!propertyValue)
                return nullptr;
            jsonObject->setValue(toProtocolString(propertyName), std::move(propertyValue));
        }
        return std::move(jsonObject);
    }
    NOTREACHED();
    return nullptr;
}
Ejemplo n.º 28
0
result_t util_base::isNumber(v8::Local<v8::Value> v, bool& retVal)
{
    retVal = v->IsNumber() || v->IsNumberObject();
    return 0;
}
Ejemplo n.º 29
0
bool javaScriptToMessage(v8::Local<v8::Value> value, Message &result)
{
    bool success = true;
    if (value->IsNumber())
    {
        double number = value->ToNumber()->Value();
        result.appendFloat(number);
    }
    else if (value->IsString())
    {
        v8::String::AsciiValue tmp(value->ToString());
        result.appendString(*tmp);
    }
    else if (value->IsArray())
    {
        // disabled for now:
        {
            std::ostringstream os;
            os << __FUNCTION__ << ": Unsupported type: array.";
            Logger::log(WARNING, os);
        }
        return false;
        // the code below is not executed, but it's a work in progress

        v8::Array *array = v8::Array::Cast(*value);
        unsigned int length = array->Length();
        //std::cout << __FUNCTION__ << ": array length : " << length << std::endl;

        for (unsigned int i = 0; i < array->Length(); i++)
        {
            v8::Local<v8::Object> element = array->CloneElementAt(i);
            if (*element == 0)
            {
                std::ostringstream os;
                os << __FUNCTION__ << ": array element is NULL";
                Logger::log(ERROR, os);
                return false;
            }
            //std::cout << __FUNCTION__ << " element: " << *element << std::endl;
            if (element->IsNumber())
            {
                double number = v8::NumberObject::Cast(*element)->NumberValue();
                result.appendFloat(number);
            }
            else if (element->IsString())
            {
                v8::String::AsciiValue tmp(element->ToString());
                result.appendString(*tmp);
            }
            else
            {
                success = false;
                {
                    std::ostringstream os;
                    os << __FUNCTION__ << ": Unsupported type.";
                    Logger::log(WARNING, os);
                }
            }
        }
    }
    else
    {
        success = false;
        {
            std::ostringstream os;
            os << __FUNCTION__ << ": Unsupported type.";
            Logger::log(WARNING, os);
        }
    }
    return success;
}
Ejemplo n.º 30
0
// converts js value to java object and recursively converts sub objects if this
// object is a container type
jobject TypeConverter::jsValueToJavaObject(v8::Local<v8::Value> jsValue, bool *isNew)
{
	JNIEnv *env = JNIScope::getEnv();
	if (env == NULL) {
		return NULL;
	}

	if (jsValue->IsNumber()) {
		jdouble javaDouble = TypeConverter::jsNumberToJavaDouble(jsValue->ToNumber());
		*isNew = true;
		return env->NewObject(JNIUtil::doubleClass, JNIUtil::doubleInitMethod, javaDouble);

	} else if (jsValue->IsBoolean()) {
		jboolean javaBoolean = TypeConverter::jsBooleanToJavaBoolean(jsValue->ToBoolean());
		*isNew = true;
		return env->NewObject(JNIUtil::booleanClass, JNIUtil::booleanInitMethod, javaBoolean);

	} else if (jsValue->IsString()) {
		*isNew = true;
		return TypeConverter::jsStringToJavaString(jsValue->ToString());

	} else if (jsValue->IsDate()) {
		Local<Date> date = Local<Date>::Cast<Value>(jsValue);
		return TypeConverter::jsDateToJavaDate(date);

	} else if (jsValue->IsArray()) {
		*isNew = true;
		return TypeConverter::jsArrayToJavaArray(v8::Handle<v8::Array>::Cast(jsValue));

	} else if (jsValue->IsFunction()) {
		*isNew = true;
		return TypeConverter::jsObjectToJavaFunction(jsValue->ToObject());

	} else if (jsValue->IsObject()) {
		v8::Handle<v8::Object> jsObject = jsValue->ToObject();

		if (JavaObject::isJavaObject(jsObject)) {
			*isNew = JavaObject::useGlobalRefs ? false : true;
			JavaObject *javaObject = JavaObject::Unwrap<JavaObject>(jsObject);
			return javaObject->getJavaObject();
		} else {
			v8::Handle<v8::Array> objectKeys = jsObject->GetOwnPropertyNames();
			int numKeys = objectKeys->Length();
			*isNew = true;
			jobject javaHashMap = env->NewObject(JNIUtil::hashMapClass, JNIUtil::hashMapInitMethod, numKeys);

			for (int i = 0; i < numKeys; i++) {
				v8::Local<v8::Value> jsObjectPropertyKey = objectKeys->Get((uint32_t) i);
				bool keyIsNew, valueIsNew;
				jobject javaObjectPropertyKey = TypeConverter::jsValueToJavaObject(jsObjectPropertyKey, &keyIsNew);
				v8::Local<v8::Value> jsObjectPropertyValue = jsObject->Get(jsObjectPropertyKey);
				jobject javaObjectPropertyValue = TypeConverter::jsValueToJavaObject(jsObjectPropertyValue, &valueIsNew);

				jobject result = env->CallObjectMethod(javaHashMap,
				                                       JNIUtil::hashMapPutMethod,
				                                       javaObjectPropertyKey,
				                                       javaObjectPropertyValue);
				env->DeleteLocalRef(result);

				if (keyIsNew) {
					env->DeleteLocalRef(javaObjectPropertyKey);
				}
				if (valueIsNew) {
					env->DeleteLocalRef(javaObjectPropertyValue);
				}
			}

			return javaHashMap;
		}
	}

	LOGW(TAG, "jsValueToJavaObject returning null");
	return NULL;
}