void MSMap::PropertySetter (Local<String> property, Local<Value> value, const AccessorInfo& info) { MSMap *map = ObjectWrap::Unwrap<MSMap>(info.Holder()); v8::String::AsciiValue n(property); if (strcmp(*n, "width") == 0) { map->this_->width = value->Int32Value(); } else if (strcmp(*n, "height") == 0) { map->this_->height = value->Int32Value(); } else if (strcmp(*n, "maxsize") == 0) { map->this_->maxsize = value->Int32Value(); } else if (strcmp(*n, "units") == 0) { int32_t units = value->Int32Value(); if (units >= MS_INCHES && units <= MS_NAUTICALMILES) { map->this_->units = (MS_UNITS) units; } } else if (strcmp(*n, "resolution") == 0) { map->this_->resolution = value->NumberValue(); } else if (strcmp(*n, "defresolution") == 0) { map->this_->defresolution = value->NumberValue(); } else if (strcmp(*n, "name") == 0) { REPLACE_STRING(map->this_->name, value); } else if (strcmp(*n, "imagetype") == 0) { REPLACE_STRING(map->this_->imagetype, value); } else if (strcmp(*n, "shapepath") == 0) { REPLACE_STRING(map->this_->shapepath, value); } else if (strcmp(*n, "projection") == 0) { v8::String::AsciiValue _v_(value->ToString()); msLoadProjectionString(&(map->this_->projection), *_v_); } else if (strcmp(*n, "mappath") == 0) { REPLACE_STRING(map->this_->mappath, value); } }
Handle<Value> Feature::addAttributes(const Arguments& args) { HandleScope scope; Feature* fp = ObjectWrap::Unwrap<Feature>(args.This()); if (args.Length() > 0 ) { Local<Value> value = args[0]; if (value->IsNull() || value->IsUndefined()) { return ThrowException(Exception::TypeError(String::New("object expected"))); } else { Local<Object> attr = value->ToObject(); try { Local<Array> names = attr->GetPropertyNames(); uint32_t i = 0; uint32_t a_length = names->Length(); boost::scoped_ptr<mapnik::transcoder> tr(new mapnik::transcoder("utf8")); while (i < a_length) { Local<Value> name = names->Get(i)->ToString(); Local<Value> value = attr->Get(name); if (value->IsString()) { UnicodeString ustr = tr->transcode(TOSTR(value)); boost::put(*fp->get(),TOSTR(name),ustr); } else if (value->IsNumber()) { double num = value->NumberValue(); // todo - round if (num == value->IntegerValue()) { int integer = value->IntegerValue(); boost::put(*fp->get(),TOSTR(name),integer); } else { double dub_val = value->NumberValue(); boost::put(*fp->get(),TOSTR(name),dub_val); } } else { std::clog << "unhandled type for property: " << TOSTR(name) << "\n"; } i++; } } catch (const std::exception & ex ) { return ThrowException(Exception::Error( String::New(ex.what()))); } catch (...) { return ThrowException(Exception::Error( String::New("Unknown exception happended - please report bug"))); } } } return Undefined(); }
void Msg_Struct::build_http_msg_buffer(Isolate* isolate, v8::Local<v8::Object> object, std::string &str) { std::stringstream stream; for(std::vector<Field_Info>::const_iterator iter = field_vec().begin(); iter != field_vec().end(); iter++) { stream.str(""); stream << "\"" << iter->field_name << "\":"; Local<Value> value = object->Get(isolate->GetCurrentContext(), String::NewFromUtf8(isolate, iter->field_name.c_str(), NewStringType::kNormal).ToLocalChecked()).ToLocalChecked(); if(iter->field_type == "int8" || iter->field_type == "int16" || iter->field_type == "int32") { int32_t val = 0; if (value->IsInt32()) { val = value->Int32Value(isolate->GetCurrentContext()).FromJust(); } stream << val << ","; } else if(iter->field_type == "int64") { int64_t val = 0; if (value->IsNumber()) { val = value->NumberValue(isolate->GetCurrentContext()).FromJust(); } stream << val << ","; } else if(iter->field_type == "double") { double val = 0; if (value->IsNumber()) { val = value->NumberValue(isolate->GetCurrentContext()).FromJust(); } stream << val << ","; } else if(iter->field_type == "bool") { bool val = 0; if (value->IsBoolean()) { val = value->BooleanValue(isolate->GetCurrentContext()).FromJust(); } stream << val << ","; } else if(iter->field_type == "string") { if (value->IsString()) { String::Utf8Value str(value->ToString(isolate->GetCurrentContext()).ToLocalChecked()); stream << "\"" << ToCString(str) << "\","; } else { stream << "\"\","; } } else { LOG_ERROR("Can not find the field_type:%s, struct_name:%s", iter->field_type.c_str(), struct_name().c_str()); } str += stream.str(); } }
void MSRect::PropertySetter (Local<String> property, Local<Value> value, const AccessorInfo& info) { MSRect *rect = ObjectWrap::Unwrap<MSRect>(info.Holder()); v8::String::AsciiValue n(property); double t; if (strcmp(*n, "minx") == 0) { rect->this_->minx = value->NumberValue(); } else if (strcmp(*n, "miny") == 0) { rect->this_->miny = value->NumberValue(); } else if (strcmp(*n, "maxx") == 0) { rect->this_->maxx = value->NumberValue(); } else if (strcmp(*n, "maxy") == 0) { rect->this_->maxy = value->NumberValue(); } }
/* static */ Handle<Value> MemoryObject::getMemObjectInfo(const Arguments& args) { HandleScope scope; MemoryObject *mo = ObjectWrap::Unwrap<MemoryObject>(args.This()); Local<Value> v = args[0]; cl_mem_info param_name = v->NumberValue(); size_t param_value_size_ret = 0; char param_value[1024]; cl_int ret = MemoryObjectWrapper::memoryObjectInfoHelper(mo->getMemoryObjectWrapper(), param_name, sizeof(param_value), param_value, ¶m_value_size_ret); if (ret != CL_SUCCESS) { WEBCL_COND_RETURN_THROW(CL_INVALID_VALUE); WEBCL_COND_RETURN_THROW(CL_INVALID_MEM_OBJECT); WEBCL_COND_RETURN_THROW(CL_OUT_OF_RESOURCES); WEBCL_COND_RETURN_THROW(CL_OUT_OF_HOST_MEMORY); return ThrowException(Exception::Error(String::New("UNKNOWN ERROR"))); } switch (param_name) { case CL_MEM_TYPE: case CL_MEM_FLAGS: case CL_MEM_REFERENCE_COUNT: case CL_MEM_MAP_COUNT: return scope.Close(Integer::NewFromUnsigned(*(cl_uint*)param_value)); case CL_MEM_SIZE: case CL_MEM_OFFSET: return scope.Close(Number::New(*(size_t*)param_value)); case CL_MEM_ASSOCIATED_MEMOBJECT: { cl_mem mem = *((cl_mem*)param_value); MemoryObjectWrapper *mw = new MemoryObjectWrapper(mem); return scope.Close(MemoryObject::New(mw)->handle_); } case CL_MEM_HOST_PTR: { char *ptr = *((char**)param_value); param_name = CL_MEM_SIZE; ret = MemoryObjectWrapper::memoryObjectInfoHelper(mo->getMemoryObjectWrapper(), param_name, sizeof(param_value), param_value, ¶m_value_size_ret); if (ret != CL_SUCCESS) { WEBCL_COND_RETURN_THROW(CL_INVALID_VALUE); WEBCL_COND_RETURN_THROW(CL_INVALID_MEM_OBJECT); WEBCL_COND_RETURN_THROW(CL_OUT_OF_RESOURCES); WEBCL_COND_RETURN_THROW(CL_OUT_OF_HOST_MEMORY); return ThrowException(Exception::Error(String::New("UNKNOWN ERROR"))); } size_t nbytes = *(size_t*)param_value; return scope.Close(node::Buffer::New(ptr, nbytes)->handle_); } default: return ThrowException(Exception::Error(String::New("UNKNOWN param_name"))); } }
/* Set the shared PRU RAM to an input array * Takes an integer array as input, writes it to PRU shared memory * Not much error checking here, don't pass in large arrays or seg faults will happen * TODO: error checking and allow user to select range to set */ Handle<Value> setSharedRAM(const Arguments& args) { HandleScope scope; //Check we have a single argument if (args.Length() != 1) { ThrowException(Exception::TypeError(String::New("Wrong number of arguments"))); return scope.Close(Undefined()); } //Check that it's an array if (!args[0]->IsArray()) { ThrowException(Exception::TypeError(String::New("Argument must be array"))); return scope.Close(Undefined()); } //Get array Local<Array> a = Array::Cast(*args[0]); //Iterate over array for (unsigned int i = 0; i<a->Length(); i++) { //Get element and check it's numeric Local<Value> element = a->Get(i); if (!element->IsNumber()) { ThrowException(Exception::TypeError(String::New("Array must be integer"))); return scope.Close(Undefined()); } //Set corresponding memory bytes sharedMem_int[OFFSET_SHAREDRAM + i] = (unsigned int) element->NumberValue(); } //Return nothing return scope.Close(Undefined()); };
Handle<Value> Dataset::setGeoTransform(const Arguments& args) { Dataset *ds = ObjectWrap::Unwrap<Dataset>(args.This()); if(!ds->this_) return NODE_THROW("Dataset object has already been destroyed"); Handle<Array> transform; NODE_ARG_ARRAY(0, "transform", transform); if (transform->Length() != 6) { return NODE_THROW("Transform array must have 6 elements") } double buffer[6]; for (int i = 0; i < 6; i++) { Local<Value> val = transform->Get(i); if (!val->IsNumber()) { return NODE_THROW("Transform array must only contain numbers"); } buffer[i] = val->NumberValue(); } CPLErr err = ds->this_->SetGeoTransform(buffer); if (err) return NODE_THROW_CPLERR(err); return Undefined(); }
void WrappedPoly::SetCoeff(Local<String> property, Local<Value> value, const PropertyCallbackInfo<void>& info) { WrappedPoly* obj = ObjectWrap::Unwrap<WrappedPoly>(info.This()); v8::String::Utf8Value s(property); std::string str(*s); if ( str == "a") { obj->a_ = value->NumberValue(); } else if (str == "b") { obj->b_ = value->NumberValue(); } else if (str == "c") { obj->c_ = value->NumberValue(); } }
void Point::SetX( Local< String > prop, Local< Value > value, const PropertyCallbackInfo< void > &info ) { // Enter new scope HandleScope scope; // Get wrapped object Local< Object > self = info.Holder(); Local< External > wrap = Local< External >::Cast( self->GetInternalField( 0 ) ); // Set internal value static_cast< Point* >( wrap->Value() )->SetX( value->NumberValue() ); }
void Point::zSetter(Local<String> property, Local<Value> value, const AccessorInfo &info) { Point *geom = ObjectWrap::Unwrap<Point>(info.This()); if (!value->IsNumber()) { NODE_THROW("z must be a number"); return; } double z = value->NumberValue(); ((OGRPoint* )geom->this_)->setZ(z); }
/*! Get the name of an audio device with a given ID number */ v8::Handle<v8::Value> Audio::AudioEngine::getDeviceName( const v8::Arguments& args ) { HandleScope scope; if( !args[0]->IsNumber() ) { return scope.Close( ThrowException(Exception::TypeError(String::New("getDeviceName() requires a device index"))) ); } Local<Number> deviceIndex = Local<Number>::Cast( args[0] ); const PaDeviceInfo* pDeviceInfo = Pa_GetDeviceInfo( (PaDeviceIndex)deviceIndex->NumberValue() ); return scope.Close( String::New(pDeviceInfo->name) ); } // end AudioEngine::GetDeviceName()
int TiUtils::getDateTime(Handle<Value> value, QDateTime& dt) { if ((value.IsEmpty()) || (!value->IsDate())) { return NATIVE_ERROR_INVALID_ARG; } unsigned int year = 0, month = 0, day = 0; Local<Object> object = Object::Cast(*value); // Get year from date Local<Value> getYear_prop = (object->Get(String::New("getFullYear"))); if (getYear_prop->IsFunction()) { Local<Function> getYear_func = Function::Cast(*getYear_prop); Local<Value> yearValue = getYear_func->Call(object, 0, NULL); year = yearValue->NumberValue(); } // Get month from date Local<Value> getMonth_prop = (object->Get(String::New("getMonth"))); if (getMonth_prop->IsFunction()) { Local<Function> getMonth_func = Function::Cast(*getMonth_prop); Local<Value> monthValue = getMonth_func->Call(object, 0, NULL); month = monthValue->NumberValue(); } // Get day property Local<Value> getDay_prop = (object->Get(String::New("getDate"))); if (getDay_prop->IsFunction()) { Local<Function> getDay_func = Function::Cast(*getDay_prop); Local<Value> dayValue = getDay_func->Call(object, 0, NULL); day = dayValue->NumberValue(); } dt.setDate(QDate(year, month, day)); return NATIVE_ERROR_OK; }
void UiWindow::SetOpacity(Local<String> property, Local<Value> value, const PropertyCallbackInfo<void>& info) { Isolate* isolate = Isolate::GetCurrent(); HandleScope scope(isolate); UiWindow* _this = Unwrap<UiWindow>(info.This()); double opacity = value->NumberValue(); if (opacity < 0) { opacity = 0; } if (opacity > 1) { opacity = 1; } _this->SetOpacity(opacity); }
static double getNumber(Handle<Object> obj, QString key, double minValue, double defaultValue) { Isolate* current = v8::Isolate::GetCurrent(); HandleScope handleScope(current); double result = defaultValue; Handle<String> cdtKey = String::NewFromUtf8(current, key.toUtf8()); if (obj->Has(cdtKey)) { Local<Value> v = obj->Get(cdtKey); if (v->IsNumber() == false || ::qIsNaN(v->NumberValue())) { throw IllegalArgumentException("Expected " + key + " to be a number."); } result = v->NumberValue(); if (result < minValue) { throw IllegalArgumentException(QString("Expected %1 to be greater than %2.") .arg(key).arg(minValue)); } } return result; }
/* static */ Handle<Value> KernelObject::getKernelWorkGroupInfo(const Arguments& args) { HandleScope scope; KernelObject *kernelObject = ObjectWrap::Unwrap<KernelObject>(args.This()); Device *device = ObjectWrap::Unwrap<Device>(args[0]->ToObject()); Local<Value> v = args[1]; cl_kernel_work_group_info param_name = v->NumberValue(); size_t param_value_size_ret = 0; char param_value[1024]; cl_int ret = KernelWrapper::kernelWorkGroupInfoHelper(kernelObject->getKernelWrapper(), device->getDeviceWrapper(), param_name, sizeof(param_value), param_value, ¶m_value_size_ret); if (ret != CL_SUCCESS) { WEBCL_COND_RETURN_THROW(CL_INVALID_DEVICE); WEBCL_COND_RETURN_THROW(CL_INVALID_VALUE); WEBCL_COND_RETURN_THROW(CL_INVALID_KERNEL); WEBCL_COND_RETURN_THROW(CL_OUT_OF_RESOURCES); WEBCL_COND_RETURN_THROW(CL_OUT_OF_HOST_MEMORY); return ThrowException(Exception::Error(String::New("UNKNOWN ERROR"))); } switch (param_name) { case CL_KERNEL_WORK_GROUP_SIZE: case CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE: return scope.Close(Number::New(*(size_t*)param_value)); case CL_KERNEL_LOCAL_MEM_SIZE: case CL_KERNEL_PRIVATE_MEM_SIZE: return scope.Close(Number::New(*(cl_ulong*)param_value)); case CL_KERNEL_COMPILE_WORK_GROUP_SIZE: { Local<Array> sizeArray = Array::New(3); for (size_t i=0; i<3; i++) { size_t s = ((size_t*)param_value)[i]; sizeArray->Set(i, Number::New(s)); } return scope.Close(sizeArray); } default: return ThrowException(Exception::Error(String::New("UNKNOWN param_name"))); } }
/* static */ Handle<Value> MemoryObject::getImageInfo(const Arguments& args) { HandleScope scope; MemoryObject *mo = ObjectWrap::Unwrap<MemoryObject>(args.This()); Local<Value> v = args[0]; cl_mem_info param_name = v->NumberValue(); size_t param_value_size_ret = 0; char param_value[1024]; cl_int ret = MemoryObjectWrapper::imageInfoHelper(mo->getMemoryObjectWrapper(), param_name, sizeof(param_value), param_value, ¶m_value_size_ret); if (ret != CL_SUCCESS) { WEBCL_COND_RETURN_THROW(CL_INVALID_VALUE); WEBCL_COND_RETURN_THROW(CL_INVALID_MEM_OBJECT); WEBCL_COND_RETURN_THROW(CL_OUT_OF_RESOURCES); WEBCL_COND_RETURN_THROW(CL_OUT_OF_HOST_MEMORY); return ThrowException(Exception::Error(String::New("UNKNOWN ERROR"))); } switch (param_name) { case CL_IMAGE_ELEMENT_SIZE: case CL_IMAGE_ROW_PITCH: case CL_IMAGE_SLICE_PITCH: case CL_IMAGE_WIDTH: case CL_IMAGE_HEIGHT: case CL_IMAGE_DEPTH: return scope.Close(Number::New(*(size_t*)param_value)); case CL_IMAGE_FORMAT: { cl_channel_order channel_order = *(cl_channel_order*)param_value; cl_channel_type channel_type = *(cl_channel_type*)(param_value + sizeof(cl_channel_order)); Local<Object> obj = Object::New(); obj->Set(String::New("cl_channel_order"), Number::New(channel_order)); obj->Set(String::New("cl_channel_type"), Number::New(channel_type)); return scope.Close(obj); } default: return ThrowException(Exception::Error(String::New("UNKNOWN param_name"))); } }
/*! Changes the output device */ v8::Handle<v8::Value> Audio::AudioEngine::SetOutputDevice( const v8::Arguments& args ) { HandleScope scope; // Validate the output args if( !args[0]->IsNumber() ) { return ThrowException( Exception::TypeError(String::New("setOutputDevice() requires a device index")) ); } Local<Number> deviceIndex = Local<Number>::Cast( args[0] ); AudioEngine* engine = AudioEngine::Unwrap<AudioEngine>( args.This() ); // Set the new output device engine->m_outputParameters.device = deviceIndex->NumberValue(); // Restart the audio stream engine->restartStream( engine ); return scope.Close( Undefined() ); } // end AudioEngine::SetOutputDevice()
/* static */ Handle<Value> Sampler::getSamplerInfo(const Arguments& args) { HandleScope scope; Sampler *sampler = ObjectWrap::Unwrap<Sampler>(args.This()); Local<Value> v = args[0]; cl_sampler_info param_name = v->NumberValue(); size_t param_value_size_ret = 0; char param_value[1024]; cl_int ret = SamplerWrapper::samplerInfoHelper(sampler->getSamplerWrapper(), param_name, sizeof(param_value), param_value, ¶m_value_size_ret); if (ret != CL_SUCCESS) { WEBCL_COND_RETURN_THROW(CL_INVALID_VALUE); WEBCL_COND_RETURN_THROW(CL_INVALID_SAMPLER); WEBCL_COND_RETURN_THROW(CL_OUT_OF_RESOURCES); WEBCL_COND_RETURN_THROW(CL_OUT_OF_HOST_MEMORY); return ThrowException(Exception::Error(String::New("UNKNOWN ERROR"))); } switch (param_name) { case CL_SAMPLER_ADDRESSING_MODE: case CL_SAMPLER_FILTER_MODE: case CL_SAMPLER_REFERENCE_COUNT: return scope.Close(Number::New(*(cl_uint*)param_value)); case CL_SAMPLER_CONTEXT:{ cl_context ctx = *((cl_context*)param_value); ContextWrapper *cw = new ContextWrapper(ctx); return scope.Close(CLContext::New(cw)->handle_); } case CL_SAMPLER_NORMALIZED_COORDS: { cl_bool b = *((cl_bool*)param_value); return scope.Close(Boolean::New(b ? true : false )); } default: return ThrowException(Exception::Error(String::New("UNKNOWN param_name"))); } }
static double getNumber(Handle<Object> obj, QString key, double minValue, double defaultValue) { double result = defaultValue; Handle<String> cdtKey = String::New(key.toUtf8()); if (obj->Has(cdtKey)) { Local<Value> v = obj->Get(cdtKey); if (v->IsNumber() == false) { throw IllegalArgumentException("Expected " + key + " to be a number."); } result = v->NumberValue(); if (result < minValue) { throw IllegalArgumentException(QString("Expected %1 to be greater than %2.") .arg(key).arg(minValue)); } } return result; }
/* static */ Handle<Value> KernelObject::getKernelInfo(const Arguments& args) { HandleScope scope; KernelObject *kernelObject = ObjectWrap::Unwrap<KernelObject>(args.This()); Local<Value> v = args[0]; cl_kernel_info param_name = v->NumberValue(); size_t param_value_size_ret = 0; char param_value[1024]; cl_int ret = KernelWrapper::kernelInfoHelper(kernelObject->getKernelWrapper(), param_name, sizeof(param_value), param_value, ¶m_value_size_ret); if (ret != CL_SUCCESS) { WEBCL_COND_RETURN_THROW(CL_INVALID_VALUE); WEBCL_COND_RETURN_THROW(CL_INVALID_KERNEL); WEBCL_COND_RETURN_THROW(CL_OUT_OF_RESOURCES); WEBCL_COND_RETURN_THROW(CL_OUT_OF_HOST_MEMORY); return ThrowException(Exception::Error(String::New("UNKNOWN ERROR"))); } switch (param_name) { case CL_KERNEL_FUNCTION_NAME: return scope.Close(String::New(param_value)); case CL_KERNEL_NUM_ARGS: case CL_KERNEL_REFERENCE_COUNT: return scope.Close(Number::New(*(size_t*)param_value)); case CL_KERNEL_CONTEXT: { cl_context ctx = *((cl_context*)param_value); ContextWrapper *cw = new ContextWrapper(ctx); return scope.Close(CLContext::New(cw)->handle_); } case CL_KERNEL_PROGRAM: { cl_program p = *((cl_program*)param_value); ProgramWrapper *pw = new ProgramWrapper(p); return scope.Close(ProgramObject::New(pw)->handle_); } default: return scope.Close(Number::New(*(size_t*)param_value)); } }
void PassArray(const FunctionCallbackInfo<Value>& args) { Isolate * isolate = args.GetIsolate(); Local<Array> array = Local<Array>::Cast(args[0]); if ( args.Length() < 1 || ! args[0]->IsArray()) { return; } if (array->Length() < 3) { return; } Local<String> prop = String::NewFromUtf8(isolate, "not_index"); if (array->Get(prop)->IsUndefined() ){ return; } for (unsigned int i = 0; i < 3; i++ ) { if (array->Has(i)) { Local<Value> v = array->Get(i); if ( !v->IsNumber()) return; double value = v->NumberValue(); array->Set(i, Number::New(isolate, value + 1)); } else { return; } } Local<Array> a = Array::New(isolate); a->Set(0, array->Get(0)); a->Set(1, array->Get(prop)); a->Set(2, array->Get(2)); args.GetReturnValue().Set(a); }
mapnik::feature_ptr next() { HandleScope scope; TryCatch try_catch; Local<Value> argv[2] = { Integer::New(feature_id_), obj_ }; Local<Value> val = ds_->cb_->Call(Context::GetCurrent()->Global(), 2, argv); if (try_catch.HasCaught()) { FatalException(try_catch); } else { if (!val->IsUndefined()) { if (val->IsObject()) { Local<Object> obj = val->ToObject(); if (obj->Has(String::New("x")) && obj->Has(String::New("y"))) { Local<Value> x = obj->Get(String::New("x")); Local<Value> y = obj->Get(String::New("y")); if (!x->IsUndefined() && x->IsNumber() && !y->IsUndefined() && y->IsNumber()) { mapnik::geometry_type * pt = new mapnik::geometry_type(mapnik::Point); pt->move_to(x->NumberValue(),y->NumberValue()); mapnik::feature_ptr feature(mapnik::feature_factory::create(feature_id_)); ++feature_id_; feature->add_geometry(pt); if (obj->Has(String::New("properties"))) { Local<Value> props = obj->Get(String::New("properties")); if (props->IsObject()) { Local<Object> p_obj = props->ToObject(); Local<Array> names = p_obj->GetPropertyNames(); uint32_t i = 0; uint32_t a_length = names->Length(); while (i < a_length) { Local<Value> name = names->Get(i)->ToString(); // if name in q.property_names() ? Local<Value> value = p_obj->Get(name); if (value->IsString()) { UnicodeString ustr = tr_->transcode(TOSTR(value)); boost::put(*feature,TOSTR(name),ustr); } else if (value->IsNumber()) { double num = value->NumberValue(); // todo - round if (num == value->IntegerValue()) { int integer = value->IntegerValue(); boost::put(*feature,TOSTR(name),integer); } else { double dub_val = value->NumberValue(); boost::put(*feature,TOSTR(name),dub_val); } } i++; } } } return feature; } } } } } return mapnik::feature_ptr(); }
void FieldAccessor::SetJavaField(Isolate *isolate, const Local<Object>& target, const Local<Value>& value, FieldCallbackData *fieldData) { JEnv env; HandleScope handleScope(isolate); auto runtime = Runtime::GetRuntime(isolate); auto objectManager = runtime->GetObjectManager(); JniLocalRef targetJavaObject; const auto& fieldTypeName = fieldData->signature; auto isStatic = fieldData->isStatic; auto isPrimitiveType = fieldTypeName.size() == 1; auto isFieldArray = fieldTypeName[0] == '['; if (fieldData->fid == nullptr) { auto fieldJniSig = isPrimitiveType ? fieldTypeName : (isFieldArray ? fieldTypeName : ("L" + fieldTypeName + ";")); if (isStatic) { fieldData->clazz = env.FindClass(fieldData->declaringType); assert(fieldData->clazz != nullptr); fieldData->fid = env.GetStaticFieldID(fieldData->clazz, fieldData->name, fieldJniSig); assert(fieldData->fid != nullptr); } else { fieldData->clazz = env.FindClass(fieldData->declaringType); assert(fieldData->clazz != nullptr); fieldData->fid = env.GetFieldID(fieldData->clazz, fieldData->name, fieldJniSig); assert(fieldData->fid != nullptr); } } if (!isStatic) { targetJavaObject = objectManager->GetJavaObjectByJsObject(target); if (targetJavaObject.IsNull()) { stringstream ss; ss << "Cannot access property '" << fieldData->name << "' because there is no corresponding Java object"; throw NativeScriptException(ss.str()); } } auto fieldId = fieldData->fid; auto clazz = fieldData->clazz; if (isPrimitiveType) { switch (fieldTypeName[0]) { case 'Z': //bool { //TODO: validate value is a boolean before calling if (isStatic) { env.SetStaticBooleanField(clazz, fieldId, value->BooleanValue()); } else { env.SetBooleanField(targetJavaObject, fieldId, value->BooleanValue()); } break; } case 'B': //byte { //TODO: validate value is a byte before calling if (isStatic) { env.SetStaticByteField(clazz, fieldId, value->Int32Value()); } else { env.SetByteField(targetJavaObject, fieldId, value->Int32Value()); } break; } case 'C': //char { //TODO: validate value is a single char String::Utf8Value stringValue(value->ToString()); JniLocalRef value(env.NewStringUTF(*stringValue)); const char* chars = env.GetStringUTFChars(value, 0); if (isStatic) { env.SetStaticCharField(clazz, fieldId, chars[0]); } else { env.SetCharField(targetJavaObject, fieldId, chars[0]); } env.ReleaseStringUTFChars(value, chars); break; } case 'S': //short { //TODO: validate value is a short before calling if (isStatic) { env.SetStaticShortField(clazz, fieldId, value->Int32Value()); } else { env.SetShortField(targetJavaObject, fieldId, value->Int32Value()); } break; } case 'I': //int { //TODO: validate value is a int before calling if (isStatic) { env.SetStaticIntField(clazz, fieldId, value->Int32Value()); } else { env.SetIntField(targetJavaObject, fieldId, value->Int32Value()); } break; } case 'J': //long { jlong longValue = static_cast<jlong>(ArgConverter::ConvertToJavaLong(value)); if (isStatic) { env.SetStaticLongField(clazz, fieldId, longValue); } else { env.SetLongField(targetJavaObject, fieldId, longValue); } break; } case 'F': //float { if (isStatic) { env.SetStaticFloatField(clazz, fieldId, static_cast<jfloat>(value->NumberValue())); } else { env.SetFloatField(targetJavaObject, fieldId, static_cast<jfloat>(value->NumberValue())); } break; } case 'D': //double { if (isStatic) { env.SetStaticDoubleField(clazz, fieldId, value->NumberValue()); } else { env.SetDoubleField(targetJavaObject, fieldId, value->NumberValue()); } break; } default: { stringstream ss; ss << "(InternalError): in FieldAccessor::SetJavaField: Unknown field type: '" << fieldTypeName[0] << "'"; throw NativeScriptException(ss.str()); } } } else { bool isString = fieldTypeName == "java/lang/String"; JniLocalRef result; if (!value->IsNull()) { if (isString) { //TODO: validate valie is a string; result = ConvertToJavaString(value); } else { auto objectWithHiddenID = value->ToObject(); result = objectManager->GetJavaObjectByJsObject(objectWithHiddenID); } } if (isStatic) { env.SetStaticObjectField(clazz, fieldId, result); } else { env.SetObjectField(targetJavaObject, fieldId, result); } } }
void FieldAccessor::SetJavaField(const Local<Object>& target, const Local<Value>& value, FieldCallbackData *fieldData) { JEnv env; auto isolate = Isolate::GetCurrent(); HandleScope handleScope(isolate); jweak targetJavaObject; const auto& fieldTypeName = fieldData->signature; auto isStatic = fieldData->isStatic; auto isPrimitiveType = fieldTypeName.size() == 1; auto isFieldArray = fieldTypeName[0] == '['; if (fieldData->fid == nullptr) { auto fieldJniSig = isPrimitiveType ? fieldTypeName : (isFieldArray ? fieldTypeName : ("L" + fieldTypeName + ";")); if (isStatic) { fieldData->clazz = env.FindClass(fieldData->declaringType); assert(fieldData->clazz != nullptr); fieldData->fid = env.GetStaticFieldID(fieldData->clazz, fieldData->name, fieldJniSig); assert(fieldData->fid != nullptr); } else { fieldData->clazz = env.FindClass(fieldData->declaringType); assert(fieldData->clazz != nullptr); fieldData->fid = env.GetFieldID(fieldData->clazz, fieldData->name, fieldJniSig); assert(fieldData->fid != nullptr); } } if (!isStatic) { targetJavaObject = objectManager->GetJavaObjectByJsObject(target); } auto fieldId = fieldData->fid; auto clazz = fieldData->clazz; if (isPrimitiveType) { switch (fieldTypeName[0]) { case 'Z': //bool { //TODO: validate value is a boolean before calling if (isStatic) { env.SetStaticBooleanField(clazz, fieldId, value->BooleanValue()); } else { env.SetBooleanField(targetJavaObject, fieldId, value->BooleanValue()); } break; } case 'B': //byte { //TODO: validate value is a byte before calling if (isStatic) { env.SetStaticByteField(clazz, fieldId, value->Int32Value()); } else { env.SetByteField(targetJavaObject, fieldId, value->Int32Value()); } break; } case 'C': //char { //TODO: validate value is a single char String::Utf8Value stringValue(value->ToString()); JniLocalRef value(env.NewStringUTF(*stringValue)); const char* chars = env.GetStringUTFChars(value, 0); if (isStatic) { env.SetStaticCharField(clazz, fieldId, chars[0]); } else { env.SetCharField(targetJavaObject, fieldId, chars[0]); } env.ReleaseStringUTFChars(value, chars); break; } case 'S': //short { //TODO: validate value is a short before calling if (isStatic) { env.SetStaticShortField(clazz, fieldId, value->Int32Value()); } else { env.SetShortField(targetJavaObject, fieldId, value->Int32Value()); } break; } case 'I': //int { //TODO: validate value is a int before calling if (isStatic) { env.SetStaticIntField(clazz, fieldId, value->Int32Value()); } else { env.SetIntField(targetJavaObject, fieldId, value->Int32Value()); } break; } case 'J': //long { jlong longValue = static_cast<jlong>(ArgConverter::ConvertToJavaLong(value)); if (isStatic) { env.SetStaticLongField(clazz, fieldId, longValue); } else { env.SetLongField(targetJavaObject, fieldId, longValue); } break; } case 'F': //float { if (isStatic) { env.SetStaticFloatField(clazz, fieldId, static_cast<jfloat>(value->NumberValue())); } else { env.SetFloatField(targetJavaObject, fieldId, static_cast<jfloat>(value->NumberValue())); } break; } case 'D': //double { if (isStatic) { env.SetStaticDoubleField(clazz, fieldId, value->NumberValue()); } else { env.SetDoubleField(targetJavaObject, fieldId, value->NumberValue()); } break; } default: { // TODO: ASSERT_FAIL("Unknown field type"); break; } } } else { bool isString = fieldTypeName == "java/lang/String"; jobject result = nullptr; if(!value->IsNull()) { if (isString) { //TODO: validate valie is a string; result = ConvertToJavaString(value); } else { auto objectWithHiddenID = value->ToObject(); result =objectManager->GetJavaObjectByJsObject(objectWithHiddenID); } } if (isStatic) { env.SetStaticObjectField(clazz, fieldId, result); } else { env.SetObjectField(targetJavaObject, fieldId, result); } if (isString) { env.DeleteLocalRef(result); } } }
//! \verbatim //! Quaternion.z //! \endverbatim void Quaternion::jsSetZ( Local<v8::String> prop, Local<v8::Value> value, const PropertyCallbackInfo<void>& info ) { Quaternion* ptr = unwrap( info.This() ); ptr->z = value->NumberValue(); }
/*----------------------------------------------------------------------------- * Parse options */ bool ConnectParseOptions(Local<Object> options, ConnectRequest* request) { // Get options data std::vector<std::string> optionNames = cvv8::CastFromJS<std::vector<std::string> >(options->GetPropertyNames()); for (size_t i = 0; i < optionNames.size(); i++) { char* optionName = (char*)(optionNames[i].c_str()); Local<Value> optionValue = options->Get(String::NewSymbol(optionName)); if (optionValue->IsUndefined()) { continue; } if (tva_str_casecmp(optionName, "username") == 0) { String::AsciiValue val(optionValue->ToString()); request->username = strdup(*val); } else if (tva_str_casecmp(optionName, "password") == 0) { String::AsciiValue val(optionValue->ToString()); request->password = strdup(*val); } else if (tva_str_casecmp(optionName, "tmx") == 0) { if (optionValue->IsString()) { String::AsciiValue val(optionValue->ToString()); request->primaryTmx = strdup(*val); } else if (optionValue->IsArray()) { Handle<Array> tmxs = Handle<Array>::Cast(optionValue); char** p_tmx = &request->primaryTmx; Local<Value> element; element = tmxs->Get(0); if (!element->IsUndefined()) { String::AsciiValue tmx(element->ToString()); *p_tmx = strdup(*tmx); p_tmx = &request->secondaryTmx; } if (tmxs->Length() > 1) { element = tmxs->Get(1); if (!element->IsUndefined()) { String::AsciiValue tmx(element->ToString()); *p_tmx = strdup(*tmx); } } } } else if (tva_str_casecmp(optionName, "name") == 0) { String::AsciiValue val(optionValue->ToString()); request->gdClientName = strdup(*val); } else if (tva_str_casecmp(optionName, "timeout") == 0) { request->timeout = optionValue->Int32Value() * 1000; } else if (tva_str_casecmp(optionName, "gdMaxOut") == 0) { request->gdMaxOut = optionValue->Int32Value(); } else if (tva_str_casecmp(optionName, "config") == 0) { if (optionValue->IsObject()) { Local<Object> config = Local<Object>::Cast(optionValue); std::vector<std::string> configNames = cvv8::CastFromJS<std::vector<std::string> >(config->GetPropertyNames()); for (size_t j = 0; j < configNames.size(); j++) { char* configName = (char*)(configNames[j].c_str()); Local<Value> configValue = config->Get(String::NewSymbol(configName)); if (configValue->IsUndefined()) { continue; } for (size_t c = 0; c < NUM_PARAMS; c++) { ConnectConfigParam* cp = &g_connectConfig[c]; if (tva_str_casecmp(configName, cp->jsName) == 0) { switch (cp->configType) { case ConfigTypeBool: { bool bVal; if (configValue->IsBoolean()) { bVal = configValue->BooleanValue(); } else if (configValue->IsNumber()) { bVal = (configValue->NumberValue() != 0); } else if (configValue->IsString()) { String::AsciiValue bStrVal(config->ToString()); bVal = (tva_str_casecmp(*bStrVal, "true") == 0); } tvaAppCfgSet(cp->tvaParam, &bVal, (TVA_INT32)sizeof(bVal)); } break; case ConfigTypeInt: { int intVal = configValue->Int32Value(); tvaAppCfgSet(cp->tvaParam, &intVal, (TVA_INT32)sizeof(intVal)); } break; case ConfigTypeString: { String::AsciiValue strVal(configValue->ToString()); tvaAppCfgSet(cp->tvaParam, *strVal, (TVA_INT32)strlen(*strVal)); } break; case ConfigTypeCustom: if (cp->tvaParam == TVA_APPCFG_DATA_TRANSPORT_TYPE) { TVA_DATATRANSPORT_TYPE transportType = TVA_DATATRANSPORT_UDP; if (configValue->IsString()) { String::AsciiValue strVal(config->ToString()); if (tva_str_casecmp(*strVal, "TCP")) { transportType = TVA_DATATRANSPORT_TCP; } else if (tva_str_casecmp(*strVal, "SSL")) { transportType = TVA_DATATRANSPORT_SSL; } } else if (configValue->IsNumber()) { int numVal = (int)configValue->NumberValue(); if ((numVal == TVA_DATATRANSPORT_TCP) || (numVal == TVA_DATATRANSPORT_SSL)) { transportType = (TVA_DATATRANSPORT_TYPE)numVal; } } tvaAppCfgSet(cp->tvaParam, &transportType, (TVA_INT32)sizeof(transportType)); } break; } break; } } } } } } // Make sure required arguments were specified if (!request->username || !request->password || !request->primaryTmx) { return false; } return true; }
Handle<Value> Session::Request(const Arguments& args) { HandleScope scope; if (args.Length() < 1 || !args[0]->IsString()) { return ThrowException(Exception::Error(String::New( "Service URI string must be provided as first parameter."))); } if (args.Length() < 2 || !args[1]->IsString()) { return ThrowException(Exception::Error(String::New( "String request name must be provided as second parameter."))); } if (args.Length() < 3 || !args[2]->IsObject()) { return ThrowException(Exception::Error(String::New( "Object containing request parameters must be provided " "as third parameter."))); } if (args.Length() < 4 || !args[3]->IsInt32()) { return ThrowException(Exception::Error(String::New( "Integer correlation identifier must be provided " "as fourth parameter."))); } if (args.Length() >= 5 && !args[4]->IsUndefined() && !args[4]->IsString()) { return ThrowException(Exception::Error(String::New( "Optional request label must be a string."))); } if (args.Length() > 5) { return ThrowException(Exception::Error(String::New( "Function expects at most five arguments."))); } int cidi = args[3]->Int32Value(); Session* session = ObjectWrap::Unwrap<Session>(args.This()); BLPAPI_EXCEPTION_TRY Local<String> uri = args[0]->ToString(); String::AsciiValue uriv(uri); blpapi::Service service = session->d_session->getService(*uriv); Local<String> name = args[1]->ToString(); String::Utf8Value namev(name); blpapi::Request request = service.createRequest(*namev); // Loop over object properties, appending/setting into the request. Local<Object> obj = args[2]->ToObject(); Local<Array> props = obj->GetPropertyNames(); for (std::size_t i = 0; i < props->Length(); ++i) { // Process the key. Local<Value> keyval = props->Get(i); Local<String> key = keyval->ToString(); String::Utf8Value keyv(key); // Process the value. // // The values present on the outer object are marshalled into the // blpapi::Request by setting values using 'set'. Arrays indicate // values which should be marshalled using 'append'. Local<Value> val = obj->Get(keyval); if (val->IsString()) { Local<String> s = val->ToString(); String::Utf8Value valv(s); request.set(*keyv, *valv); } else if (val->IsBoolean()) { request.set(*keyv, val->BooleanValue()); } else if (val->IsNumber()) { request.set(*keyv, val->NumberValue()); } else if (val->IsInt32()) { request.set(*keyv, val->Int32Value()); } else if (val->IsUint32()) { request.set(*keyv, static_cast<blpapi::Int64>(val->Uint32Value())); } else if (val->IsDate()) { blpapi::Datetime dt; mkdatetime(&dt, val); request.set(*keyv, dt); } else if (val->IsArray()) { // Arrays are marshalled into the blpapi::Request by appending // value types using the key of the array in the outer object. Local<Object> subarray = val->ToObject(); int jmax = Array::Cast(*val)->Length(); for (int j = 0; j < jmax; ++j) { Local<Value> subval = subarray->Get(j); // Only strings, booleans, and numbers are marshalled. if (subval->IsString()) { Local<String> s = subval->ToString(); String::Utf8Value subvalv(s); request.append(*keyv, *subvalv); } else if (subval->IsBoolean()) { request.append(*keyv, subval->BooleanValue()); } else if (subval->IsNumber()) { request.append(*keyv, subval->NumberValue()); } else if (subval->IsInt32()) { request.append(*keyv, subval->Int32Value()); } else if (subval->IsUint32()) { request.append(*keyv, static_cast<blpapi::Int64>(subval->Uint32Value())); } else if (subval->IsDate()) { blpapi::Datetime dt; mkdatetime(&dt, subval); request.append(*keyv, dt); } else { return ThrowException(Exception::Error(String::New( "Array contains invalid value type."))); } } } else { return ThrowException(Exception::Error(String::New( "Object contains invalid value type."))); } } blpapi::CorrelationId cid(cidi); if (args.Length() == 5) { String::Utf8Value labelv(args[4]->ToString()); session->d_session->sendRequest(request, session->d_identity, cid, 0, *labelv, labelv.length()); } else { session->d_session->sendRequest(request, session->d_identity, cid); } BLPAPI_EXCEPTION_CATCH_RETURN return scope.Close(Integer::New(cidi)); }
bool JsArgToArrayConverter::ConvertArg(const Local<Value>& arg, int index) { bool success = false; stringstream s; JEnv env; Type returnType = JType::getClassType(m_return_type); if (arg.IsEmpty()) { s << "Cannot convert empty JavaScript object"; success = false; } else if (arg->IsInt32() && (returnType == Type::Int || returnType == Type::Null)) { jint value = arg->Int32Value(); JniLocalRef javaObject(JType::NewInt(env, value)); SetConvertedObject(env, index, javaObject); success = true; } else if (arg->IsNumber() || arg->IsNumberObject()) { double d = arg->NumberValue(); int64_t i = (int64_t)d; bool isInteger = d == i; if (isInteger) { jobject obj; //if returnType is long it will cast to long //if there is no return type specified it will cast to int //because default return type is null (ref type) if ((INT_MIN <= i) && (i <= INT_MAX) && (returnType == Type::Int || returnType == Type::Null)) { obj = JType::NewInt(env, (jint)d); } else /*isLong*/ { obj = JType::NewLong(env, (jlong)d); } JniLocalRef javaObject(obj); SetConvertedObject(env, index, javaObject); success = true; } else { jobject obj; //if returnType is double it will cast to double //if there is no return type specified it will cast to float //because default return type is null (ref type) if((FLT_MIN <= d) && (d <= FLT_MAX) && (returnType == Type::Float || returnType == Type::Null)) { obj = JType::NewFloat(env, (jfloat)d); } else {/*isDouble*/ obj = JType::NewDouble(env, (jdouble)d); } JniLocalRef javaObject(obj); SetConvertedObject(env, index, javaObject); success = true; } } else if (arg->IsBoolean()) { jboolean value = arg->BooleanValue(); JniLocalRef javaObject(JType::NewBoolean(env, value)); SetConvertedObject(env, index, javaObject); success = true; } else if (arg->IsBooleanObject()) { auto boolObj = Local<BooleanObject>::Cast(arg); jboolean value = boolObj->BooleanValue() ? JNI_TRUE : JNI_FALSE; JniLocalRef javaObject(JType::NewBoolean(env, value)); SetConvertedObject(env, index, javaObject); success = true; } else if (arg->IsString() || arg->IsStringObject()) { JniLocalRef stringObject(ConvertToJavaString(arg)); SetConvertedObject(env, index, stringObject); success = true; } else if (arg->IsObject()) { auto objectWithHiddenID = arg->ToObject(); auto hidden = objectWithHiddenID->GetHiddenValue(V8StringConstants::GetMarkedAsLong()); if (!hidden.IsEmpty()) { jlong value = 0; if (hidden->IsString()) { auto strValue = ConvertToString(hidden->ToString()); value = atoll(strValue.c_str()); } else if (hidden->IsInt32()) { value = hidden->ToInt32()->Int32Value(); } JniLocalRef javaObject(JType::NewLong(env, value)); SetConvertedObject(env, index, javaObject); return true; } hidden = objectWithHiddenID->GetHiddenValue(V8StringConstants::GetMarkedAsByte()); if (!hidden.IsEmpty()) { jbyte value = 0; if (hidden->IsString()) { string value = ConvertToString(hidden->ToString()); int byteArg = atoi(value.c_str()); value = (jbyte)byteArg; } else if (hidden->IsInt32()) { int byteArg = hidden->ToInt32()->Int32Value(); value = (jbyte)byteArg; } JniLocalRef javaObject(JType::NewByte(env, value)); SetConvertedObject(env, index, javaObject); return true; } hidden = objectWithHiddenID->GetHiddenValue(V8StringConstants::GetMarkedAsShort()); if (!hidden.IsEmpty()) { jshort value = 0; if (hidden->IsString()) { string value = ConvertToString(hidden->ToString()); int shortArg = atoi(value.c_str()); value = (jshort)shortArg; } else if (hidden->IsInt32()) { jlong shortArg = hidden->ToInt32()->Int32Value(); value = (jshort)shortArg; } JniLocalRef javaObject(JType::NewShort(env, value)); SetConvertedObject(env, index, javaObject); return true; } hidden = objectWithHiddenID->GetHiddenValue(V8StringConstants::GetMarkedAsDouble()); if (!hidden.IsEmpty()) { jdouble value = 0; if (hidden->IsNumber()) { double doubleArg = hidden->ToNumber()->NumberValue(); value = (jdouble)doubleArg; } JniLocalRef javaObject(JType::NewDouble(env, value)); SetConvertedObject(env, index, javaObject); return true; } hidden = objectWithHiddenID->GetHiddenValue(V8StringConstants::GetMarkedAsFloat()); if (!hidden.IsEmpty()) { jfloat value = 0; if (hidden->IsNumber()) { double floatArg = hidden->ToNumber()->NumberValue(); value = (jfloat)floatArg; } JniLocalRef javaObject(JType::NewFloat(env, value)); SetConvertedObject(env, index, javaObject); return true; } hidden = objectWithHiddenID->GetHiddenValue(V8StringConstants::GetMarkedAsChar()); if (!hidden.IsEmpty()) { jchar value = '\0'; if (hidden->IsString()) { string str = ConvertToString(hidden->ToString()); value = (jchar)str[0]; } JniLocalRef javaObject(JType::NewChar(env, value)); SetConvertedObject(env, index, javaObject); return true; } jweak obj = ObjectManager::GetJavaObjectByJsObjectStatic(objectWithHiddenID); success = obj != nullptr; if (success) { SetConvertedObject(env, index, obj, true); } else { s << "Cannot convert JavaScript object with id " << objectWithHiddenID->GetIdentityHash() << " at index " << index; } } else if (arg->IsUndefined() || arg->IsNull()) { SetConvertedObject(env, index, nullptr); success = true; } else { s << "Cannot convert JavaScript object at index " << index; success = false; } if (!success) { m_error.index = index; m_error.msg = s.str(); } return success; }
inline void encodeInteger(bson_buffer *bb, const char *name, const Local<Value> element) { int value(element->NumberValue()); bson_append_int(bb, name, value); }
inline void encodeNumber(bson_buffer *bb, const char *name, const Local<Value> element) { double value(element->NumberValue()); bson_append_double(bb, name, value); }