void MetadataNode::MethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
	SET_PROFILER_FRAME();

	auto e = info.Data().As<External>();

	auto callbackData = reinterpret_cast<MethodCallbackData*>(e->Value());

	int argLength = info.Length();

	MetadataEntry *entry = nullptr;

	string *className;
	const auto& first = callbackData->candidates.front();
	const auto& methodName = first.name;

	while ((callbackData != nullptr) && (entry == nullptr))
	{
		auto& candidates = callbackData->candidates;

		className = &callbackData->node->m_name;

		auto found = false;
		for (auto& c: candidates)
		{
			found = c.paramCount == argLength;
			if (found)
			{
				entry = &c;
				break;
			}
		}

		if (!found)
		{
			callbackData = callbackData->parent;
		}
	}

	auto thiz = info.This();

	auto isSuper = false;
	if (!first.isStatic)
	{
		auto superValue = thiz->GetInternalField(static_cast<int>(ObjectManager::MetadataNodeKeys::CallSuper));
		isSuper = !superValue.IsEmpty() && superValue->IsTrue();
	}

//	// TODO: refactor this
	if (isSuper && (*className == "com/tns/NativeScriptActivity"))
	{
		string activityBaseClassName("android/app/Activity");
		className = &activityBaseClassName;
	}

	if ((argLength == 0) && (methodName == V8StringConstants::VALUE_OF))
	{
		info.GetReturnValue().Set(thiz);
	}
	else
	{
		NativeScriptRuntime::CallJavaMethod(thiz, *className, methodName, entry, first.isStatic, isSuper, info);
	}
}
Esempio n. 2
0
void Proxy::proxyConstructor(const v8::FunctionCallbackInfo<v8::Value>& args)
{
    LOGD(TAG, "proxy constructor callback!");
    Isolate* isolate = args.GetIsolate();
    EscapableHandleScope scope(isolate);

    JNIEnv *env = JNIScope::getEnv();
    Local<Object> jsProxy = args.This();

    // First things first, we need to wrap the object in case future calls need to unwrap proxy!
    Proxy* proxy = new Proxy(NULL);
    proxy->wrap(isolate, jsProxy);

    // every instance gets a special "_properties" object for us to use internally for get/setProperty
    jsProxy->DefineOwnProperty(isolate->GetCurrentContext(), propertiesSymbol.Get(isolate), Object::New(isolate), static_cast<PropertyAttribute>(DontEnum));

    // Now we hook up a java Object from the JVM...
    jobject javaProxy = ProxyFactory::unwrapJavaProxy(args); // do we already have one that got passed in?
    bool deleteRef = false;
    if (!javaProxy) {
        // No passed in java object, so let's create an instance
        // Look up java class from prototype...
        Local<Object> prototype = jsProxy->GetPrototype()->ToObject(isolate);
        Local<Function> constructor = prototype->Get(constructorSymbol.Get(isolate)).As<Function>();
        Local<External> wrap = constructor->Get(javaClassSymbol.Get(isolate)).As<External>();
        jclass javaClass = static_cast<jclass>(wrap->Value());

        // Now we create an instance of the class and hook it up
        JNIUtil::logClassName("Creating java proxy for class %s", javaClass);
        javaProxy = ProxyFactory::createJavaProxy(javaClass, jsProxy, args);
        deleteRef = true;
    }
    proxy->attach(javaProxy);

    int length = args.Length();

    if (length > 0 && args[0]->IsObject()) {
        bool extend = true;
        Local<Object> createProperties = args[0].As<Object>();
        Local<String> constructorName = createProperties->GetConstructorName();
        if (strcmp(*titanium::Utf8Value(constructorName), "Arguments") == 0) {
            extend = false;
            int32_t argsLength = createProperties->Get(STRING_NEW(isolate, "length"))->Int32Value();
            if (argsLength > 1) {
                Local<Value> properties = createProperties->Get(1);
                if (properties->IsObject()) {
                    extend = true;
                    createProperties = properties.As<Object>();
                }
            }
        }

        if (extend) {
            Local<Array> names = createProperties->GetOwnPropertyNames();
            int length = names->Length();
            Local<Object> properties = jsProxy->Get(propertiesSymbol.Get(isolate))->ToObject(isolate);

            for (int i = 0; i < length; ++i) {
                Local<Value> name = names->Get(i);
                Local<Value> value = createProperties->Get(name);
                bool isProperty = true;
                if (name->IsString()) {
                    Local<String> nameString = name.As<String>();
                    if (!jsProxy->HasRealNamedCallbackProperty(nameString)
                            && !jsProxy->HasRealNamedProperty(nameString)) {
                        jsProxy->Set(name, value);
                        isProperty = false;
                    }
                }
                if (isProperty) {
                    properties->Set(name, value);
                }
            }
        }
    }


    if (!args.Data().IsEmpty() && args.Data()->IsFunction()) {
        Local<Function> proxyFn = args.Data().As<Function>();
        Local<Value> *fnArgs = new Local<Value>[length];
        for (int i = 0; i < length; ++i) {
            fnArgs[i] = args[i];
        }
        proxyFn->Call(isolate->GetCurrentContext(), jsProxy, length, fnArgs);
    }

    if (deleteRef) {
        JNIEnv *env = JNIScope::getEnv();
        if (env) {
            env->DeleteLocalRef(javaProxy);
        }
    }

    args.GetReturnValue().Set(scope.Escape(jsProxy));
}
Esempio n. 3
0
//
// Called from javascript to do prediction
//  This method will call local prediction function
//
void SVMPredict::predict(const v8::FunctionCallbackInfo<v8::Value>& args){

  //v8::Isolate* isolate = args.GetIsolate();//v8::Isolate::GetCurrent();
  //v8::EscapableHandleScope scope(isolate);
  // arguments: 1
  //    Json: { id:"", value:{1:0.1, 2:3.5, ...} }
  // instance of SVMPredict
  //
  if (args.Length()!=1) {
    args.GetIsolate()->ThrowException(
                                      v8::String::NewFromUtf8(args.GetIsolate(), "Wrong arguments"));
    //return;
  }
  // Check arguments type: Null or undefined
  if (args[0]->IsNull() || args[0]->IsUndefined()) {
    args.GetIsolate()->ThrowException(
                                      v8::String::NewFromUtf8( args.GetIsolate(),
                                                              "The Input variable is Null or Undefined"));
    //return;
  }
  v8::Local<v8::Object> lobj = args.Holder();
  if (lobj.IsEmpty()) {
    std::cout<<"Input arguments is empty" <<std::endl;
  }
  SVMPredict* predictor =
  node::ObjectWrap::Unwrap<SVMPredict>(lobj);

  v8::Isolate* isolate = predictor->GetIsolate();
  v8::EscapableHandleScope scope(isolate);

#if defined(PROCESS_DEBUG)
  log(" is called.");
  //CW_ASSERT(&lobj==NULL);
  //CW_ASSERT(predictor==NULL);
#endif

  if (predictor==NULL) {
    std::cout<<"Failed to unwrap predictor: NULL"<<std::endl;
    return;
  }
#if defined(PROCESS_DEBUG)
  std::cout<<"Function:"<<__FUNCTION__<<" Success to unwrap predictor: "
  <<predictor->isModelLoaded<<std::endl;
#endif

  if (!predictor->isModelLoaded) {
    // Model file is not loaded.
    ThrowError("SVM Model is not loaded.");
    //return;
  }
#if defined(PROCESS_DEBUG)
  if (predictor->isModelLoaded) {
    log(" svm model is ready.");
  }
#endif
  struct svm_model* model = predictor->model;
  int nr_class=svm_get_nr_class(predictor->model);
  //svm_save_model(std::string("model").c_str(),predictor->model);
  if (args[0]->IsObject()){
    // single
    v8::Local<v8::Object> obj = v8::Local<v8::Object>::Cast(args[0]);
    // Data conversion
    struct svm_node *prob_node = predictor->FromJsonObj(obj);
    if (prob_node != nullptr){
      //Check field: id
      v8::Local<v8::Value> id = obj->Get(ToV8<std::string>(std::string("id")));
      //predict
      //predictor->print_node(prob_node);
      v8::Local<v8::Object> Result =
      predictor->predict_single(model, prob_node,id,nr_class);

      // free memory
      //free(prob_node);<-- V8 will take it easy.
      //free(labels);
      //free(probab_estimate);
      args.GetReturnValue().Set(Result);
      //scope.Close(id);
      //scope.Close(Result);
    }else{
      ThrowError("Object does not have property id or value.");
      //scope.Escape(obj);
    }

  }else if (args[0]->IsArray()) {
    // Array of Object
    v8::Local<v8::Array> obj = v8::Local<v8::Array>::Cast(args[0]);
    // Data conversion
    struct svm_node **prob_node = nullptr;
    ///////////////////////////
    // Not finished yet
    ///////////////////////////
    //scope.Escape(obj);
  }else{
    ThrowError("Wrong arguments!");
    //scope.Escape(v8::Undefined(isolate));
  }

};
void MetadataNode::InterfaceConstructorCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
	SET_PROFILER_FRAME();

	auto isolate = info.GetIsolate();
	auto thiz = info.This();
	auto node = reinterpret_cast<MetadataNode*>(info.Data().As<External>()->Value());

	Local<Object> implementationObject;
	Local<String> v8ExtendName;
	string extendLocation;
	bool extendLocationFound = GetExtendLocation(extendLocation);
	if (info.Length() == 1)
	{
		if (!extendLocationFound)
		{
			ASSERT_FAIL("Invalid extend() call. No name specified for extend. Location: %s", extendLocation.c_str());
		}

		if (!info[0]->IsObject())
		{
			isolate->ThrowException(ConvertToV8String("First argument must be implementation object"));
			return;
		}
		implementationObject = info[0]->ToObject();
	}
	else if (info.Length() == 2)
	{
		if (!info[0]->IsString())
		{
			isolate->ThrowException(ConvertToV8String("First argument must be string"));
			return;
		}
		if (!info[1]->IsObject())
		{
			isolate->ThrowException(ConvertToV8String("Second argument must be implementation object"));
			return;
		}

		DEBUG_WRITE("InterfaceConstructorCallback: getting extend name");
		v8ExtendName = info[0]->ToString();
		implementationObject = info[1]->ToObject();
	}
	else
	{
		isolate->ThrowException(ConvertToV8String("Invalid number of arguments"));
		return;
	}

	auto className = node->m_implType;
	auto extendName = ConvertToString(v8ExtendName);
	auto extendNameAndLocation = extendLocation + extendName;
	SetInstanceMetadata(isolate, implementationObject, node);

	//@@@ Refactor
	thiz->SetInternalField(static_cast<int>(ObjectManager::MetadataNodeKeys::CallSuper), True(isolate));

	string fullClassName = CreateFullClassName(className, extendNameAndLocation);

	implementationObject->SetPrototype(thiz->GetPrototype());
	thiz->SetPrototype(implementationObject);
	thiz->SetHiddenValue(ConvertToV8String("t::implObj"), implementationObject);

	ArgsWrapper argWrapper(info, ArgType::Interface, Local<Object>());

	auto success = NativeScriptRuntime::RegisterInstance(thiz, fullClassName, argWrapper, implementationObject, true);
}
Esempio n. 5
0
 void JSZCluster::checkArgument(const v8::FunctionCallbackInfo<v8::Value> &info, unsigned int index,
                                const std::shared_ptr<ClusterCmdParamsBase> &cmdParam) {
     if (info.Length() <= ((int) index + 1)) {
         stringstream stream;
         stream << EXECUTE_CMD_BY_ID << " needs almost " << index << " arguments where the first is the cmd";
         throw JSException(stream.str());
     }
     Local<v8::Value> arg = info[index + 1];
     switch (cmdParam->getZCLDataType()) {
         case ZCLTypeDataType::ZCLTypeUInt8:
         case ZCLTypeDataType::ZCLTypeUInt16:
         case ZCLTypeDataType::ZCLTypeUInt24:
         case ZCLTypeDataType::ZCLTypeUInt32:
         case ZCLTypeDataType::ZCLTypeUInt40:
         case ZCLTypeDataType::ZCLTypeUInt48:
         case ZCLTypeDataType::ZCLTypeUInt56:
         case ZCLTypeDataType::ZCLTypeUInt64:
             if (!arg->IsUint32()) {
                 stringstream stream;
                 stream << EXECUTE_CMD_BY_ID << " needs as argument " << index << " an unsigned integer";
                 throw JSException(stream.str());
             }
             break;
         case ZCLTypeDataType::ZCLTypeSInt8:
         case ZCLTypeDataType::ZCLTypeSInt16:
         case ZCLTypeDataType::ZCLTypeSInt24:
         case ZCLTypeDataType::ZCLTypeSInt32:
         case ZCLTypeDataType::ZCLTypeSInt40:
         case ZCLTypeDataType::ZCLTypeSInt48:
         case ZCLTypeDataType::ZCLTypeSInt56:
         case ZCLTypeDataType::ZCLTypeSInt64:
             if (!arg->IsInt32()) {
                 stringstream stream;
                 stream << EXECUTE_CMD_BY_ID << " needs as argument " << index << " an integer";
                 throw JSException(stream.str());
             }
             break;
         case ZCLTypeDataType::ZCLTypeIEEEaddress:
         case ZCLTypeDataType::ZCLTypeStringChar:
             if (!arg->IsString()) {
                 stringstream stream;
                 stream << EXECUTE_CMD_BY_ID << " needs as argument " << index << " a string";
                 throw JSException(stream.str());
             }
             break;
         case ZCLTypeDataType::ZCLTypeArray:
             if (!arg->IsUint32Array() && !arg->IsUint32Array()) {
                 if (!arg->IsArray()) {
                     stringstream stream;
                     stream << EXECUTE_CMD_BY_ID << " needs as argument " << index << " an array";
                     throw JSException(stream.str());
                 }
             }
             break;
         default:
             stringstream stream;
             stream << EXECUTE_CMD_BY_ID << " needs as argument " << index << " a type "
                    << cmdParam->getZCLDataType() << " the it is not managed";
             throw JSException(stream.str());
     }
 }
