result_t util_base::last(v8::Local<v8::Value> v, int32_t n, v8::Local<v8::Value> &retVal) { Isolate* isolate = Isolate::current(); if (v->IsUndefined() || v->IsNull() || n <= 0) { retVal = v8::Array::New(isolate->m_isolate); return 0; } if (!v->IsArray()) return CHECK_ERROR(CALL_E_TYPEMISMATCH); v8::Local<v8::Array> arr = v8::Local<v8::Array>::Cast(v); int32_t len = arr->Length(); int32_t i; if (n > len) n = len; v8::Local<v8::Array> arr1 = v8::Array::New(isolate->m_isolate); for (i = 0; i < n; i ++) arr1->Set(i, arr->Get(len - n + i)); retVal = arr1; return 0; }
result_t util_base::isEmpty(v8::Local<v8::Value> v, bool& retVal) { if (v->IsNull()) { retVal = true; return 0; } if (v->IsString()) { retVal = v8::Local<v8::String>::Cast(v)->Length() == 0; return 0; } if (v->IsStringObject()) { retVal = v8::Local<v8::StringObject>::Cast(v)->ValueOf()->Length() == 0; return 0; } if (v->IsArray()) { retVal = v8::Local<v8::Array>::Cast(v)->Length() == 0; return 0; } if (v->IsObject()) { retVal = v->ToObject()->GetOwnPropertyNames()->Length() == 0; return 0; } retVal = true; return 0; }
std::vector<uint8_t> JSZCluster::addArgument(v8::Local<v8::Value> value, const std::shared_ptr<ClusterCmdParamsBase> &cmdParam) { if (value->IsUint32()) { return cmdParam->getType().getRaw(value->ToUint32()->Value()); } if (value->IsInt32()) { return cmdParam->getType().getRaw(value->ToInt32()->Value()); } if (value->IsString()) { String::Utf8Value utf8Value(value); return cmdParam->getType().getRaw(*utf8Value); } if (value->IsArray()) { Local<Array> array = value.As<Array>(); std::vector<std::string> strArray; for (uint32_t index = 0; index < array->Length(); index++) { String::Utf8Value utf8Value(array->Get(index)); strArray.push_back(*utf8Value); } return cmdParam->getType().getRaw(strArray); } stringstream stream; stream << "To " << EXECUTE_CMD_BY_ID << " it is passed an invalid argument instead of type " << cmdParam->getZCLDataType(); throw JSException(stream.str()); }
result_t util_base::last(v8::Local<v8::Value> v, v8::Local<v8::Value> &retVal) { Isolate* isolate = Isolate::current(); if (v->IsUndefined() || v->IsNull()) { retVal = v8::Undefined(isolate->m_isolate); return 0; } if (!v->IsArray()) return CHECK_ERROR(CALL_E_TYPEMISMATCH); v8::Local<v8::Array> arr = v8::Local<v8::Array>::Cast(v); int32_t len = arr->Length(); if (len == 0) { retVal = v8::Undefined(isolate->m_isolate); return 0; } retVal = arr->Get(len - 1); return 0; }
void Buffer::fromJSON(Isolate* isolate, v8::Local<v8::Value> data, v8::Local<v8::Object>& o) { if (data->IsArray()) { obj_ptr<Buffer_base> buf = new Buffer(); buf->append(v8::Local<v8::Array>::Cast(data)); o = buf->wrap(); } }
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; }
bool getMessagePortArray(v8::Local<v8::Value> value, int argumentIndex, MessagePortArray& ports, v8::Isolate* isolate) { if (isUndefinedOrNull(value)) { ports.resize(0); return true; } if (!value->IsArray()) { throwTypeError(ExceptionMessages::notAnArrayTypeArgumentOrValue(argumentIndex), isolate); return false; } bool success = false; ports = toRefPtrNativeArray<MessagePort, V8MessagePort>(value, argumentIndex, isolate, &success); return success; }
bool getMessagePortArray(v8::Local<v8::Value> value, const String& propertyName, MessagePortArray& ports, v8::Isolate* isolate) { if (isUndefinedOrNull(value)) { ports.resize(0); return true; } if (!value->IsArray()) { throwTypeError(ExceptionMessages::notASequenceTypeProperty(propertyName), isolate); return false; } bool success = false; ports = toRefPtrNativeArray<MessagePort, V8MessagePort>(value, propertyName, isolate, &success); return success; }
bool extractTransferables(v8::Local<v8::Value> value, int argumentIndex, MessagePortArray& ports, ArrayBufferArray& arrayBuffers, ExceptionState& exceptionState, v8::Isolate* isolate) { if (isUndefinedOrNull(value)) { ports.resize(0); arrayBuffers.resize(0); return true; } uint32_t length = 0; if (value->IsArray()) { v8::Local<v8::Array> array = v8::Local<v8::Array>::Cast(value); length = array->Length(); } else if (toV8Sequence(value, length, isolate).IsEmpty()) { exceptionState.throwTypeError(ExceptionMessages::notAnArrayTypeArgumentOrValue(argumentIndex + 1)); return false; } v8::Local<v8::Object> transferrables = v8::Local<v8::Object>::Cast(value); // Validate the passed array of transferrables. for (unsigned int i = 0; i < length; ++i) { v8::Local<v8::Value> transferrable = transferrables->Get(i); // Validation of non-null objects, per HTML5 spec 10.3.3. if (isUndefinedOrNull(transferrable)) { exceptionState.throwDOMException(DataCloneError, "Value at index " + String::number(i) + " is an untransferable " + (transferrable->IsUndefined() ? "'undefined'" : "'null'") + " value."); return false; } // Validation of Objects implementing an interface, per WebIDL spec 4.1.15. if (V8MessagePort::hasInstance(transferrable, isolate)) { RefPtr<MessagePort> port = V8MessagePort::toNative(v8::Handle<v8::Object>::Cast(transferrable)); // Check for duplicate MessagePorts. if (ports.contains(port)) { exceptionState.throwDOMException(DataCloneError, "Message port at index " + String::number(i) + " is a duplicate of an earlier port."); return false; } ports.append(port.release()); } else if (V8ArrayBuffer::hasInstance(transferrable, isolate)) { RefPtr<ArrayBuffer> arrayBuffer = V8ArrayBuffer::toNative(v8::Handle<v8::Object>::Cast(transferrable)); if (arrayBuffers.contains(arrayBuffer)) { exceptionState.throwDOMException(DataCloneError, "ArrayBuffer at index " + String::number(i) + " is a duplicate of an earlier ArrayBuffer."); return false; } arrayBuffers.append(arrayBuffer.release()); } else { exceptionState.throwDOMException(DataCloneError, "Value at index " + String::number(i) + " does not have a transferable type."); return false; } } return true; }
SassImportList CustomImporterBridge::post_process_return_value(v8::Local<v8::Value> returned_value) const { SassImportList imports = 0; Nan::HandleScope scope; if (returned_value->IsArray()) { v8::Local<v8::Array> array = returned_value.As<v8::Array>(); imports = sass_make_import_list(array->Length()); for (size_t i = 0; i < array->Length(); ++i) { v8::Local<v8::Value> value = Nan::Get(array, static_cast<uint32_t>(i)).ToLocalChecked(); if (!value->IsObject()) { auto entry = sass_make_import_entry(0, 0, 0); sass_import_set_error(entry, "returned array must only contain object literals", -1, -1); continue; } v8::Local<v8::Object> object = value.As<v8::Object>(); if (value->IsNativeError()) { char* message = create_string(Nan::Get(object, Nan::New<v8::String>("message").ToLocalChecked())); imports[i] = sass_make_import_entry(0, 0, 0); sass_import_set_error(imports[i], message, -1, -1); } else { imports[i] = get_importer_entry(object); } } } else if (returned_value->IsNativeError()) { imports = sass_make_import_list(1); v8::Local<v8::Object> object = returned_value.As<v8::Object>(); char* message = create_string(Nan::Get(object, Nan::New<v8::String>("message").ToLocalChecked())); imports[0] = sass_make_import_entry(0, 0, 0); sass_import_set_error(imports[0], message, -1, -1); } else if (returned_value->IsObject()) { imports = sass_make_import_list(1); imports[0] = get_importer_entry(returned_value.As<v8::Object>()); } return imports; }
result_t util_base::unique(v8::Local<v8::Value> v, bool sorted, v8::Local<v8::Array> &retVal) { Isolate* isolate = Isolate::current(); if (v->IsUndefined() || v->IsNull()) { retVal = v8::Array::New(isolate->m_isolate); return 0; } if (!v->IsArray()) return CHECK_ERROR(CALL_E_TYPEMISMATCH); v8::Local<v8::Array> arr1 = v8::Array::New(isolate->m_isolate); v8::Local<v8::Array> arr = v8::Local<v8::Array>::Cast(v); int32_t len = arr->Length(); QuickArray<v8::Local<v8::Value> > vals; int32_t i, j, n = 0; vals.resize(len); for (i = 0; i < len; i ++) { v8::Local<v8::Value> val = arr->Get(i); for (j = i - 1; j >= 0; j --) if (!vals[j].IsEmpty()) { if (val->StrictEquals(vals[j])) break; if (sorted) { j = -1; break; } } if (j < 0) vals[i] = val; } for (i = 0; i < len; i ++) if (!vals[i].IsEmpty()) arr1->Set(n++, vals[i]); retVal = arr1; return 0; }
bool extractTransferables(v8::Local<v8::Value> value, MessagePortArray& ports, ArrayBufferArray& arrayBuffers) { if (isUndefinedOrNull(value)) { ports.resize(0); arrayBuffers.resize(0); return true; } if (!value->IsObject()) { throwError("TransferArray argument must be an object"); return false; } uint32_t length = 0; v8::Local<v8::Object> transferrables = v8::Local<v8::Object>::Cast(value); if (value->IsArray()) { v8::Local<v8::Array> array = v8::Local<v8::Array>::Cast(value); length = array->Length(); } else { // Sequence-type object - get the length attribute v8::Local<v8::Value> sequenceLength = transferrables->Get(v8::String::New("length")); if (!sequenceLength->IsNumber()) { throwError("TransferArray argument has no length attribute"); return false; } length = sequenceLength->Uint32Value(); } // Validate the passed array of transferrables. for (unsigned int i = 0; i < length; ++i) { v8::Local<v8::Value> transferrable = transferrables->Get(i); // Validation of non-null objects, per HTML5 spec 10.3.3. if (isUndefinedOrNull(transferrable)) { throwError(DATA_CLONE_ERR); return false; } // Validation of Objects implementing an interface, per WebIDL spec 4.1.15. if (V8MessagePort::HasInstance(transferrable)) ports.append(V8MessagePort::toNative(v8::Handle<v8::Object>::Cast(transferrable))); else if (V8ArrayBuffer::HasInstance(transferrable)) arrayBuffers.append(V8ArrayBuffer::toNative(v8::Handle<v8::Object>::Cast(transferrable))); else { throwError("TransferArray argument must contain only Transferables"); return false; } } return true; }
bool extractTransferables(v8::Local<v8::Value> value, MessagePortArray& ports, ArrayBufferArray& arrayBuffers, v8::Isolate* isolate) { if (isUndefinedOrNull(value)) { ports.resize(0); arrayBuffers.resize(0); return true; } uint32_t length = 0; if (value->IsArray()) { v8::Local<v8::Array> array = v8::Local<v8::Array>::Cast(value); length = array->Length(); } else { if (toV8Sequence(value, length).IsEmpty()) return false; } v8::Local<v8::Object> transferrables = v8::Local<v8::Object>::Cast(value); // Validate the passed array of transferrables. for (unsigned int i = 0; i < length; ++i) { v8::Local<v8::Value> transferrable = transferrables->Get(i); // Validation of non-null objects, per HTML5 spec 10.3.3. if (isUndefinedOrNull(transferrable)) { setDOMException(INVALID_STATE_ERR, isolate); return false; } // Validation of Objects implementing an interface, per WebIDL spec 4.1.15. if (V8MessagePort::HasInstance(transferrable)) { RefPtr<MessagePort> port = V8MessagePort::toNative(v8::Handle<v8::Object>::Cast(transferrable)); // Check for duplicate MessagePorts. if (ports.contains(port)) { setDOMException(INVALID_STATE_ERR, isolate); return false; } ports.append(port.release()); } else if (V8ArrayBuffer::HasInstance(transferrable)) arrayBuffers.append(V8ArrayBuffer::toNative(v8::Handle<v8::Object>::Cast(transferrable))); else { throwTypeError(); return false; } } return true; }
std::vector<uint8_t> Convert::getVectorForUint8(v8::Local<v8::Value> js) { if (!js->IsArray()) { throw std::runtime_error("array"); } v8::Local<v8::Array> jsarray = v8::Local<v8::Array>::Cast(js); auto length = jsarray->Length(); std::vector<uint8_t> returnData; for (uint32_t i = 0; i < length; ++i) { returnData.push_back(static_cast<uint8_t>(jsarray->Get(Nan::New(i))->Uint32Value())); } return returnData; }
bool getMessagePortArray(v8::Local<v8::Value> value, MessagePortArray& portArray) { if (isUndefinedOrNull(value)) { portArray.resize(0); return true; } if (!value->IsObject()) { throwError("MessagePortArray argument must be an object"); return false; } uint32_t length = 0; v8::Local<v8::Object> ports = v8::Local<v8::Object>::Cast(value); if (value->IsArray()) { v8::Local<v8::Array> array = v8::Local<v8::Array>::Cast(value); length = array->Length(); } else { // Sequence-type object - get the length attribute v8::Local<v8::Value> sequenceLength = ports->Get(v8::String::New("length")); if (!sequenceLength->IsNumber()) { throwError("MessagePortArray argument has no length attribute"); return false; } length = sequenceLength->Uint32Value(); } portArray.resize(length); for (unsigned int i = 0; i < length; ++i) { v8::Local<v8::Value> port = ports->Get(v8::Integer::New(i)); // Validation of non-null objects, per HTML5 spec 8.3.3. if (isUndefinedOrNull(port)) { throwError(INVALID_STATE_ERR); return false; } // Validation of Objects implementing an interface, per WebIDL spec 4.1.15. if (!V8MessagePort::HasInstance(port)) { throwError("MessagePortArray argument must contain only MessagePorts"); return false; } portArray[i] = V8DOMWrapper::convertToNativeObject<MessagePort>(V8ClassIndex::MESSAGEPORT, v8::Handle<v8::Object>::Cast(port)); } return true; }
inline result_t GetArray(v8::Local<v8::Value> v, QuickArray<T> &n) { if (v.IsEmpty() || !v->IsArray()) return CALL_E_INVALIDARG; v8::Local<v8::Array> a = v8::Local<v8::Array>::Cast(v); result_t hr; for (int32_t i = 0; i < (int32_t)a->Length(); i ++) { T vr; hr = GetArgumentValue(a->Get(i), vr, true); if (hr < 0) return hr; n.append(vr); } return 0; }
result_t RedisSortedSet::add(v8::Local<v8::Object> sms, int32_t &retVal) { if (sms->IsArray()) return CHECK_ERROR(CALL_E_INVALIDARG); v8::Local<v8::Array> keys = sms->GetPropertyNames(); v8::Local<v8::Array> mss = v8::Array::New(holder()->m_isolate); int32_t i, n = 0; for (i = 0; i < (int32_t)keys->Length(); i ++) { v8::Local<v8::Value> v = keys->Get(i); mss->Set(n++, sms->Get(v)); mss->Set(n++, v); } return m_rdb->doCommand("ZADD", m_key, mss, retVal); }
void Msg_Struct::build_buffer_vector(const Field_Info &field_info, Block_Buffer &buffer, Isolate* isolate, v8::Local<v8::Value> value) { if (!value->IsArray()) { LOG_ERROR("field_name:%s is not array, struct_name:%s", field_info.field_name.c_str(), struct_name().c_str()); buffer.write_uint16(0); return; } Local<Array> array = Local<Array>::Cast(value); int16_t len = array->Length(); buffer.write_uint16(len); for (int i = 0; i < len; ++i) { Local<Value> element = array->Get(isolate->GetCurrentContext(), i).ToLocalChecked(); if(is_struct(field_info.field_type)) { build_buffer_struct(field_info, buffer, isolate, element); } else { build_buffer_arg(field_info, buffer, isolate, element); } } }
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; }
v8::Local<v8::Array> CFX_V8::ToArray(v8::Local<v8::Value> pValue) { if (pValue.IsEmpty() || !pValue->IsArray()) return v8::Local<v8::Array>(); v8::Local<v8::Context> context = m_pIsolate->GetCurrentContext(); return v8::Local<v8::Array>::Cast(pValue->ToObject(context).ToLocalChecked()); }
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!"); } } }
inline bool isObject(v8::Local<v8::Value> value) { Nan::HandleScope scope; return value->IsObject() && !value->IsArray(); }
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; }
result_t util_base::isArray(v8::Local<v8::Value> v, bool& retVal) { retVal = v->IsArray(); return 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)); } }
// 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; }
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; }
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; }