コード例 #1
0
void DBOperationHelper_NonVO(Handle<Object> spec, KeyOperation & op) {
  HandleScope scope;

  Local<Value> v;
  Local<Object> o;

  setKeysInOp(spec, op);
  
  v = spec->Get(HELPER_ROW_BUFFER);
  if(! v->IsNull()) {
    o = v->ToObject();
    op.row_buffer = V8BINDER_UNWRAP_BUFFER(o);
  }
  
  v = spec->Get(HELPER_ROW_RECORD);
  if(! v->IsNull()) {
    o = v->ToObject();
    const Record * record = unwrapPointer<const Record *>(o);
    op.row_record = record;

    v = spec->Get(HELPER_BLOBS);
    if(v->IsObject()) {
      if(op.opcode == 1) {
        op.nblobs = op.createBlobReadHandles(record);
      } else {
        op.nblobs = op.createBlobWriteHandles(v->ToObject(), record);
      }
    }
  }
  
  v = spec->Get(HELPER_LOCK_MODE);
  if(! v->IsNull()) {
    int intLockMode = v->Int32Value();
    op.lmode = static_cast<NdbOperation::LockMode>(intLockMode);
  }

  v = spec->Get(HELPER_COLUMN_MASK);
  if(! v->IsNull()) {
    Array *maskArray = Array::Cast(*v);
    for(unsigned int m = 0 ; m < maskArray->Length() ; m++) {
      Local<Value> colId = maskArray->Get(m);
      op.useColumn(colId->Int32Value());
    }
  }

  DEBUG_PRINT("Non-VO %s -- mask: %u lobs: %d", op.getOperationName(), 
              op.u.maskvalue, op.nblobs);
}
コード例 #2
0
void setKeysInOp(Handle<Object> spec, KeyOperation & op) {
  Local<Value> v;
  Local<Object> o;

  v = spec->Get(HELPER_KEY_BUFFER);
  if(! v->IsNull()) {
    o = v->ToObject();
    op.key_buffer = node::Buffer::Data(o);
  }
  
  v = spec->Get(HELPER_KEY_RECORD);
  if(! v->IsNull()) {
    o = v->ToObject();
    op.key_record = unwrapPointer<const Record *>(o);
  }
}
コード例 #3
0
JNIEXPORT void JNICALL
Java_org_appcelerator_kroll_runtime_v8_V8Object_nativeSetWindow
	(JNIEnv *env, jobject javaKrollWindow, jlong ptr, jobject javaWindow)
{
	HandleScope scope(V8Runtime::v8_isolate);
	titanium::JNIScope jniScope(env);

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

	Local<Value> setWindowValue = jsKrollWindow->Get(STRING_NEW(V8Runtime::v8_isolate, "setWindow"));
	if (!setWindowValue->IsFunction()) {
		return;
	}

	Local<Function> setWindow = setWindowValue.As<Function>();

	Local<Value> jsWindow = TypeConverter::javaObjectToJsValue(V8Runtime::v8_isolate, env, javaWindow);

	TryCatch tryCatch(V8Runtime::v8_isolate);
	if (!jsWindow->IsNull()) {
		Local<Value> args[] = { jsWindow };
		setWindow->Call(V8Runtime::v8_isolate->GetCurrentContext(), jsKrollWindow, 1, args);
	}

	if (tryCatch.HasCaught()) {
		V8Util::openJSErrorDialog(V8Runtime::v8_isolate, tryCatch);
		V8Util::reportException(V8Runtime::v8_isolate, tryCatch);
	}
}
コード例 #4
0
ファイル: rtScriptNode.cpp プロジェクト: madanagopalt/pxCore
rtValue rtNodeContext::get(const char *name)
{
  if(name == NULL)
  {
    rtLogError(" rtNodeContext::get() - no symbolic name for rtValue");
    return rtValue();
  }

  Locker                locker(mIsolate);
  Isolate::Scope isolate_scope(mIsolate);
  HandleScope     handle_scope(mIsolate);    // Create a stack-allocated handle scope.

  // Get a Local context...
  Local<Context> local_context = node::PersistentToLocal<Context>(mIsolate, mContext);
  Context::Scope context_scope(local_context);

  Handle<Object> global = local_context->Global();

  // Get the object
  Local<Value> object = global->Get( String::NewFromUtf8(mIsolate, name) );

  if(object->IsUndefined() || object->IsNull() )
  {
    rtLogError("FATAL: '%s' is Undefined ", name);
    return rtValue();
  }
  else
  {
    rtWrapperError error; // TODO - handle error
    return js2rt(local_context, object, &error);
  }
}
コード例 #5
0
ファイル: engine.hpp プロジェクト: jfirebaugh/node-OSRM
Handle<Value> Engine::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) {
            if (!args[0]->IsObject()) {
                return ThrowException(Exception::TypeError(String::New("must provide an osrm.Options object")));
            }
            Local<Object> obj = args[0]->ToObject();
            if (obj->IsNull() || obj->IsUndefined() || !Options::constructor->HasInstance(obj)) {
                return ThrowException(Exception::TypeError(String::New("osrm.Options object expected for first argument")));
            }
            Options *opts = ObjectWrap::Unwrap<Options>(obj);
            Engine* im = new Engine(opts);
            im->Wrap(args.This());
            return args.This();
        } else {
            return ThrowException(Exception::TypeError(String::New("please provide Engine width and height")));
        }
    } catch (std::exception const& ex) {
        return ThrowException(Exception::Error(String::New(ex.what())));
    }
    return Undefined();
}
void PushbotsModule::setter_enabled(Local<String> property, Local<Value> value, const AccessorInfo& info)
{
	LOGD(TAG, "set enabled");
	HandleScope scope;

	JNIEnv *env = titanium::JNIScope::getEnv();
	if (!env) {
		LOGE(TAG, "Failed to get environment, enabled wasn't set");
		return;
	}

	static jmethodID methodID = NULL;
	if (!methodID) {
		methodID = env->GetMethodID(PushbotsModule::javaClass, "setEnabled", "(Ljava/lang/Boolean;)V");
		if (!methodID) {
			const char *error = "Couldn't find proxy method 'setEnabled' with signature '(Ljava/lang/Boolean;)V'";
			LOGE(TAG, error);
		}
	}

	titanium::Proxy* proxy = titanium::Proxy::unwrap(info.Holder());
	if (!proxy) {
		return;
	}

	jvalue jArguments[1];

	bool isNew_0;
	
	if (!value->IsNull()) {
		Local<Value> arg_0 = value;
		jArguments[0].l =
			titanium::TypeConverter::jsValueToJavaObject(env, arg_0, &isNew_0);
	} else {
		jArguments[0].l = NULL;
	}

	jobject javaProxy = proxy->getJavaObject();
	env->CallVoidMethodA(javaProxy, methodID, jArguments);

	if (!JavaObject::useGlobalRefs) {
		env->DeleteLocalRef(javaProxy);
	}



			if (isNew_0) {
				env->DeleteLocalRef(jArguments[0].l);
			}


	if (env->ExceptionCheck()) {
		titanium::JSException::fromJavaException();
		env->ExceptionClear();
	}




}
コード例 #7
0
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();
}
コード例 #8
0
ファイル: gdal_field_defn.cpp プロジェクト: jarped/node-gdal
void FieldDefn::justificationSetter(Local<String> property, Local<Value> value, const AccessorInfo &info)
{
	HandleScope scope;
	FieldDefn *def = ObjectWrap::Unwrap<FieldDefn>(info.This());
	

	OGRJustification justification;
	std::string str = TOSTR(value);
	if(value->IsString()){
		if(str == "Left") {
			justification = OJLeft;
		} else if (str == "Right") {
			justification = OJRight;
		} else if (str == "Undefined") {
			justification = OJUndefined; 
		} else {
			NODE_THROW("Unrecognized justification");
			return;
		}
	} else if (value->IsNull() || value->IsUndefined()){
		justification = OJUndefined;
	} else {
		NODE_THROW("justification must be a string or undefined");
		return;
	}
	
	def->this_->SetJustify(justification);
}
コード例 #9
0
Handle<Value> TiAppPropertiesObject::_set(const Arguments& args, PropertyType type)
{
    HandleScope scope;

    Local<Value> key = args[0], value = args[1];

    if (key->IsUndefined() || key->IsNull()) {
        return Undefined();
    }

    // Remove property if value is set to null or undefined.
    if (value->IsUndefined() || value->IsNull()) {
        settings.remove(QString::fromUtf8(*String::Utf8Value(key)));
        return Undefined();
    }

    // Serialize the property value to JSON.
    Local<String> json = stringify(convertType(type, value));

    // Update the application settings with the new property value.
    settings.setValue(QString::fromUtf8(*String::Utf8Value(key)),
                      QString::fromUtf8(*String::Utf8Value(json)));

    return Undefined();
}
コード例 #10
0
Handle<Value> TiAppPropertiesObject::_get(const Arguments& args, PropertyType type)
{
    HandleScope scope;

    Local<Value> k = args[0], defaultValue = args[1];

    // If key is undefined or null do nothing.
    if (k->IsUndefined() || k->IsNull()) {
        return Undefined();
    }

    // Lookup property value from the application settings.
    QString key = QString::fromUtf8(*String::Utf8Value(k));
    QVariant value = settings.value(key);
    if (value.isValid()) {
        // Parse JSON value and return value as type requested by caller.
        return scope.Close(convertType(type, parseJson(value.toString())));
    }

    // Fallback to default settings if no property found.
    value = defaultSettings.value(key);
    if (value.isValid()) {
        // The default property values should be valid strings, not JSON.
        // We still must convert the type if the user requests a non-string type.
        Q_ASSERT(value.canConvert(QVariant::String));
        return scope.Close(convertType(type, String::New(value.toString().toUtf8())));
    }

    return defaultValue;
}
コード例 #11
0
ファイル: Image.cpp プロジェクト: luismreis/node-image
Image::~Image() {

  Local<Value> internalField = NanObjectWrapHandle(this)->GetInternalField(0);
  if (internalField->IsNull()) return;

  FIBITMAP *dib = static_cast<FIBITMAP*>(Local<External>::Cast(internalField)->Value());
  FreeImage_Unload(dib);
}
コード例 #12
0
ファイル: DBOperationHelper.cpp プロジェクト: rajiv9/mysql-js
void setKeysInOp(Handle<Object> spec, Operation & op) {
  HandleScope scope;

  Local<Value> v;
  Local<Object> o;

  v = spec->Get(HELPER_KEY_BUFFER);
  if(! v->IsNull()) {
    o = v->ToObject();
    op.key_buffer = V8BINDER_UNWRAP_BUFFER(o);
  }
  
  v = spec->Get(HELPER_KEY_RECORD);
  if(! v->IsNull()) {
    o = v->ToObject();
    op.key_record = unwrapPointer<const Record *>(o);
  }
}
コード例 #13
0
ファイル: native_window.cpp プロジェクト: cthackers/appjs
long NativeWindow::JSResult(){
  Local<Value> result = v8handle_->Get(String::NewSymbol("result"));
  if (result->IsUndefined() || result->IsNull()) {
    return 0;
  } else {
    v8handle_->Set(String::NewSymbol("result"), Undefined());
    return result->Int32Value();
  }
}
コード例 #14
0
ファイル: DBOperationHelper.cpp プロジェクト: rajiv9/mysql-js
Handle<Value> DBOperationHelper_NonVO(const Arguments &args) {
  HandleScope scope;
  Operation op;

  const Local<Object> spec = args[0]->ToObject();
  Local<Value> v;
  Local<Object> o;

  setKeysInOp(spec, op);
  
  v = spec->Get(HELPER_ROW_BUFFER);
  if(! v->IsNull()) {
    o = v->ToObject();
    op.row_buffer = V8BINDER_UNWRAP_BUFFER(o);
  }
  
  v = spec->Get(HELPER_ROW_RECORD);
  if(! v->IsNull()) {
    o = v->ToObject();
    op.row_record = unwrapPointer<const Record *>(o);
  }
  
  v = spec->Get(HELPER_LOCK_MODE);
  if(! v->IsNull()) {
    int intLockMode = v->Int32Value();
    op.lmode = static_cast<NdbOperation::LockMode>(intLockMode);
  }

  v = spec->Get(HELPER_COLUMN_MASK);
  if(! v->IsNull()) {
    Array *maskArray = Array::Cast(*v);
    for(unsigned int m = 0 ; m < maskArray->Length() ; m++) {
      Local<Value> colId = maskArray->Get(m);
      op.useColumn(colId->Int32Value());
    }
  }
  
  int opcode = args[1]->Int32Value();
  NdbTransaction *tx = unwrapPointer<NdbTransaction *>(args[2]->ToObject());
  DEBUG_PRINT("Non-VO opcode: %d mask: %u", opcode, op.u.maskvalue);

  return scope.Close(buildNdbOperation(op, opcode, tx));
}
コード例 #15
0
bool V8Value::hasProperty(std::string propertyName)
{
    HandleScope handleScope;

    Local<Object> obj = value->ToObject();

    Local<Value> val = obj->Get(String::New(propertyName.c_str()));
    return !(val->IsNull() || val->IsUndefined()); // These are not 'true' values, that we can return in e.g. getPropertyString
                                                   // (we can't return 'Null' there - so this is for both undefined and null)
}
コード例 #16
0
ファイル: mapnik_feature.cpp プロジェクト: booo/node-mapnik
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();
}
コード例 #17
0
Handle<Value> MSRect::Project(const Arguments &args) {
  MSRect *rect = ObjectWrap::Unwrap<MSRect>(args.This());
  Local<Object> obj;
  MSProjection *projIn;
  MSProjection *projOut;

  if (args.Length() != 2) {
    THROW_ERROR(Error, "projecting a point requires two projection arguments");
  }

  if (!args[0]->IsObject()) {
    THROW_ERROR(TypeError, "first argument to project must be Projection object");
  }

  obj = args[0]->ToObject();

  if (obj->IsNull() || obj->IsUndefined() || !MSProjection::constructor->HasInstance(obj)) {
    THROW_ERROR(TypeError, "first argument to project must be Projection object");
  }

  projIn = ObjectWrap::Unwrap<MSProjection>(obj);

  if (!args[1]->IsObject()) {
    THROW_ERROR(TypeError, "second argument to project must be Projection object");
  }

  obj = args[1]->ToObject();

  if (obj->IsNull() || obj->IsUndefined() || !MSProjection::constructor->HasInstance(obj)) {
    THROW_ERROR(TypeError, "first argument to project must be Projection object");
  }

  projOut = ObjectWrap::Unwrap<MSProjection>(obj);

  msProjectRect(projIn->this_, projOut->this_, rect->this_);

  return Undefined();
}
コード例 #18
0
ファイル: gdal_geometry.cpp プロジェクト: xkwangy/node-gdal
void Geometry::srsSetter(Local<String> property, Local<Value> value, const AccessorInfo &info)
{
	HandleScope scope;
	Geometry *geom = ObjectWrap::Unwrap<Geometry>(info.This());

	OGRSpatialReference *srs = NULL;
	if (SpatialReference::constructor->HasInstance(value)) {
		SpatialReference *srs_obj = ObjectWrap::Unwrap<SpatialReference>(value->ToObject());
		srs = srs_obj->get();
	} else if (!value->IsNull() && !value->IsUndefined()) {
		NODE_THROW("srs must be SpatialReference object");
		return;
	}

	geom->this_->assignSpatialReference(srs);
}
コード例 #19
0
bool JSWrapper::execute( const char *scr, JSWrapperData *data, const char *fileName )
{
    HandleScope handle_scope( m_isolate );

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

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

    bool success=false;

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

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

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

            success=true;
        } 
    }

    return success;
}
コード例 #20
0
ファイル: mapnik_image.cpp プロジェクト: tannewt/node-mapnik
Handle<Value> Image::setGrayScaleToAlpha(const Arguments& args)
{
    HandleScope scope;

    Image* im = ObjectWrap::Unwrap<Image>(args.This());
    if (args.Length() == 0) {
        im->this_->set_grayscale_to_alpha();
    } else {
        if (!args[0]->IsObject())
            return ThrowException(Exception::TypeError(
                                      String::New("optional second arg must be a mapnik.Color")));

        Local<Object> obj = args[0]->ToObject();

        if (obj->IsNull() || obj->IsUndefined() || !Color::constructor->HasInstance(obj))
            return ThrowException(Exception::TypeError(String::New("mapnik.Color expected as second arg")));

        Color * color = ObjectWrap::Unwrap<Color>(obj);

        mapnik::image_data_32 & data = im->this_->data();
        for (unsigned int y = 0; y < data.height(); ++y)
        {
            unsigned int* row_from = data.getRow(y);
            for (unsigned int x = 0; x < data.width(); ++x)
            {
                unsigned rgba = row_from[x];
                // TODO - big endian support
                unsigned r = rgba & 0xff;
                unsigned g = (rgba >> 8 ) & 0xff;
                unsigned b = (rgba >> 16) & 0xff;

                // magic numbers for grayscale
                unsigned a = (int)((r * .3) + (g * .59) + (b * .11));

                row_from[x] = (a << 24) |
                    (color->get()->blue() << 16) |
                    (color->get()->green() << 8) |
                    (color->get()->red()) ;
            }
        }
    }

    return Undefined();
}
コード例 #21
0
void Image::set_prop(Local<String> property,
                     Local<Value> value,
                     const AccessorInfo& info)
{
    HandleScope scope;
    Image* im = node::ObjectWrap::Unwrap<Image>(info.Holder());
    std::string a = TOSTR(property);
    if (a == "background") {
        if (!value->IsObject())
            ThrowException(Exception::TypeError(
                               String::New("mapnik.Color expected")));

        Local<Object> obj = value->ToObject();
        if (obj->IsNull() || obj->IsUndefined() || !Color::constructor->HasInstance(obj))
            ThrowException(Exception::TypeError(String::New("mapnik.Color expected")));
        Color *c = node::ObjectWrap::Unwrap<Color>(obj);
        im->get()->set_background(*c->get());
    }
}
コード例 #22
0
ファイル: mapnik_feature.cpp プロジェクト: booo/node-mapnik
// TODO void?
Handle<Value> Feature::addGeometry(const Arguments& args)
{
    HandleScope scope;

    Feature* fp = ObjectWrap::Unwrap<Feature>(args.This());

    if (args.Length() >= 1 ) {
        Local<Value> value = args[0];
        if (value->IsNull() || value->IsUndefined()) {
            return ThrowException(Exception::TypeError(String::New("mapnik.Geometry instance expected")));
        } else {
            Local<Object> obj = value->ToObject();
            if (Geometry::constructor->HasInstance(obj)) {
                Geometry* g = ObjectWrap::Unwrap<Geometry>(obj);
            
                try
                {
                    std::auto_ptr<mapnik::geometry_type> geom_ptr = g->get();
                    if (geom_ptr.get()) {
                        fp->get()->add_geometry(geom_ptr.get());
                        geom_ptr.release();
                    } else {
                        return ThrowException(Exception::Error(
                          String::New("empty geometry!")));
                    }
                }
                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();
}
コード例 #23
0
ファイル: engine.hpp プロジェクト: jfirebaugh/node-OSRM
Handle<Value> Engine::run(Arguments const& args)
{
    HandleScope scope;

    if (args.Length() == 1) {
        return runSync(args);
    }

    if (args.Length() < 1) {
        ThrowException(String::New("first argument must be a osrm.Query"));
    }

    if (!args[0]->IsObject()) {
        return ThrowException(String::New("first argument must be a osrm.Query object"));
    }

    Local<Object> obj = args[0]->ToObject();
    if (obj->IsNull() || obj->IsUndefined() || !Query::constructor->HasInstance(obj)) {
        ThrowException(Exception::TypeError(String::New("osrm.Query object expected for first argument")));
    }

    // 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")));
    }

    Query * query = ObjectWrap::Unwrap<Query>(obj);
    Engine * machine = ObjectWrap::Unwrap<Engine>(args.This());
    run_query_baton_t *closure = new run_query_baton_t();
    closure->request.data = closure;
    closure->machine = machine;
    closure->query = query;
    closure->error = false;
    closure->cb = Persistent<Function>::New(Handle<Function>::Cast(callback));
    uv_queue_work(uv_default_loop(), &closure->request, AsyncRun, (uv_after_work_cb)AfterRun);
    closure->machine->_ref();
    closure->query->_ref();
    return Undefined();
}
コード例 #24
0
ファイル: gumv8process.cpp プロジェクト: terry2012/frida-gum
/*
 * Prototype:
 * Process.setExceptionHandler(callback)
 *
 * Docs:
 * TBW
 *
 * Example:
 * TBW
 */
static void
gum_v8_process_on_set_exception_handler (
    const FunctionCallbackInfo<Value> & info)
{
  GumV8Process * self = static_cast<GumV8Process *> (
      info.Data ().As<External> ()->Value ());
  Isolate * isolate = info.GetIsolate ();

  bool argument_valid = false;
  Local<Function> callback;
  if (info.Length () >= 1)
  {
    Local<Value> argument = info[0];
    if (argument->IsFunction ())
    {
      argument_valid = true;
      callback = argument.As<Function> ();
    }
    else if (argument->IsNull ())
    {
      argument_valid = true;
    }
  }
  if (!argument_valid)
  {
    isolate->ThrowException (Exception::TypeError (String::NewFromUtf8 (
        isolate, "invalid argument")));
    return;
  }

  gum_v8_exception_handler_free (self->exception_handler);
  self->exception_handler = NULL;

  if (!callback.IsEmpty ())
  {
    self->exception_handler = gum_v8_exception_handler_new (callback,
        self->core);
  }
}
コード例 #25
0
ファイル: engine.hpp プロジェクト: jfirebaugh/node-OSRM
Handle<Value> Engine::runSync(Arguments const& args)
{
    HandleScope scope;

    if (args.Length() < 1) {
        ThrowException(Exception::TypeError(String::New("first argument must be a osrm.Query")));
    }

    if (!args[0]->IsObject()) {
        return ThrowException(Exception::TypeError(String::New("first argument must be a osrm.Query object")));
    }

    Local<Object> obj = args[0]->ToObject();
    if (obj->IsNull() || obj->IsUndefined() || !Query::constructor->HasInstance(obj)) {
        return ThrowException(Exception::TypeError(String::New("osrm.Query object expected for first argument")));
    }
    Query *query = ObjectWrap::Unwrap<Query>(obj);
    Engine* machine = ObjectWrap::Unwrap<Engine>(args.This());
    http::Reply osrm_reply;
    machine->this_->RunQuery(*query->get(), osrm_reply);
    return scope.Close(String::New(osrm_reply.content.c_str()));
}
コード例 #26
0
Handle<Value> MSMap::InsertLayer (const Arguments& args) {
  HandleScope scope;
  MSMap *map = ObjectWrap::Unwrap<MSMap>(args.This());
  MSLayer *layer;
  Local<Object> obj;
  int result;
  int position = -1;

  if (args.Length() < 1) {
    THROW_ERROR(Error, "insertLayer requires at least one argument");
  }

  if (!args[0]->IsObject()) {
    THROW_ERROR(TypeError, "first argument to project must be Layer object");
  }

  obj = args[0]->ToObject();

  if (obj->IsNull() || obj->IsUndefined() || !MSLayer::constructor->HasInstance(obj)) {
    THROW_ERROR(TypeError, "first argument to project must be Layer object");
  }

  layer = ObjectWrap::Unwrap<MSLayer>(obj);

  if (args.Length() == 2) {
    if (!args[1]->IsNumber()) {
      THROW_ERROR(TypeError, "second argument must be an integer");
    } else {
      position = args[1]->ToInteger()->Value();
      if (position >= map->this_->numlayers) {
        position = -1;
      }
    }
  }
  result = msInsertLayer(map->this_, layer->this_, position);

  return scope.Close(Number::New(result));
}
コード例 #27
0
ファイル: protobuf.cpp プロジェクト: ftcaicai/GOD
	void SerializePart(google::protobuf::Message *message, Handle<Object> src) {
		Handle<Function> to_array = handle_->GetInternalField(3).As<Function>();
		Handle<Array> properties = to_array->Call(src, 0, NULL).As<Array>();
		const Reflection *r = message->GetReflection();
		for (int i = 0; i < descriptor->field_count(); i++) {
			Local<Value> value = properties->Get(i);
			if (value->IsUndefined() || value->IsNull()) 
				continue;

			const FieldDescriptor* field = descriptor->field(i);
			if (field->is_repeated()) {
				if (value->IsArray()) {
					Handle<Array> array = value.As<Array>();
					int length = array->Length();
					for (int j = 0; j < length; j++)
						SerializeField(message, r, field, array->Get(j));
				}
				else if (value->IsObject() && 
					field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE && 
					field->message_type()->name().compare(0, 20, "KeyValuePair_String_") == 0) {
					Local<Object> object = value.As<Object>();
					Local<Array> subProperties = object->GetOwnPropertyNames();
					int len = subProperties->Length();
					for (int keyIdx = 0; keyIdx < len; keyIdx++) {
						Local<Object> keyValuePair = Object::New();
						Local<Value> key = subProperties->Get(keyIdx);
						keyValuePair->Set(KeySymbol, key);
						keyValuePair->Set(ValueSymbol, object->Get(key));
						SerializeField(message, r, field, keyValuePair);
					}
				}
			} else {
				SerializeField(message, r, field, value);
			}
		}
	}
コード例 #28
0
Handle<Value> Expression::evaluate(const Arguments& args)
{
    HandleScope scope;

    if (args.Length() < 1) {
        return ThrowException(Exception::Error(
                                  String::New("requires a mapnik.Feature as an argument")));
    }

    Local<Object> obj = args[0]->ToObject();
    if (obj->IsNull() || obj->IsUndefined()) {
        return ThrowException(Exception::TypeError(String::New("first argument is invalid, must be a mapnik.Feature not null/undefined")));
    }

    if (!Feature::constructor->HasInstance(obj)) {
        return ThrowException(Exception::TypeError(String::New("first argument is invalid, must be a mapnik.Feature")));
    }

    Feature* f = node::ObjectWrap::Unwrap<Feature>(obj);

    Expression* e = node::ObjectWrap::Unwrap<Expression>(args.This());
    mapnik::value value_obj = boost::apply_visitor(mapnik::evaluate<mapnik::Feature,mapnik::value>(*(f->get())),*(e->get()));
    return scope.Close(boost::apply_visitor(node_mapnik::value_converter(),value_obj.base()));
}
コード例 #29
0
ファイル: IndexBoundHelper.cpp プロジェクト: mysql/mysql-js
void newIndexBound(const Arguments &args) {
  EscapableHandleScope scope(args.GetIsolate());

  NdbIndexScanOperation::IndexBound * bound = 
    new NdbIndexScanOperation::IndexBound;
  Local<Value> jsBound = IndexBoundEnvelope.wrap(bound);

  const Local<Object> spec = args[0]->ToObject();
  Local<Value> v;
  Local<Object> o;


  bound->low_key = 0;
  v = spec->Get(BOUND_LOW_KEY);
  if(v->IsNull()) {
    bound->low_key = 0;
  } else {
    o = v->ToObject();
    bound->low_key = node::Buffer::Data(o);
  }

  bound->low_key_count = 0;
  v = spec->Get(BOUND_LOW_KEY_COUNT);
  if(! v->IsNull()) {
    bound->low_key_count = v->Uint32Value();
  }
  
  bound->low_inclusive = false;
  v = spec->Get(BOUND_LOW_INCLUSIVE);
  if(! v->IsNull()) {
    bound->low_inclusive = v->BooleanValue();
  }
  
  bound->high_key = 0;
  v = spec->Get(BOUND_HIGH_KEY);
  if(v->IsNull()) {
    bound->high_key = 0;
  } else {
    o = v->ToObject();
    bound->high_key = node::Buffer::Data(o);
  }
  
  bound->high_key_count = 0;
  v = spec->Get(BOUND_HIGH_KEY_COUNT);
  if(! v->IsNull()) {
    bound->high_key_count = v->Uint32Value();
  }
  
  bound->high_inclusive = false;
  v = spec->Get(BOUND_HIGH_INCLUSIVE);
  if(! v->IsNull()) {
    bound->high_inclusive = v->BooleanValue();
  }
  
  bound->range_no = 0;
  v = spec->Get(BOUND_RANGE_NO);
  if(! v->IsNull()) {
    bound->range_no = v->Uint32Value();
  }

  debug_print_bound(bound);

  args.GetReturnValue().Set(scope.Escape(jsBound));
}
コード例 #30
0
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);
		}
	}
}