Esempio n. 6
0
void JNIV8ClassInfo::v8JavaMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& args) {
    JNIEnv *env = JNIWrapper::getEnvironment();
    JNILocalFrame localFrame(env);

    HandleScope scope(args.GetIsolate());
    Isolate *isolate = args.GetIsolate();

    jobject jobj = nullptr;

    v8::Local<v8::External> ext;
    ext = args.Data().As<v8::External>();
    JNIV8ObjectJavaCallbackHolder* cb = static_cast<JNIV8ObjectJavaCallbackHolder*>(ext->Value());

    // we only check the "this" for non-static methods
    // otherwise "this" can be anything, we do not care..
    if(!cb->isStatic) {
        v8::Local<v8::Object> thisArg = args.This();
        v8::Local<v8::Value> internalField = thisArg->GetInternalField(0);
        // this is not really "safe".. but how could it be? another part of the program could store arbitrary stuff in internal fields
        ext = internalField.As<v8::External>();
        JNIV8Object *v8Object = reinterpret_cast<JNIV8Object *>(ext->Value());
        jobj = v8Object->getJObject();
    }

    // try to find a matching signature
    JNIV8ObjectJavaSignatureInfo *signature = nullptr;

    for (auto& sig : cb->signatures) {
        if (!sig.arguments) {
            if (!signature) {
                signature = &sig;
            }
        } else if (sig.arguments->size() == args.Length()) {
            signature = &sig;
            break;
        }
    }

    if(!signature) {
        isolate->ThrowException(v8::Exception::TypeError(String::NewFromUtf8(isolate, ("invalid number of arguments (" + std::to_string(args.Length()) + ") supplied to " + cb->methodName).c_str())));
        return;
    }

    jvalue *jargs;
    jobject obj;
    size_t numJArgs;

    if(!signature->arguments) {
        // generic case: an array of objects!
        // nothing to validate here, this always works
        numJArgs = 1;
        jargs = (jvalue*)malloc(sizeof(jvalue)*numJArgs);
        memset(jargs, 0, sizeof(jvalue)*numJArgs);
        jobjectArray jArray = env->NewObjectArray(args.Length(), _jniObject.clazz, nullptr);
        for (int idx = 0, n = args.Length(); idx < n; idx++) {
            obj = JNIV8Marshalling::v8value2jobject(args[idx]);
            env->SetObjectArrayElement(jArray, idx, obj);
            env->DeleteLocalRef(obj);
        }
        jargs[0].l = jArray;
    } else {
        // specific case
        // arguments might have to be of a certain type, so we need to validate!
        numJArgs = (size_t)args.Length();
        if(numJArgs) {
            jargs = (jvalue *) malloc(sizeof(jvalue) * numJArgs);
            memset(jargs, 0, sizeof(jvalue) * numJArgs);

            for(int idx = 0, n = args.Length(); idx < n; idx++) {
                JNIV8JavaValue &arg = (*signature->arguments)[idx];
                v8::Local<v8::Value> value = args[idx];

                JNIV8MarshallingError res = JNIV8Marshalling::convertV8ValueToJavaValue(env, value, arg, &(jargs[idx]));
                if(res != JNIV8MarshallingError::kOk) {
                    // conversion failed => simply clean up & throw an exception
                    free(jargs);
                    switch(res) {
                        default:
                        case JNIV8MarshallingError::kWrongType:
                            ThrowV8TypeError("wrong type for argument #" + std::to_string(idx) + " of '" + cb->methodName + "'");
                            break;
                        case JNIV8MarshallingError::kUndefined:
                            ThrowV8TypeError("argument #" + std::to_string(idx) + " of '" + cb->methodName + "' does not accept undefined");
                            break;
                        case JNIV8MarshallingError::kNotNullable:
                            ThrowV8TypeError("argument #" + std::to_string(idx) + " of '" + cb->methodName + "' is not nullable");
                            break;
                        case JNIV8MarshallingError::kNoNaN:
                            ThrowV8TypeError("argument #" + std::to_string(idx) + " of '" + cb->methodName + "' must not be NaN");
                            break;
                        case JNIV8MarshallingError::kVoidNotNull:
                            ThrowV8TypeError("argument #" + std::to_string(idx) + " of '" + cb->methodName + "' must be null or undefined");
                            break;
                        case JNIV8MarshallingError::kOutOfRange:
                            ThrowV8RangeError("value '"+
                                              JNIV8Marshalling::v8string2string(value->ToString(isolate))+"' is out of range for argument #" + std::to_string(idx) + " of '" + cb->methodName + "'");
                            break;
                    }
                    return;
                }
            }
        } else {
            jargs = nullptr;
        }
    }

    v8::Local<v8::Value> result;

    result = JNIV8Marshalling::callJavaMethod(env, cb->returnType, cb->javaClass, signature->javaMethodId, jobj, jargs);

    if(jargs) {
        free(jargs);
    }

    // java method could have thrown an exception; if so forward it to v8
    if(env->ExceptionCheck()) {
        BGJSV8Engine::GetInstance(isolate)->forwardJNIExceptionToV8();
        return;
    }

    args.GetReturnValue().Set(result);
}
Esempio n. 7
0
static void JS_JsonCursor(v8::FunctionCallbackInfo<v8::Value> const& args) {
  TRI_V8_TRY_CATCH_BEGIN(isolate);
  v8::HandleScope scope(isolate);

  TRI_vocbase_t* vocbase = GetContextVocBase(isolate);

  if (vocbase == nullptr) {
    TRI_V8_THROW_EXCEPTION(TRI_ERROR_ARANGO_DATABASE_NOT_FOUND);
  }

  if (args.Length() != 1) {
    TRI_V8_THROW_EXCEPTION_USAGE("JSON_CURSOR(<id>)");
  }

  std::string const id = TRI_ObjectToString(args[0]);
  auto cursorId = static_cast<arangodb::CursorId>(
      arangodb::basics::StringUtils::uint64(id));

  // find the cursor
  auto cursors = vocbase->cursorRepository();
  TRI_ASSERT(cursors != nullptr);

  bool busy;
  auto cursor = cursors->find(cursorId, Cursor::CURSOR_VPACK, busy);

  if (cursor == nullptr) {
    if (busy) {
      TRI_V8_THROW_EXCEPTION(TRI_ERROR_CURSOR_BUSY);
    }

    TRI_V8_THROW_EXCEPTION(TRI_ERROR_CURSOR_NOT_FOUND);
  }

  try {
    auto result = v8::Object::New(isolate);

    // build documents
    auto docs = v8::Array::New(isolate);
    size_t const n = cursor->batchSize();

    for (size_t i = 0; i < n; ++i) {
      if (!cursor->hasNext()) {
        break;
      }

      auto row = cursor->next();

      if (row.isNone()) {
        TRI_V8_THROW_EXCEPTION(TRI_ERROR_OUT_OF_MEMORY);
      }

      docs->Set(static_cast<uint32_t>(i), TRI_VPackToV8(isolate, row));
    }

    result->ForceSet(TRI_V8_ASCII_STRING("result"), docs);

    bool hasCount = cursor->hasCount();
    size_t count = cursor->count();
    bool hasNext = cursor->hasNext();
    VPackSlice const extra = cursor->extra();

    result->ForceSet(TRI_V8_ASCII_STRING("hasMore"),
                     v8::Boolean::New(isolate, hasNext));

    if (hasNext) {
      result->ForceSet(TRI_V8_ASCII_STRING("id"),
                       V8TickId(isolate, cursor->id()));
    }

    if (hasCount) {
      result->ForceSet(TRI_V8_ASCII_STRING("count"),
                       v8::Number::New(isolate, static_cast<double>(count)));
    }
    if (!extra.isNone()) {
      result->ForceSet(TRI_V8_ASCII_STRING("extra"),
                       TRI_VPackToV8(isolate, extra));
    }

    cursors->release(cursor);

    TRI_V8_RETURN(result);
  } catch (...) {
    cursors->release(cursor);
    TRI_V8_THROW_EXCEPTION_MEMORY();
  }
  TRI_V8_TRY_CATCH_END
}
void
JavascriptEngineV8::constructGeoExtentCallback(const v8::FunctionCallbackInfo<v8::Value> &info)
{
  if (!info.IsConstructCall())
  {
    v8::ThrowException(v8::String::New("Cannot call constructor as function"));
    return;
  }

  v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
  osgEarth::GeoExtent* extent = 0L;// = new osgEarth::GeoExtent(

  //if (info.Length() == 0)
  //  extent = new osgEarth::GeoExtent();
  //else
  if (info.Length() == 1 && info[0]->IsObject())
  {
    v8::Local<v8::Object> obj( v8::Local<v8::Object>::Cast(info[0]) );

    //if (V8Util::CheckObjectType(obj, JSSpatialReference::GetObjectType()))
    //{
    //  osgEarth::SpatialReference* srs = V8Util::UnwrapObject<osgEarth::SpatialReference>(obj);
    //  extent = new osgEarth::GeoExtent(srs);
    //}
    //else
    if (V8Util::CheckObjectType(obj, JSGeoExtent::GetObjectType()))
    {
      osgEarth::GeoExtent* rhs = V8Util::UnwrapObject<osgEarth::GeoExtent>(obj);
      extent = new osgEarth::GeoExtent(*rhs);
    }
  }
  else if (info.Length() == 2 && info[0]->IsObject() && info[1]->IsObject())
  {
    v8::Local<v8::Object> obj0( v8::Local<v8::Object>::Cast(info[0]) );
    v8::Local<v8::Object> obj1( v8::Local<v8::Object>::Cast(info[1]) );

    if (V8Util::CheckObjectType(obj0, JSSpatialReference::GetObjectType()) && V8Util::CheckObjectType(obj1, JSBounds::GetObjectType()))
    {
      osgEarth::SpatialReference* srs = V8Util::UnwrapObject<osgEarth::SpatialReference>(obj0);
      osgEarth::Bounds* bounds = V8Util::UnwrapObject<osgEarth::Bounds>(obj1);
      extent = new osgEarth::GeoExtent(srs, *bounds);
    }
  }
  else if (info.Length() == 5 && info[0]->IsObject())
  {
    v8::Local<v8::Object> obj( v8::Local<v8::Object>::Cast(info[0]) );

    if (V8Util::CheckObjectType(obj, JSSpatialReference::GetObjectType()))
    {
      osgEarth::SpatialReference* srs = V8Util::UnwrapObject<osgEarth::SpatialReference>(obj);
      extent = new osgEarth::GeoExtent(srs, info[1]->NumberValue(), info[2]->NumberValue(), info[3]->NumberValue(), info[4]->NumberValue());
    }
  }

  if (!extent)
  {
    v8::ThrowException(v8::String::New("Unsupported arguments in constructor call"));
    return;
  }

  info.GetReturnValue().Set(JSGeoExtent::WrapGeoExtent(v8::Isolate::GetCurrent(), extent, true));
}
Esempio n. 9
0
result_t _format(const char* sql, const v8::FunctionCallbackInfo<v8::Value>& args,
    bool mysql, bool mssql, exlib::string& retVal)
{
    exlib::string str;
    const char *p, *p1;
    int32_t cnt = 1;

    while (*sql) {
        p = p1 = sql;
        while (*p1 && *p1 != '?')
            p1++;

        str.append(p, p1 - p);

        if (*p1) {
            p1++;

            if (cnt < args.Length()) {
                v8::Local<v8::Value> v = args[cnt];

                if (v->IsFunction())
                    return CHECK_ERROR(CALL_E_INVALIDARG);

                obj_ptr<Buffer_base> bin = Buffer_base::getInstance(v);

                if (bin) {
                    exlib::string s;

                    if (mssql) {
                        str.append("0x", 2);
                        bin->hex(s);
                        str.append(s);
                    } else {
                        str.append("x\'", 2);
                        bin->hex(s);
                        str.append(s);
                        str += '\'';
                    }
                } else if (v->IsArray()) {
                    v8::Local<v8::Array> a = v8::Local<v8::Array>::Cast(v);
                    int32_t len = a->Length();
                    int32_t i;

                    str += '(';

                    for (i = 0; i < len; i++) {
                        v8::Local<v8::Value> v1 = a->Get(i);

                        if (i > 0)
                            str += ',';
                        _appendValue(str, v1, mysql);
                    }

                    str += ')';
                } else
                    _appendValue(str, v, mysql);
            } else
                str.append("\'\'", 2);

            cnt++;
        }

        sql = p1;
    }

    retVal = str;
    return 0;
}
Esempio n. 10
0
void Module::RequireCallback(const v8::FunctionCallbackInfo<v8::Value>& args)
{
	try
	{
		auto isolate = Isolate::GetCurrent();

		if (args.Length() != 2)
		{
			throw NativeScriptException(string("require should be called with two parameters"));
		}
		if (!args[0]->IsString())
		{
			throw NativeScriptException(string("require's first parameter should be string"));
		}
		if (!args[1]->IsString())
		{
			throw NativeScriptException(string("require's second parameter should be string"));
		}

		string moduleName = ConvertToString(args[0].As<String>());
		string callingModuleDirName = ConvertToString(args[1].As<String>());

		JEnv env;
		JniLocalRef jsModulename(env.NewStringUTF(moduleName.c_str()));
		JniLocalRef jsCallingModuleDirName(env.NewStringUTF(callingModuleDirName.c_str()));
		JniLocalRef jsModulePath(env.CallStaticObjectMethod(MODULE_CLASS, RESOLVE_PATH_METHOD_ID, (jstring) jsModulename, (jstring) jsCallingModuleDirName));

		// cache the required modules by full path, not name only, since there might be some collisions with relative paths and names
		string modulePath = ArgConverter::jstringToString((jstring) jsModulePath);

		auto isData = false;

		auto moduleObj = Load(modulePath, isData);

		if (isData)
		{
			assert(!moduleObj.IsEmpty());

			args.GetReturnValue().Set(moduleObj);
		}
		else
		{
			auto exportsObj = moduleObj->Get(ConvertToV8String("exports"));

			assert(!exportsObj.IsEmpty());

			args.GetReturnValue().Set(exportsObj);
		}
	}
	catch (NativeScriptException& e)
	{
		e.ReThrowToV8();
	}
	catch (std::exception e) {
				stringstream ss;
		ss << "Error: c++ exception: " << e.what() << endl;
		NativeScriptException nsEx(ss.str());
		nsEx.ReThrowToV8();
	}
	catch (...) {
		NativeScriptException nsEx(std::string("Error: c++ exception!"));
		nsEx.ReThrowToV8();
	}
}
Esempio n. 11
0
void V8Element::animateMethodCustom(const v8::FunctionCallbackInfo<v8::Value>& info)
{
    v8::Isolate* isolate = info.GetIsolate();
    ExceptionState exceptionState(ExceptionState::ExecutionContext, "animate", "Element", info.Holder(), isolate);
    // AnimationPlayer animate(
    //     (AnimationEffect or sequence<Dictionary>)? effect,
    //     optional (double or Dictionary) timing);
    switch (info.Length()) {
    case 1:
        // null resolved as to AnimationEffect, as if the member were nullable:
        // (AnimationEffect? or sequence<Dictionary>)
        // instead of the *union* being nullable:
        // (AnimationEffect or sequence<Dictionary>)?
        // AnimationPlayer animate(AnimationEffect? effect);
        if (info[0]->IsNull()) {
            animate1Method(info);
            return;
        }
        // AnimationPlayer animate(AnimationEffect effect);
        if (V8AnimationEffect::hasInstance(info[0], isolate)) {
            animate1Method(info);
            return;
        }
        // [MeasureAs=ElementAnimateKeyframeListEffectNoTiming]
        // AnimationPlayer animate(sequence<Dictionary> effect);
        if (info[0]->IsArray()) {
            UseCounter::count(callingExecutionContext(isolate), UseCounter::ElementAnimateKeyframeListEffectNoTiming);
            animate2Method(info);
            return;
        }
        break;
    case 2:
        // As above, null resolved to AnimationEffect
        // AnimationPlayer animate(AnimationEffect? effect, Dictionary timing);
        if (info[0]->IsNull() && info[1]->IsObject()) {
            animate4Method(info);
            return;
        }
        // AnimationPlayer animate(AnimationEffect? effect, double timing);
        if (info[0]->IsNull()) {
            animate3Method(info);
            return;
        }
        // AnimationPlayer animate(AnimationEffect effect, Dictionary timing);
        if (V8AnimationEffect::hasInstance(info[0], isolate)
                && info[1]->IsObject()) {
            animate4Method(info);
            return;
        }
        // AnimationPlayer animate(AnimationEffect effect, double timing);
        if (V8AnimationEffect::hasInstance(info[0], isolate)) {
            animate3Method(info);
            return;
        }
        // [MeasureAs=ElementAnimateKeyframeListEffectObjectTiming]
        // AnimationPlayer animate(sequence<Dictionary> effect, Dictionary timing);
        if (info[0]->IsArray() && info[1]->IsObject()) {
            UseCounter::count(callingExecutionContext(isolate), UseCounter::ElementAnimateKeyframeListEffectObjectTiming);
            animate6Method(info);
            return;
        }
        // [MeasureAs=ElementAnimateKeyframeListEffectDoubleTiming]
        // AnimationPlayer animate(sequence<Dictionary> effect, double timing);
        if (info[0]->IsArray()) {
            UseCounter::count(callingExecutionContext(isolate), UseCounter::ElementAnimateKeyframeListEffectDoubleTiming);
            animate5Method(info);
            return;
        }
        break;
    default:
        throwArityTypeError(exceptionState, "[1]", info.Length());
        return;
        break;
    }
    exceptionState.throwTypeError("No function was found that matched the signature provided.");
    exceptionState.throwIfNeeded();
}
void V8InjectedScriptHost::isTypedArrayCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
    if (info.Length() < 1)
        return;
    v8SetReturnValue(info, info[0]->IsTypedArray());
}
Esempio n. 13
0
static void v8_arg_count(v8::FunctionCallbackInfo<v8::Value> const& args)
{
	args.GetReturnValue().Set(args.Length());
}
Esempio n. 14
0
void Proxy::proxyOnPropertiesChanged(const v8::FunctionCallbackInfo<v8::Value>& args)
{
    Isolate* isolate = args.GetIsolate();
    HandleScope scope(isolate);
    Local<Object> jsProxy = args.Holder();

    if (args.Length() < 1 || !(args[0]->IsArray())) {
        JSException::Error(isolate, "Proxy.propertiesChanged requires a list of lists of property name, the old value, and the new value");
        return;
    }

    JNIEnv *env = JNIScope::getEnv();
    if (!env) {
        JSException::GetJNIEnvironmentError(isolate);
        return;
    }

    Proxy *proxy = unwrap(jsProxy);
    if (!proxy) {
        JSException::Error(isolate, "Failed to unwrap Proxy instance");
        return;
    }

    Local<Array> changes = args[0].As<Array>();
    uint32_t length = changes->Length();
    jobjectArray jChanges = env->NewObjectArray(length, JNIUtil::objectClass, NULL);

    for (uint32_t i = 0; i < length; ++i) {
        Local<Array> change = changes->Get(i).As<Array>();
        Local<String> name = change->Get(INDEX_NAME)->ToString(isolate);
        Local<Value> oldValue = change->Get(INDEX_OLD_VALUE);
        Local<Value> value = change->Get(INDEX_VALUE);

        jobjectArray jChange = env->NewObjectArray(3, JNIUtil::objectClass, NULL);

        jstring jName = TypeConverter::jsStringToJavaString(env, name);
        env->SetObjectArrayElement(jChange, INDEX_NAME, jName);
        env->DeleteLocalRef(jName);

        bool isNew;
        jobject jOldValue = TypeConverter::jsValueToJavaObject(isolate, env, oldValue, &isNew);
        env->SetObjectArrayElement(jChange, INDEX_OLD_VALUE, jOldValue);
        if (isNew) {
            env->DeleteLocalRef(jOldValue);
        }

        jobject jValue = TypeConverter::jsValueToJavaObject(isolate, env, value, &isNew);
        env->SetObjectArrayElement(jChange, INDEX_VALUE, jValue);
        if (isNew) {
            env->DeleteLocalRef(jValue);
        }

        env->SetObjectArrayElement(jChanges, i, jChange);
        env->DeleteLocalRef(jChange);
    }

    jobject javaProxy = proxy->getJavaObject();
    env->CallVoidMethod(javaProxy, JNIUtil::krollProxyOnPropertiesChangedMethod, jChanges);
    env->DeleteLocalRef(jChanges);

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

    return;
}
Esempio n. 15
0
static void JS_CreateCursor(v8::FunctionCallbackInfo<v8::Value> const& args) {
  TRI_V8_TRY_CATCH_BEGIN(isolate);
  v8::HandleScope scope(isolate);

  TRI_vocbase_t* vocbase = GetContextVocBase(isolate);

  if (vocbase == nullptr) {
    TRI_V8_THROW_EXCEPTION(TRI_ERROR_ARANGO_DATABASE_NOT_FOUND);
  }

  if (args.Length() < 1) {
    TRI_V8_THROW_EXCEPTION_USAGE("CREATE_CURSOR(<data>, <batchSize>, <ttl>)");
  }

  if (!args[0]->IsArray()) {
    TRI_V8_THROW_TYPE_ERROR("<data> must be an array");
  }

  // extract objects
  v8::Handle<v8::Array> array = v8::Handle<v8::Array>::Cast(args[0]);
  auto builder = std::make_shared<VPackBuilder>();
  int res = TRI_V8ToVPack(isolate, *builder, array, false);

  if (res != TRI_ERROR_NO_ERROR) {
    TRI_V8_THROW_TYPE_ERROR("cannot convert <array> to JSON");
  }

  // maximum number of results to return at once
  uint32_t batchSize = 1000;

  if (args.Length() >= 2) {
    int64_t maxValue = TRI_ObjectToInt64(args[1]);

    if (maxValue > 0 && maxValue < (int64_t)UINT32_MAX) {
      batchSize = static_cast<uint32_t>(maxValue);
    }
  }

  double ttl = 0.0;
  if (args.Length() >= 3) {
    ttl = TRI_ObjectToDouble(args[2]);
  }

  if (ttl <= 0.0) {
    ttl = 30.0;  // default ttl
  }

  // create a cursor
  auto cursors = vocbase->cursorRepository();

  arangodb::aql::QueryResult result(TRI_ERROR_NO_ERROR);
  result.result = builder;
  result.cached = false;
  result.context = std::make_shared<arangodb::StandaloneTransactionContext>(vocbase);

  TRI_ASSERT(builder.get() != nullptr);

  try {
    arangodb::Cursor* cursor = cursors->createFromQueryResult(
        std::move(result), static_cast<size_t>(batchSize), nullptr, ttl, true);

    TRI_ASSERT(cursor != nullptr);
    auto id = cursor->id(); // need to fetch id before release() as release() will delete the cursor
    cursors->release(cursor);

    auto result = V8TickId(isolate, id);
    TRI_V8_RETURN(result);
  } catch (...) {
    TRI_V8_THROW_EXCEPTION_MEMORY();
  }
  TRI_V8_TRY_CATCH_END
}
Esempio n. 16
0
void SessionWrapper::execute(const v8::FunctionCallbackInfo<v8::Value>& args)
{
	SessionHolder* pSessionHolder = Wrapper::unwrapNative<SessionHolder>(args);
	Poco::Data::Session& session = pSessionHolder->session();
	if (args.Length() > 0)
	{
		RecordSetHolder* pRecordSetHolder = new RecordSetHolder;
		pRecordSetHolder->reserveBindings(static_cast<std::size_t>(args.Length() - 1));
		try
		{
			Poco::Data::Statement statement = (session << toString(args[0]));
			for (int i = 1; i < args.Length(); i++)
			{
				if (args[i]->IsString())
				{
					statement , use(pRecordSetHolder->bindValue(toString(args[i])));
				}
				else if (args[i]->IsBoolean())
				{
					statement , use(pRecordSetHolder->bindValue(args[i]->BooleanValue()));
				}
				else if (args[i]->IsInt32())
				{
					statement , use(pRecordSetHolder->bindValue(args[i]->Int32Value()));
				}
				else if (args[i]->IsUint32())
				{
					statement , use(pRecordSetHolder->bindValue(args[i]->Uint32Value()));
				}
				else if (args[i]->IsNumber())
				{
					statement , use(pRecordSetHolder->bindValue(args[i]->NumberValue()));
				}
#if POCO_VERSION > 0x01050000
				else if (args[i]->IsDate())
				{
					v8::Local<v8::Date> jsDate = v8::Local<v8::Date>::Cast(args[i]);
					double millis = jsDate->ValueOf();
					Poco::Timestamp ts(static_cast<Poco::Timestamp::TimeVal>(millis*1000));
					Poco::DateTime dateTime(ts);
					statement , use(pRecordSetHolder->bindValue(dateTime));
				}
#endif
				else
				{
					throw Poco::InvalidArgumentException(Poco::format("cannot convert argument %d to native type", i));
				}
			}
			if (pSessionHolder->getPageSize() > 0)
			{
				statement , limit(pSessionHolder->getPageSize());
			}
			statement.execute();
			pRecordSetHolder->assignStatement(statement);
			pRecordSetHolder->updateRecordSet();
			RecordSetWrapper wrapper;
			v8::Persistent<v8::Object>& recordSetObject(wrapper.wrapNativePersistent(args.GetIsolate(), pRecordSetHolder));
			args.GetReturnValue().Set(recordSetObject);
		}
		catch (Poco::Exception& exc)
		{
			delete pRecordSetHolder;
			returnException(args, exc);
		}
	}
}
Esempio n. 17
0
result_t util_base::format(const char *fmt, const v8::FunctionCallbackInfo<v8::Value> &args,
                           std::string &retVal)
{
    const char *s1;
    char ch;
    int argc = args.Length();
    int idx = 1;

    if (fmt == NULL)
    {
        idx = 0;
        fmt = "";
    }
    else if (argc == 1)
    {
        retVal = fmt;
        return 0;
    }

    const char *s = fmt;

    while (1)
    {
        s1 = s;
        while ((ch = *s++) && (ch != '%'));

        retVal.append(s1, s - s1 - 1);

        if (ch == '%')
        {
            switch (ch = *s++)
            {
            case 's':
                if (idx < argc)
                {
                    v8::String::Utf8Value s(args[idx++]);
                    if (*s)
                        retVal.append(*s);
                }
                else
                    retVal.append("%s", 2);
                break;
            case 'd':
                if (idx < argc)
                {
                    v8::String::Utf8Value s(args[idx++]->ToNumber());
                    if (*s)
                        retVal.append(*s);
                }
                else
                    retVal.append("%d", 2);
                break;
            case 'j':
                if (idx < argc)
                {
                    std::string s;
                    s = json_format(args[idx++]);
                    retVal.append(s);
                }
                else
                    retVal.append("%j", 2);
                break;
            default:
                retVal.append("%", 1);
            case '%':
                retVal.append(&ch, 1);
                break;
            }
        }
        else
            break;
    }

    while (idx < argc)
    {
        if (!retVal.empty())
            retVal.append(" ", 1);

        bool v;

        isString(args[idx], v);

        if (v)
        {
            v8::String::Utf8Value s(args[idx++]);
            retVal.append(*s);
        }
        else
        {
            std::string s;
            s = json_format(args[idx++]);

            retVal.append(s);
        }
    }

    return 0;
}