void ShowToast(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = Isolate::GetCurrent(); HandleScope scope(isolate); if (args.Length() < 2){ isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "show() requires an object and function argument"))); return; } Local<Object> o = args[0].As<Object>(); WCHAR* title = NULL; WCHAR* msg = NULL; char* img = NULL; Local<String> titleKey = String::NewFromUtf8(isolate, "title"); Local<String> msgKey = String::NewFromUtf8(isolate, "subtitle"); Local<String> imgKey = String::NewFromUtf8(isolate, "imageUri"); if (o->Has(titleKey)){ String::Utf8Value v (o->Get(titleKey)->ToString()); size_t len = strlen(*v) + 1; title = new WCHAR[len]; swprintf(title, len, L"%S", *v); } if (o->Has(msgKey)){ String::Utf8Value v(o->Get(msgKey)->ToString()); size_t len = strlen(*v) + 1; msg = new WCHAR[len]; swprintf(msg, len, L"%S", *v); } if (o->Has(imgKey)){ String::Utf8Value v(o->Get(imgKey)->ToString()); size_t len = strlen(*v) + 1; img = new char[len]; sprintf(img, "%s", *v); } if (title == NULL && msg == NULL){ return; } Local<Function> cbFn = args[1].As<Function>(); WindowsToastNotification* wtn = new WindowsToastNotification(); wtn->ShowNotification(title, msg, img, cbFn); DELETE_IF(title); DELETE_IF(msg); DELETE_IF(img); }
JSONValue JSONValue::operator[](int index) { Locker locker(isolate); Isolate::Scope isolateScope(isolate); HandleScope handleScope; // Check if value is an array if (!value->IsArray()) throw bit::Exception("JSONValue is not an array"); Local<Value> valueLocal = Local<Value>::New(value); Local<Array> valueArray = Local<Array>::Cast(valueLocal); if (valueArray.IsEmpty()) throw bit::Exception("V8 array could not be created"); // Check if index exists if (!valueArray->Has(index)) throw bit::Exception("Index does not exist"); // Return JSONValue Local<Value> newValue = valueArray->Get(index); JSONValue jsonValue(newValue, isolate); return jsonValue; }
JSONValue JSONValue::operator[](const std::string &key) { Locker locker(isolate); Isolate::Scope isolateScope(isolate); HandleScope handleScope; // Check if value is an object if (!value->IsObject()) throw bit::Exception("JSONValue is not an object"); Local<Value> valueLocal = Local<Value>::New(value); Local<Object> valueObject = Local<Object>::Cast(valueLocal); Local<String> keyString = String::New(key.c_str()); // Check if key exists if (!valueObject->Has(keyString)) throw bit::Exception("Key '" + std::string(key) + "' does not exist"); // Return JSONValue Local<Value> newValue = handleScope.Close(valueObject->Get(keyString)); return JSONValue(newValue, isolate); }
Handle<Value> ImageView::encode(const Arguments& args) { HandleScope scope; ImageView* im = ObjectWrap::Unwrap<ImageView>(args.This()); std::string format = "png"; palette_ptr palette; // accept custom format if (args.Length() > 1){ if (!args[0]->IsString()) return ThrowException(Exception::TypeError( String::New("first arg, 'format' must be a string"))); format = TOSTR(args[0]); } // options hash if (args.Length() >= 2) { if (!args[1]->IsObject()) return ThrowException(Exception::TypeError( String::New("optional second arg must be an options object"))); Local<Object> options = args[1]->ToObject(); if (options->Has(String::New("palette"))) { Local<Value> format_opt = options->Get(String::New("palette")); if (!format_opt->IsObject()) return ThrowException(Exception::TypeError( String::New("'palette' must be an object"))); Local<Object> obj = format_opt->ToObject(); if (obj->IsNull() || obj->IsUndefined() || !Palette::constructor->HasInstance(obj)) return ThrowException(Exception::TypeError(String::New("mapnik.Palette expected as second arg"))); palette = ObjectWrap::Unwrap<Palette>(obj)->palette(); } } // ensure callback is a function Local<Value> callback = args[args.Length()-1]; if (!args[args.Length()-1]->IsFunction()) return ThrowException(Exception::TypeError( String::New("last argument must be a callback function"))); encode_image_baton_t *closure = new encode_image_baton_t(); closure->request.data = closure; closure->im = im; closure->image = im->this_; closure->format = format; closure->palette = palette; closure->error = false; closure->cb = Persistent<Function>::New(Handle<Function>::Cast(callback)); uv_queue_work(uv_default_loop(), &closure->request, EIO_Encode, EIO_AfterEncode); //uv_ref(uv_default_loop()); im->Ref(); return Undefined(); }
static inline NAN_METHOD(register_fonts) { NanScope(); try { if (args.Length() == 0 || !args[0]->IsString()) { NanThrowTypeError("first argument must be a path to a directory of fonts"); NanReturnUndefined(); } bool found = false; std::vector<std::string> const names_before = mapnik::freetype_engine::face_names(); // option hash if (args.Length() == 2){ if (!args[1]->IsObject()) { NanThrowTypeError("second argument is optional, but if provided must be an object, eg. { recurse:Boolean }"); NanReturnUndefined(); } Local<Object> options = args[1].As<Object>(); if (options->Has(NanNew("recurse"))) { Local<Value> recurse_opt = options->Get(NanNew("recurse")); if (!recurse_opt->IsBoolean()) { NanThrowTypeError("'recurse' must be a Boolean"); NanReturnUndefined(); } bool recurse = recurse_opt->BooleanValue(); std::string path = TOSTR(args[0]); found = mapnik::freetype_engine::register_fonts(path,recurse); } } else { std::string path = TOSTR(args[0]); found = mapnik::freetype_engine::register_fonts(path); } std::vector<std::string> const& names_after = mapnik::freetype_engine::face_names(); if (names_after.size() == names_before.size()) found = false; NanReturnValue(NanNew(found)); } catch (std::exception const& ex) { NanThrowError(ex.what()); NanReturnUndefined(); } }
void HtmlStripFunc(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); HandleScope scope(isolate); uint16_t* inBuf = NULL; size_t inBufSize = 0; if (args.Length() >= 2) { inBuf = static_cast<uint16_t*>( // NULL on flush. args[0].As<Object>()->GetIndexedPropertiesExternalArrayData()); inBufSize = args[1]->Uint32Value(); } HtmlStripOptions opts; // Check if we have any options passed if(args.Length() >= 3 && !args[2].IsEmpty() && args[2]->IsObject()){ Local<Object> optsObj = args[2]->ToObject(); if(!optsObj.IsEmpty()){ if(optsObj->Has(PERSISTENT(include_script_sym))){ opts.include_script = optsObj->Get(PERSISTENT(include_script_sym))->ToBoolean()->Value(); } if(optsObj->Has(PERSISTENT(include_style_sym))){ opts.include_style = optsObj->Get(PERSISTENT(include_style_sym))->ToBoolean()->Value(); } if(optsObj->Has(PERSISTENT(compact_whitespace_sym))){ opts.compact_whitespace = optsObj->Get(PERSISTENT(compact_whitespace_sym))->ToBoolean()->Value(); } if(optsObj->Has(PERSISTENT(include_attributes_sym))){ opts.include_attributes = true; opts.includeAttributesMap = optsObj->Get(PERSISTENT(include_attributes_sym))->ToObject(); Local< String > allAttr = String::NewFromUtf8(isolate, "*"); opts.include_all_attributes = opts.includeAttributesMap->Has(allAttr); } } } args.GetReturnValue().Set( HtmlStrip(inBuf, inBufSize, opts, isolate) ); }
void Initialize(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = Isolate::GetCurrent(); HandleScope scope(isolate); if (args.Length() < 1){ isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "init() requires an object"))); return; } Local<Object> o = args[0].As<Object>(); char* appName = NULL; char* tempDirPath = NULL; Local<String> appKey = String::NewFromUtf8(isolate, "appName"); Local<String> tempDirKey = String::NewFromUtf8(isolate, "tempDir"); if (o->Has(appKey)){ String::Utf8Value v(o->Get(appKey)->ToString()); size_t len = strlen(*v) + 1; appName = new char[len]; sprintf(appName, "%s", *v); } if (o->Has(tempDirKey)){ String::Utf8Value v(o->Get(tempDirKey)->ToString()); size_t len = strlen(*v) + 1; tempDirPath = new char[len]; sprintf(tempDirPath, "%s", *v); } if (appName == NULL || tempDirPath == NULL){ isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "init() requires 'appName' and 'tempDir'"))); return; } WindowsToastNotification::InitSystemProps(appName, tempDirPath); DELETE_IF(appName); DELETE_IF(tempDirPath); }
Handle<Value> ODBCResult::FetchAll(const Arguments& args) { DEBUG_PRINTF("ODBCResult::FetchAll\n"); HandleScope scope; ODBCResult* objODBCResult = ObjectWrap::Unwrap<ODBCResult>(args.Holder()); uv_work_t* work_req = (uv_work_t *) (calloc(1, sizeof(uv_work_t))); fetch_work_data* data = (fetch_work_data *) calloc(1, sizeof(fetch_work_data)); Local<Function> cb; data->fetchMode = objODBCResult->m_fetchMode; if (args.Length() == 1 && args[0]->IsFunction()) { cb = Local<Function>::Cast(args[0]); } else if (args.Length() == 2 && args[0]->IsObject() && args[1]->IsFunction()) { cb = Local<Function>::Cast(args[1]); Local<Object> obj = args[0]->ToObject(); if (obj->Has(OPTION_FETCH_MODE) && obj->Get(OPTION_FETCH_MODE)->IsInt32()) { data->fetchMode = obj->Get(OPTION_FETCH_MODE)->ToInt32()->Value(); } } else { return ThrowException(Exception::TypeError( String::New("ODBCResult::FetchAll(): 1 or 2 arguments are required. The last argument must be a callback function.") )); } data->rows = Persistent<Array>::New(Array::New()); data->errorCount = 0; data->count = 0; data->objError = Persistent<Object>::New(Object::New()); data->cb = Persistent<Function>::New(cb); data->objResult = objODBCResult; work_req->data = data; uv_queue_work(uv_default_loop(), work_req, UV_FetchAll, (uv_after_work_cb)UV_AfterFetchAll); data->objResult->Ref(); return scope.Close(Undefined()); }
static inline Handle<Value> register_fonts(const Arguments& args) { HandleScope scope; try { if (!args.Length() >= 1 || !args[0]->IsString()) return ThrowException(Exception::TypeError( String::New("first argument must be a path to a directory of fonts"))); bool found = false; std::vector<std::string> const names_before = mapnik::freetype_engine::face_names(); // option hash if (args.Length() == 2){ if (!args[1]->IsObject()) return ThrowException(Exception::TypeError( String::New("second argument is optional, but if provided must be an object, eg. { recurse:Boolean }"))); Local<Object> options = args[1]->ToObject(); if (options->Has(String::New("recurse"))) { Local<Value> recurse_opt = options->Get(String::New("recurse")); if (!recurse_opt->IsBoolean()) return ThrowException(Exception::TypeError( String::New("'recurse' must be a Boolean"))); bool recurse = recurse_opt->BooleanValue(); std::string path = TOSTR(args[0]); found = mapnik::freetype_engine::register_fonts(path,recurse); } } else { std::string path = TOSTR(args[0]); found = mapnik::freetype_engine::register_fonts(path); } std::vector<std::string> const& names_after = mapnik::freetype_engine::face_names(); if (names_after.size() == names_before.size()) found = false; return scope.Close(Boolean::New(found)); } catch (std::exception const& ex) { return ThrowException(Exception::Error( String::New(ex.what()))); } }
void V8BuilderPolicy::AppendToDictKeyList(std::string const & _key, type const & var) { Nan::HandleScope scope; Local<Value> object(Nan::New(object_)); assert(object->IsObject()); Local<Object> obj = Local<Object>::Cast(object); KeyMap::const_iterator k_it = keys_.find(_key); if (k_it == keys_.end()) { Nan::Persistent<v8::String> * pers_key = new Nan::Persistent<v8::String>(Nan::New(_key).ToLocalChecked()); keys_[_key] = pers_key; k_it = keys_.find(_key); } Local<String> key = Nan::New(*k_it->second); // Local<String> key = Nan::New(_key).ToLocalChecked(); if (obj->Has(key)) { Local<Value> value = obj->Get(key); if (value->IsArray()) { Local<Array> arr = Local<Array>::Cast(value); arr->Set(arr->Length(), Nan::New(var)); } else { Local<Array> arr(Nan::New<Array>()); arr->Set(0, value); arr->Set(1, Nan::New(var)); obj->Set(key, arr); } } else { if (options_.explicit_array_) { Local<Array> arr(Nan::New<Array>()); arr->Set(0, Nan::New(var)); obj->Set(key, arr); } else { obj->Set(key, Nan::New(var)); } } }
bool JSONValue::has(const std::string &key) { Locker locker(isolate); Isolate::Scope isolateScope(isolate); HandleScope handleScope; // Check if value is an object if (!value->IsObject()) throw bit::Exception("JSONValue is not an object"); Local<Value> valueLocal = Local<Value>::New(value); Local<Object> valueObject = Local<Object>::Cast(valueLocal); Local<String> keyString = String::New(key.c_str()); // Check if key exists return valueObject->Has(keyString); }
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); }
Handle<Value> ODBCResult::FetchSync(const Arguments& args) { DEBUG_PRINTF("ODBCResult::FetchSync\n"); HandleScope scope; ODBCResult* objResult = ObjectWrap::Unwrap<ODBCResult>(args.Holder()); Local<Object> objError; bool moreWork = true; bool error = false; int fetchMode = objResult->m_fetchMode; if (args.Length() == 1 && args[0]->IsObject()) { Local<Object> obj = args[0]->ToObject(); if (obj->Has(OPTION_FETCH_MODE) && obj->Get(OPTION_FETCH_MODE)->IsInt32()) { fetchMode = obj->Get(OPTION_FETCH_MODE)->ToInt32()->Value(); } } SQLRETURN ret = SQLFetch(objResult->m_hSTMT); if (objResult->colCount == 0) { objResult->columns = ODBC::GetColumns( objResult->m_hSTMT, &objResult->colCount); } //check to see if the result has no columns if (objResult->colCount == 0) { moreWork = false; } //check to see if there was an error else if (ret == SQL_ERROR) { moreWork = false; error = true; objError = ODBC::GetSQLError( SQL_HANDLE_STMT, objResult->m_hSTMT, (char *) "Error in ODBCResult::UV_AfterFetch"); } //check to see if we are at the end of the recordset else if (ret == SQL_NO_DATA) { moreWork = false; } if (moreWork) { Handle<Value> data; if (fetchMode == FETCH_ARRAY) { data = ODBC::GetRecordArray( objResult->m_hSTMT, objResult->columns, &objResult->colCount, objResult->buffer, objResult->bufferLength); } else { data = ODBC::GetRecordTuple( objResult->m_hSTMT, objResult->columns, &objResult->colCount, objResult->buffer, objResult->bufferLength); } return scope.Close(data); } else { ODBC::FreeColumns(objResult->columns, &objResult->colCount); //if there was an error, pass that as arg[0] otherwise Null if (error) { ThrowException(objError); return scope.Close(Null()); } else { return scope.Close(Null()); } } }
Handle<Value> ODBCResult::FetchAllSync(const Arguments& args) { DEBUG_PRINTF("ODBCResult::FetchAllSync\n"); HandleScope scope; ODBCResult* self = ObjectWrap::Unwrap<ODBCResult>(args.Holder()); Local<Object> objError = Object::New(); SQLRETURN ret; int count = 0; int errorCount = 0; int fetchMode = self->m_fetchMode; if (args.Length() == 1 && args[0]->IsObject()) { Local<Object> obj = args[0]->ToObject(); if (obj->Has(OPTION_FETCH_MODE) && obj->Get(OPTION_FETCH_MODE)->IsInt32()) { fetchMode = obj->Get(OPTION_FETCH_MODE)->ToInt32()->Value(); } } if (self->colCount == 0) { self->columns = ODBC::GetColumns(self->m_hSTMT, &self->colCount); } Local<Array> rows = Array::New(); //Only loop through the recordset if there are columns if (self->colCount > 0) { //loop through all records while (true) { ret = SQLFetch(self->m_hSTMT); //check to see if there was an error if (ret == SQL_ERROR) { errorCount++; objError = ODBC::GetSQLError( SQL_HANDLE_STMT, self->m_hSTMT, (char *) "[node-odbc] Error in ODBCResult::UV_AfterFetchAll; probably" " your query did not have a result set." ); break; } //check to see if we are at the end of the recordset if (ret == SQL_NO_DATA) { ODBC::FreeColumns(self->columns, &self->colCount); break; } if (fetchMode == FETCH_ARRAY) { rows->Set( Integer::New(count), ODBC::GetRecordArray( self->m_hSTMT, self->columns, &self->colCount, self->buffer, self->bufferLength) ); } else { rows->Set( Integer::New(count), ODBC::GetRecordTuple( self->m_hSTMT, self->columns, &self->colCount, self->buffer, self->bufferLength) ); } count++; } } else { ODBC::FreeColumns(self->columns, &self->colCount); } //throw the error object if there were errors if (errorCount > 0) { ThrowException(objError); } return scope.Close(rows); }
Handle<Value> ImageView::encodeSync(const Arguments& args) { HandleScope scope; ImageView* im = ObjectWrap::Unwrap<ImageView>(args.This()); std::string format = "png"; palette_ptr palette; // accept custom format if (args.Length() >= 1) { if (!args[0]->IsString()) return ThrowException(Exception::TypeError( String::New("first arg, 'format' must be a string"))); format = TOSTR(args[0]); } // options hash if (args.Length() >= 2) { if (!args[1]->IsObject()) return ThrowException(Exception::TypeError( String::New("optional second arg must be an options object"))); Local<Object> options = args[1]->ToObject(); if (options->Has(String::New("palette"))) { Local<Value> format_opt = options->Get(String::New("palette")); if (!format_opt->IsObject()) return ThrowException(Exception::TypeError( String::New("'palette' must be an object"))); Local<Object> obj = format_opt->ToObject(); if (obj->IsNull() || obj->IsUndefined() || !Palette::constructor->HasInstance(obj)) return ThrowException(Exception::TypeError(String::New("mapnik.Palette expected as second arg"))); palette = ObjectWrap::Unwrap<Palette>(obj)->palette(); } } try { std::string s; if (palette.get()) { s = save_to_string(*(im->this_), format, *palette); } else { s = save_to_string(*(im->this_), format); } #if NODE_VERSION_AT_LEAST(0,3,0) node::Buffer *retbuf = Buffer::New((char*)s.data(),s.size()); #else node::Buffer *retbuf = Buffer::New(s.size()); memcpy(retbuf->data(), s.data(), s.size()); #endif return scope.Close(retbuf->handle_); } catch (std::exception & ex) { return ThrowException(Exception::Error( String::New(ex.what()))); } catch (...) { return ThrowException(Exception::Error( String::New("unknown exception happened when encoding image: please file bug report"))); } }
Handle<Value> MemoryDatasource::add(const Arguments& args) { HandleScope scope; if ((args.Length() != 1) || !args[0]->IsObject()) { return ThrowException(Exception::Error( String::New("accepts one argument: an object including x and y (or wkt) and properties"))); } MemoryDatasource* d = node::ObjectWrap::Unwrap<MemoryDatasource>(args.This()); Local<Object> obj = args[0]->ToObject(); if (obj->Has(String::New("wkt")) || (obj->Has(String::New("x")) && obj->Has(String::New("y")))) { if (obj->Has(String::New("wkt"))) return ThrowException(Exception::Error( String::New("wkt not yet supported"))); 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()); #if MAPNIK_VERSION >= 200100 mapnik::context_ptr ctx = MAPNIK_MAKE_SHARED<mapnik::context_type>(); mapnik::feature_ptr feature(mapnik::feature_factory::create(ctx,d->feature_id_)); #else mapnik::feature_ptr feature(mapnik::feature_factory::create(d->feature_id_)); #endif ++(d->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(); unsigned int i = 0; unsigned int 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()) { mapnik::value_unicode_string ustr = d->tr_->transcode(TOSTR(value)); #if MAPNIK_VERSION >= 200100 feature->put_new(TOSTR(name),ustr); #else boost::put(*feature,TOSTR(name),ustr); #endif } else if (value->IsNumber()) { double num = value->NumberValue(); // todo - round if (num == value->IntegerValue()) { #if MAPNIK_VERSION >= 200100 feature->put_new(TOSTR(name),static_cast<node_mapnik::value_integer>(value->IntegerValue())); #else boost::put(*feature,TOSTR(name),static_cast<int>(value->IntegerValue())); #endif } else { double dub_val = value->NumberValue(); #if MAPNIK_VERSION >= 200100 feature->put_new(TOSTR(name),dub_val); #else boost::put(*feature,TOSTR(name),dub_val); #endif } } else if (value->IsNull()) { #if MAPNIK_VERSION >= 200100 feature->put_new(TOSTR(name),mapnik::value_null()); #else boost::put(*feature,TOSTR(name),mapnik::value_null()); #endif } else { std::clog << "unhandled type for property: " << TOSTR(name) << "\n"; } i++; } } } mapnik::memory_datasource *cache = dynamic_cast<mapnik::memory_datasource *>(d->datasource_.get()); cache->push(feature); } } return scope.Close(False()); }
ScanOperation::ScanOperation(const Arguments &args) : KeyOperation(), scan_op(0), index_scan_op(0), nbounds(0), isIndexScan(false) { DEBUG_MARKER(UDEB_DEBUG); Local<Value> v; const Local<Object> spec = args[0]->ToObject(); opcode = args[1]->Int32Value(); ctx = unwrapPointer<TransactionImpl *>(args[2]->ToObject()); lmode = NdbOperation::LM_CommittedRead; scan_options.scan_flags = 0; scan_options.optionsPresent = 0ULL; v = spec->Get(SCAN_TABLE_RECORD); if(! v->IsNull()) { Local<Object> o = v->ToObject(); row_record = unwrapPointer<const Record *>(o); createBlobReadHandles(row_record); } v = spec->Get(SCAN_INDEX_RECORD); if(! v->IsNull()) { Local<Object> o = v->ToObject(); isIndexScan = true; key_record = unwrapPointer<const Record *>(o); } v = spec->Get(SCAN_LOCK_MODE); if(! v->IsNull()) { int intLockMode = v->Int32Value(); DEBUG_PRINT("Scan lock mode %d", intLockMode); lmode = static_cast<NdbOperation::LockMode>(intLockMode); } // SCAN_BOUNDS is an array of BoundHelpers v = spec->Get(SCAN_BOUNDS); if(v->IsArray()) { Local<Object> o = v->ToObject(); while(o->Has(nbounds)) { nbounds++; } DEBUG_PRINT("Index Scan with %d IndexBounds", nbounds); bounds = new NdbIndexScanOperation::IndexBound *[nbounds]; for(int i = 0 ; i < nbounds ; i++) { Local<Object> b = o->Get(i)->ToObject(); bounds[i] = unwrapPointer<NdbIndexScanOperation::IndexBound *>(b); } } v = spec->Get(SCAN_OPTION_FLAGS); if(! v->IsNull()) { scan_options.scan_flags = v->Uint32Value(); } v = spec->Get(SCAN_OPTION_BATCH_SIZE); if(! v->IsNull()) { scan_options.batch = v->Uint32Value(); scan_options.optionsPresent |= NdbScanOperation::ScanOptions::SO_BATCH; } v = spec->Get(SCAN_OPTION_PARALLELISM); if(! v->IsNull()) { scan_options.parallel = v->Uint32Value(); scan_options.optionsPresent |= NdbScanOperation::ScanOptions::SO_PARALLEL; } v = spec->Get(SCAN_FILTER_CODE); if(! v->IsNull()) { Local<Object> o = v->ToObject(); scan_options.interpretedCode = unwrapPointer<NdbInterpretedCode *>(o); scan_options.optionsPresent |= NdbScanOperation::ScanOptions::SO_INTERPRETED; } /* Scanning delete requires key info */ if(opcode == OP_SCAN_DELETE) { scan_options.scan_flags |= NdbScanOperation::SF_KeyInfo; } /* If any flags were set, also set SO_SCANFLAGS options */ if(scan_options.scan_flags != 0) { scan_options.optionsPresent |= NdbScanOperation::ScanOptions::SO_SCANFLAGS; } /* Done defining the object */ debug_print_flags_and_options(scan_options); }
Handle<Value> Grid::encodeSync(const Arguments& args) // format, resolution { HandleScope scope; Grid* g = ObjectWrap::Unwrap<Grid>(args.This()); // defaults std::string format("utf"); unsigned int resolution = 4; bool add_features = true; // accept custom format if (args.Length() >= 1){ if (!args[0]->IsString()) return ThrowException(Exception::TypeError( String::New("first arg, 'format' must be a string"))); format = TOSTR(args[0]); } // options hash if (args.Length() >= 2) { if (!args[1]->IsObject()) return ThrowException(Exception::TypeError( String::New("optional second arg must be an options object"))); Local<Object> options = args[1]->ToObject(); if (options->Has(String::New("resolution"))) { Local<Value> bind_opt = options->Get(String::New("resolution")); if (!bind_opt->IsNumber()) return ThrowException(Exception::TypeError( String::New("'resolution' must be an Integer"))); resolution = bind_opt->IntegerValue(); } if (options->Has(String::New("features"))) { Local<Value> bind_opt = options->Get(String::New("features")); if (!bind_opt->IsBoolean()) return ThrowException(Exception::TypeError( String::New("'features' must be an Boolean"))); add_features = bind_opt->BooleanValue(); } } try { Local<Array> grid_array = Array::New(); std::vector<mapnik::grid::lookup_type> key_order; node_mapnik::grid2utf<mapnik::grid>(*g->get(),grid_array,key_order,resolution); // convert key order to proper javascript array Local<Array> keys_a = Array::New(key_order.size()); std::vector<std::string>::iterator it; unsigned int i; for (it = key_order.begin(), i = 0; it < key_order.end(); ++it, ++i) { keys_a->Set(i, String::New((*it).c_str())); } // gather feature data Local<Object> feature_data = Object::New(); if (add_features) { node_mapnik::write_features<mapnik::grid>(*g->get(), feature_data, key_order ); } // Create the return hash. Local<Object> json = Object::New(); json->Set(String::NewSymbol("grid"), grid_array); json->Set(String::NewSymbol("keys"), keys_a); json->Set(String::NewSymbol("data"), feature_data); return json; } catch (std::exception & ex) { return ThrowException(Exception::Error( String::New(ex.what()))); } }
/* * Prototype: * TBW * * Docs: * TBW * * Example: * TBW */ static void gum_v8_stalker_on_follow (const FunctionCallbackInfo<Value> & info) { GumV8Stalker * self = static_cast<GumV8Stalker *> ( info.Data ().As<External> ()->Value ()); GumV8Core * core = self->core; Isolate * isolate = info.GetIsolate (); GumThreadId thread_id; Local<Value> options_value; switch (info.Length ()) { case 0: thread_id = gum_process_get_current_thread_id (); break; case 1: if (info[0]->IsNumber ()) { thread_id = info[0]->IntegerValue (); } else { thread_id = gum_process_get_current_thread_id (); options_value = info[0]; } break; default: thread_id = info[0]->IntegerValue (); options_value = info[1]; break; } GumV8EventSinkOptions so; so.core = self->core; so.main_context = gum_script_scheduler_get_js_context (self->core->scheduler); so.event_mask = GUM_NOTHING; so.queue_capacity = self->queue_capacity; so.queue_drain_interval = self->queue_drain_interval; if (!options_value.IsEmpty ()) { if (!options_value->IsObject ()) { isolate->ThrowException (Exception::TypeError (String::NewFromUtf8 ( isolate, "Stalker.follow: options argument must be an object"))); return; } Local<Object> options = Local<Object>::Cast (options_value); Local<String> events_key (String::NewFromUtf8 (isolate, "events")); if (options->Has (events_key)) { Local<Value> events_value (options->Get (events_key)); if (!events_value->IsObject ()) { isolate->ThrowException (Exception::TypeError (String::NewFromUtf8 ( isolate, "Stalker.follow: events key must be an object"))); return; } Local<Object> events (Local<Object>::Cast (events_value)); if (gum_v8_flags_get (events, "call", core)) so.event_mask |= GUM_CALL; if (gum_v8_flags_get (events, "ret", core)) so.event_mask |= GUM_RET; if (gum_v8_flags_get (events, "exec", core)) so.event_mask |= GUM_EXEC; } if (so.event_mask != GUM_NOTHING && !_gum_v8_callbacks_get_opt (options, "onReceive", &so.on_receive, core)) { return; } if ((so.event_mask & GUM_CALL) != 0) { _gum_v8_callbacks_get_opt (options, "onCallSummary", &so.on_call_summary, core); } } if (self->sink != NULL) { GumEventSink * sink = self->sink; self->sink = NULL; g_object_unref (sink); } self->sink = gum_v8_event_sink_new (&so); if (thread_id == gum_process_get_current_thread_id ()) { self->pending_follow_level = 1; } else { GumEventSink * sink = self->sink; self->sink = NULL; gum_stalker_follow (_gum_v8_stalker_get (self), thread_id, sink); g_object_unref (sink); } }
Handle<Value> MemoryDatasource::add(const Arguments& args) { HandleScope scope; if ((args.Length() != 1) || !args[0]->IsObject()) { return ThrowException(Exception::Error( String::New("accepts one argument: an object including x and y (or wkt) and properties"))); } MemoryDatasource* d = ObjectWrap::Unwrap<MemoryDatasource>(args.This()); Local<Object> obj = args[0]->ToObject(); if (obj->Has(String::New("wkt")) || (obj->Has(String::New("x")) && obj->Has(String::New("y")))) { if (obj->Has(String::New("wkt"))) return ThrowException(Exception::Error( String::New("wkt not yet supported"))); 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(new mapnik::Feature(d->feature_id_)); ++(d->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 = d->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); } } else { std::clog << "unhandled type for property: " << TOSTR(name) << "\n"; } i++; } } } mapnik::memory_datasource *cache = dynamic_cast<mapnik::memory_datasource *>(d->datasource_.get()); cache->push(feature); } } return scope.Close(Boolean::New(false)); }
DBScanHelper::DBScanHelper(const Arguments &args) : nbounds(0), isIndexScan(false) { DEBUG_MARKER(UDEB_DEBUG); Local<Value> v; const Local<Object> spec = args[0]->ToObject(); int opcode = args[1]->Int32Value(); tx = unwrapPointer<NdbTransaction *>(args[2]->ToObject()); lmode = NdbOperation::LM_CommittedRead; scan_options = & options; options.optionsPresent = 0ULL; v = spec->Get(SCAN_TABLE_RECORD); if(! v->IsNull()) { Local<Object> o = v->ToObject(); row_record = unwrapPointer<const Record *>(o); } v = spec->Get(SCAN_INDEX_RECORD); if(! v->IsNull()) { Local<Object> o = v->ToObject(); isIndexScan = true; key_record = unwrapPointer<const Record *>(o); } v = spec->Get(SCAN_LOCK_MODE); if(! v->IsNull()) { int intLockMode = v->Int32Value(); lmode = static_cast<NdbOperation::LockMode>(intLockMode); } // SCAN_BOUNDS is an array of BoundHelpers v = spec->Get(SCAN_BOUNDS); if(v->IsArray()) { Local<Object> o = v->ToObject(); while(o->Has(nbounds)) { nbounds++; } bounds = new NdbIndexScanOperation::IndexBound *[nbounds]; for(int i = 0 ; i < nbounds ; i++) { Local<Object> b = o->Get(i)->ToObject(); bounds[i] = unwrapPointer<NdbIndexScanOperation::IndexBound *>(b); } } v = spec->Get(SCAN_OPTION_FLAGS); if(! v->IsNull()) { options.scan_flags = v->Uint32Value(); options.optionsPresent |= NdbScanOperation::ScanOptions::SO_SCANFLAGS; } v = spec->Get(SCAN_OPTION_BATCH_SIZE); if(! v->IsNull()) { options.batch = v->Uint32Value(); options.optionsPresent |= NdbScanOperation::ScanOptions::SO_BATCH; } v = spec->Get(SCAN_OPTION_PARALLELISM); if(! v->IsNull()) { options.parallel = v->Uint32Value(); options.optionsPresent |= NdbScanOperation::ScanOptions::SO_PARALLEL; } v = spec->Get(SCAN_FILTER_CODE); if(! v->IsNull()) { Local<Object> o = v->ToObject(); options.interpretedCode = unwrapPointer<NdbInterpretedCode *>(o); options.optionsPresent |= NdbScanOperation::ScanOptions::SO_INTERPRETED; } /* Scanning delete requires key info */ if(opcode == OP_SCAN_DELETE) { options.scan_flags |= NdbScanOperation::SF_KeyInfo; options.optionsPresent |= NdbScanOperation::ScanOptions::SO_SCANFLAGS; } /* Done defining the object */ }
/* * Wrap the quote() method to marshal and unmarshal arguments * * Entirely inefficient. * * Will throw an exception if the Quote fails. * Currently doing NO INPUT VALIDATION * * Arguments: srkpwd, aikfile, pcrs[], nonce * */ static Handle<Value> getQuote(const Arguments& args) { //unmarshal the arguments Local<String> srkpwd = args[0]->ToString(); Local<String> aik = args[1]->ToString(); Local<Object> pcrsObj = args[2]->ToObject(); Local<Object> nonceObj = args[3]->ToObject(); int fieldCount = 0; while (pcrsObj->Has(fieldCount)) fieldCount++; long pcrs[fieldCount]; int i = 0; for (i = 0; i < fieldCount; i++) { pcrs[i] = pcrsObj->Get(i)->Int32Value(); } int j = 0; BYTE nonce[20]; while (nonceObj->Has(j) && j < 20) { nonce[j] = nonceObj->Get(j)->Int32Value(); j++; } char* srkpwdAscii = stringToChar(srkpwd); char* aikAscii = stringToChar(aik); TSS_VALIDATION valid; TPM_QUOTE_INFO quoteInfo; //perform the quote TSS_RESULT quoteRes = quote(srkpwdAscii, aikAscii, pcrs, fieldCount, nonce, &valid, "eInfo); if (quoteRes != 0) { return ThrowException( Exception::Error(String::New("Error producing TPM Quote"))); } // turn all these stupid TSS structs into JSON structures! Local<Object> validData = Object::New(); validData->Set(String::New("rgbData"), bytesToArray(valid.rgbData, valid.ulDataLength)); validData->Set(String::New("rgbExternalData"), bytesToArray(valid.rgbExternalData, valid.ulExternalDataLength)); validData->Set(String::New("rgbValidationData"), bytesToArray(valid.rgbValidationData, valid.ulValidationDataLength)); validData->Set(String::New("versionInfo"), version2ToObject(valid.versionInfo)); Local<Object> quoteData = Object::New(); quoteData->Set(String::New("compositeHash"), bytesToArray(quoteInfo.compositeHash.digest, 20)); quoteData->Set(String::New("externalData"), bytesToArray(quoteInfo.externalData.nonce, 20)); quoteData->Set(String::New("fixed"), bytesToArray(quoteInfo.fixed, 4)); quoteData->Set(String::New("versionInfo"), versionToObject(quoteInfo.version)); Local<Object> both = Object::New(); both->Set(String::New("validationData"), validData); both->Set(String::New("quoteInfo"), quoteData); free(aikAscii); free(srkpwdAscii); return both; }
Handle<Value> Query::New(Arguments const& args) { HandleScope scope; if (!args.IsConstructCall()) { return ThrowException(Exception::Error(String::New("Cannot call constructor as function, you need to use 'new' keyword"))); } try { if (args.Length() != 1) { return ThrowException(Exception::TypeError(String::New("please provide an object of options for the first argument"))); } if (!args[0]->IsObject()) { return ThrowException(Exception::TypeError(String::New("first argument must be an object"))); } Local<Object> obj = args[0]->ToObject(); if (obj->IsNull() || obj->IsUndefined()) { return ThrowException(Exception::TypeError(String::New("first arg must be an object"))); } if (!obj->Has(String::NewSymbol("coordinates"))) { return ThrowException(Exception::TypeError(String::New("must provide a coordinates property"))); } Local<Value> coordinates = obj->Get(String::New("coordinates")); if (!coordinates->IsArray()) { return ThrowException(Exception::TypeError(String::New("coordinates must be an array of (lat/long) pairs"))); } Local<Array> coordinates_array = Local<Array>::Cast(coordinates); if (coordinates_array->Length() < 2) { return ThrowException(Exception::TypeError(String::New("at least two coordinates must be provided"))); } Query* q = new Query(); q->this_->zoomLevel = 18; //no generalization q->this_->printInstructions = true; //turn by turn instructions q->this_->alternateRoute = true; //get an alternate route, too q->this_->geometry = true; //retrieve geometry of route q->this_->compression = true; //polyline encoding q->this_->checkSum = UINT_MAX; //see wiki q->this_->service = "viaroute"; //that's routing q->this_->outputFormat = "json"; q->this_->jsonpParameter = ""; //set for jsonp wrapping q->this_->language = ""; //unused atm if (obj->Has(String::NewSymbol("alternateRoute"))) { q->this_->alternateRoute = obj->Get(String::New("alternateRoute"))->BooleanValue(); } for (uint32_t i = 0; i < coordinates_array->Length(); ++i) { Local<Value> coordinate = coordinates_array->Get(i); if (!coordinate->IsArray()) { return ThrowException(Exception::TypeError(String::New("coordinates must be an array of (lat/long) pairs"))); } Local<Array> coordinate_array = Local<Array>::Cast(coordinate); if (coordinate_array->Length() != 2) { return ThrowException(Exception::TypeError(String::New("coordinates must be an array of (lat/long) pairs"))); } q->this_->coordinates.push_back( FixedPointCoordinate(coordinate_array->Get(0)->NumberValue()*COORDINATE_PRECISION, coordinate_array->Get(1)->NumberValue()*COORDINATE_PRECISION)); } q->Wrap(args.This()); return args.This(); } catch (std::exception const& ex) { return ThrowException(Exception::TypeError(String::New(ex.what()))); } return Undefined(); }
Handle<Value> Datasource::New(const Arguments& args) { HandleScope scope; if (!args.IsConstructCall()) return ThrowException(String::New("Cannot call constructor as function, you need to use 'new' keyword")); if (args[0]->IsExternal()) { //std::clog << "external!\n"; Local<External> ext = Local<External>::Cast(args[0]); void* ptr = ext->Value(); Datasource* d = static_cast<Datasource*>(ptr); d->Wrap(args.This()); return args.This(); } if (!args.Length() == 1){ return ThrowException(Exception::TypeError( String::New("accepts only one argument, an object of key:value datasource options"))); } if (!args[0]->IsObject()) return ThrowException(Exception::TypeError( String::New("must provide an object, eg {type: 'shape', file : 'world.shp'}"))); Local<Object> options = args[0]->ToObject(); // TODO - maybe validate in js? bool bind=true; if (options->Has(String::New("bind"))) { Local<Value> bind_opt = options->Get(String::New("bind")); if (!bind_opt->IsBoolean()) return ThrowException(Exception::TypeError( String::New("'bind' must be a Boolean"))); bind = bind_opt->BooleanValue(); } mapnik::parameters params; Local<Array> names = options->GetPropertyNames(); uint32_t i = 0; uint32_t a_length = names->Length(); while (i < a_length) { Local<Value> name = names->Get(i)->ToString(); Local<Value> value = options->Get(name); params[TOSTR(name)] = TOSTR(value); i++; } mapnik::datasource_ptr ds; try { ds = mapnik::datasource_cache::create(params, bind); } catch (const mapnik::config_error & ex ) { return ThrowException(Exception::Error( String::New(ex.what()))); } catch (const mapnik::datasource_exception & ex ) { return ThrowException(Exception::Error( String::New(ex.what()))); } catch (const std::runtime_error & ex ) { return ThrowException(Exception::Error( String::New(ex.what()))); } catch (const std::exception & ex) { return ThrowException(Exception::Error( String::New(ex.what()))); } catch (...) { return ThrowException(Exception::Error( String::New("unknown exception happened, please file bug"))); } if (ds) { Datasource* d = new Datasource(); d->Wrap(args.This()); d->datasource_ = ds; return args.This(); } return Undefined(); }
Handle<Value> AjaxModule::ajax(const Arguments& args) { v8::Locker l; if (args.Length() < 1) { LOGE("Not enough parameters for ajax"); return v8::Undefined(); } HandleScope scope; Local<v8::Object> options = args[0]->ToObject(); // Get callbacks Local<Function> callback = Local<Function>::Cast( options->Get(String::New("success"))); Local<Function> errCallback = Local<Function>::Cast( options->Get(String::New("error"))); Persistent<Function> callbackPers = Persistent<Function>::New(callback); Persistent<Function> errorPers; if (!errCallback.IsEmpty() && errCallback != v8::Undefined()) { errorPers = Persistent<Function>::New(errCallback); } // Persist the this object Persistent<Object> thisObj = Persistent<Object>::New(args.This()); // Get url Local<String> url = Local<String>::Cast(options->Get(String::New("url"))); String::AsciiValue urlLocal(url); // Get data Local<Value> data = options->Get(String::New("data")); Local<String> method = Local<String>::Cast(options->Get(String::New("type"))); Local<String> processKey = String::New("processData"); bool processData = true; if (options->Has(processKey)) { processData = options->Get(processKey)->BooleanValue(); } #ifdef ANDROID jstring dataStr, urlStr, methodStr; ClientAndroid* client = (ClientAndroid*)(_bgjscontext->_client); JNIEnv* env = JNU_GetEnv(); if (env == NULL) { LOGE("Cannot execute AJAX request with no envCache"); return v8::Undefined(); } urlStr = env->NewStringUTF(*urlLocal); if (data != v8::Undefined()) { String::Utf8Value dataLocal(data); dataStr = env->NewStringUTF(*dataLocal); } else { dataStr = 0; } if (method != v8::Undefined()) { String::Utf8Value methodLocal(method); methodStr = env->NewStringUTF(*methodLocal); } else { methodStr = 0; } jclass clazz = env->FindClass("ag/boersego/bgjs/V8Engine"); jmethodID ajaxMethod = env->GetStaticMethodID(clazz, "doAjaxRequest", "(Ljava/lang/String;JJJLjava/lang/String;Ljava/lang/String;Z)V"); assert(ajaxMethod); assert(clazz); env->CallStaticVoidMethod(clazz, ajaxMethod, urlStr, (jlong) *callbackPers, (jlong) *thisObj, (jlong) *errorPers, dataStr, methodStr, (jboolean)processData); #endif return v8::Undefined(); }
// @TODO: convert this to EIO. It's currently doing all the work in the main // thread, and just provides an async interface. Handle<Value> Grid::encode(const Arguments& args) // format, resolution { HandleScope scope; Grid* g = ObjectWrap::Unwrap<Grid>(args.This()); // defaults std::string format("utf"); unsigned int resolution = 4; bool add_features = true; // accept custom format if (args.Length() >= 1){ if (!args[0]->IsString()) return ThrowException(Exception::TypeError( String::New("first arg, 'format' must be a string"))); format = TOSTR(args[0]); } // options hash if (args.Length() >= 2) { if (!args[1]->IsObject()) return ThrowException(Exception::TypeError( String::New("optional second arg must be an options object"))); Local<Object> options = args[1]->ToObject(); if (options->Has(String::New("resolution"))) { Local<Value> bind_opt = options->Get(String::New("resolution")); if (!bind_opt->IsNumber()) return ThrowException(Exception::TypeError( String::New("'resolution' must be an Integer"))); resolution = bind_opt->IntegerValue(); } if (options->Has(String::New("features"))) { Local<Value> bind_opt = options->Get(String::New("features")); if (!bind_opt->IsBoolean()) return ThrowException(Exception::TypeError( String::New("'features' must be an Boolean"))); add_features = bind_opt->BooleanValue(); } } // ensure callback is a function if (!args[args.Length()-1]->IsFunction()) return ThrowException(Exception::TypeError( String::New("last argument must be a callback function"))); Local<Function> callback = Local<Function>::Cast(args[args.Length()-1]); try { Local<Array> grid_array = Array::New(); std::vector<mapnik::grid::lookup_type> key_order; node_mapnik::grid2utf<mapnik::grid>(*g->get(),grid_array,key_order,resolution); // convert key order to proper javascript array Local<Array> keys_a = Array::New(key_order.size()); std::vector<std::string>::iterator it; unsigned int i; for (it = key_order.begin(), i = 0; it < key_order.end(); ++it, ++i) { keys_a->Set(i, String::New((*it).c_str())); } // gather feature data Local<Object> feature_data = Object::New(); if (add_features) { node_mapnik::write_features<mapnik::grid>(*g->get(), feature_data, key_order ); } // Create the return hash. Local<Object> json = Object::New(); json->Set(String::NewSymbol("grid"), grid_array); json->Set(String::NewSymbol("keys"), keys_a); json->Set(String::NewSymbol("data"), feature_data); TryCatch try_catch; Local<Value> argv[2] = { Local<Value>::New(Null()), Local<Value>::New(json) }; callback->Call(Context::GetCurrent()->Global(), 2, argv); if (try_catch.HasCaught()) { FatalException(try_catch); } } catch (std::exception & ex) { Local<Value> argv[1] = { Exception::Error(String::New(ex.what())) }; callback->Call(Context::GetCurrent()->Global(), 1, argv); } return scope.Close(Undefined()); }
Handle<Value> JSDatasource::New(const Arguments& args) { if (!args.IsConstructCall()) return ThrowException(String::New("Cannot call constructor as function, you need to use 'new' keyword")); if (args[0]->IsExternal()) { //std::clog << "external!\n"; Local<External> ext = Local<External>::Cast(args[0]); void* ptr = ext->Value(); JSDatasource* d = static_cast<JSDatasource*>(ptr); d->Wrap(args.This()); return args.This(); } if (!args.Length() == 2){ return ThrowException(Exception::TypeError( String::New("two argument required: an object of key:value datasource options and a callback function for features"))); } if (!args[0]->IsObject()) return ThrowException(Exception::TypeError( String::New("Must provide an object, eg {extent: '-180,-90,180,90'}"))); Local<Object> options = args[0]->ToObject(); // function callback if (!args[args.Length()-1]->IsFunction()) return ThrowException(Exception::TypeError( String::New("last argument must be a callback function"))); // TODO - maybe validate in js? bool bind=true; if (options->Has(String::New("bind"))) { Local<Value> bind_opt = options->Get(String::New("bind")); if (!bind_opt->IsBoolean()) return ThrowException(Exception::TypeError( String::New("'bind' must be a Boolean"))); bind = bind_opt->BooleanValue(); } mapnik::parameters params; params["type"] = "js"; Local<Array> names = options->GetPropertyNames(); uint32_t i = 0; uint32_t a_length = names->Length(); while (i < a_length) { Local<Value> name = names->Get(i)->ToString(); Local<Value> value = options->Get(name); params[TOSTR(name)] = TOSTR(value); i++; } mapnik::datasource_ptr ds; try { ds = mapnik::datasource_ptr(new js_datasource(params,bind,args[args.Length()-1])); } catch (const std::exception & ex) { return ThrowException(Exception::Error( String::New(ex.what()))); } catch (...) { return ThrowException(Exception::Error( String::New("unknown exception happened, please file bug"))); } if (ds) { JSDatasource* d = new JSDatasource(); d->Wrap(args.This()); d->ds_ptr_ = ds; return args.This(); } return Undefined(); }
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(); }
Handle<Value> Grid::New(const Arguments& args) { HandleScope scope; if (!args.IsConstructCall()) return ThrowException(String::New("Cannot call constructor as function, you need to use 'new' keyword")); if (args[0]->IsExternal()) { //std::clog << "external!\n"; Local<External> ext = Local<External>::Cast(args[0]); void* ptr = ext->Value(); Grid* g = static_cast<Grid*>(ptr); g->Wrap(args.This()); return args.This(); } if (args.Length() >= 2) { if (!args[0]->IsNumber() || !args[1]->IsNumber()) return ThrowException(Exception::TypeError( String::New("Grid 'width' and 'height' must be a integers"))); // defaults std::string key("__id__"); unsigned int resolution = 1; if (args.Length() >= 3) { if (!args[2]->IsObject()) return ThrowException(Exception::TypeError( String::New("optional third arg must be an options object"))); Local<Object> options = args[2]->ToObject(); if (options->Has(String::New("key"))) { Local<Value> bind_opt = options->Get(String::New("key")); if (!bind_opt->IsString()) return ThrowException(Exception::TypeError( String::New("optional arg 'key' must be an string"))); key = TOSTR(bind_opt); } // TODO - remove, deprecated if (options->Has(String::New("resolution"))) { Local<Value> bind_opt = options->Get(String::New("resolution")); if (!bind_opt->IsNumber()) return ThrowException(Exception::TypeError( String::New("optional arg 'resolution' must be an string"))); resolution = bind_opt->IntegerValue(); } } Grid* g = new Grid(args[0]->IntegerValue(),args[1]->IntegerValue(),key,resolution); g->Wrap(args.This()); return args.This(); } else { return ThrowException(Exception::Error( String::New("please provide Grid width and height"))); } return Undefined(); }
Handle<Value> Grid::encode(const Arguments& args) // format, resolution { HandleScope scope; Grid* g = ObjectWrap::Unwrap<Grid>(args.This()); // defaults std::string format("utf"); unsigned int resolution = 4; bool add_features = true; // accept custom format if (args.Length() >= 1){ if (!args[0]->IsString()) return ThrowException(Exception::TypeError( String::New("first arg, 'format' must be a string"))); format = TOSTR(args[0]); } // options hash if (args.Length() >= 2) { if (!args[1]->IsObject()) return ThrowException(Exception::TypeError( String::New("optional second arg must be an options object"))); Local<Object> options = args[1]->ToObject(); if (options->Has(String::New("resolution"))) { Local<Value> bind_opt = options->Get(String::New("resolution")); if (!bind_opt->IsNumber()) return ThrowException(Exception::TypeError( String::New("'resolution' must be an Integer"))); resolution = bind_opt->IntegerValue(); } if (options->Has(String::New("features"))) { Local<Value> bind_opt = options->Get(String::New("features")); if (!bind_opt->IsBoolean()) return ThrowException(Exception::TypeError( String::New("'features' must be an Boolean"))); add_features = bind_opt->BooleanValue(); } } // ensure callback is a function if (!args[args.Length()-1]->IsFunction()) return ThrowException(Exception::TypeError( String::New("last argument must be a callback function"))); Local<Function> callback = Local<Function>::Cast(args[args.Length()-1]); encode_grid_baton_t *closure = new encode_grid_baton_t(); closure->request.data = closure; closure->g = g; closure->format = format; closure->error = false; closure->resolution = resolution; closure->add_features = add_features; closure->cb = Persistent<Function>::New(Handle<Function>::Cast(callback)); // todo - reserve lines size? uv_queue_work(uv_default_loop(), &closure->request, EIO_Encode, EIO_AfterEncode); g->Ref(); return Undefined(); }