Esempio n. 1
0
Handle<Value> find_or_create_object_chain(Tomato *tomato, VALUE chain)
{
  Handle<Value> value = tomato->context()->Global();
  if (value->IsObject())
  {
    Handle<Object> object = Handle<Object>::Cast(value);
    if (!NIL_P(chain))
    {
      int len = RARRAY_LEN(chain);
      VALUE *items = RARRAY_PTR(chain);
      
      for (int i = 0; i < len; i++)
      {
        Handle<String> object_name = String::New(StringValuePtr(items[i]));
        value = object->Get(object_name);
        if (value->IsObject())
        {
          object = Handle<Object>::Cast(value);  
        }
        else
        {
          Handle<Object> new_object = Object::New();
          object->Set(object_name, new_object);
          object = new_object;
        }
      }
    }
    return object;
  }
  return value;
}
Esempio n. 2
0
std::map<QString, double> ScriptMatch::getFeatures(const ConstOsmMapPtr& map) const
{
  Context::Scope context_scope(_script->getContext());
  HandleScope handleScope;

  // removing these two lines causes a crash when checking for conflicts. WTF?
  Handle<Object> global = _script->getContext()->Global();
  global->Get(String::NewSymbol("plugin"));

  std::map<QString, double> result;
  Handle<Value> v = _callGetMatchFeatureDetails(map);

  if (v.IsEmpty() || v->IsObject() == false)
  {
    throw IllegalArgumentException(
      "Expected getMatchFeatureDetails to return an associative array.");
  }

  QVariantMap vm = toCpp<QVariantMap>(v);
  for (QVariantMap::const_iterator it = vm.begin(); it != vm.end(); ++it)
  {
    if (it.value().isNull() == false)
    {
      double d = it.value().toDouble();
      result[it.key()] = d;
      if (isnan(result[it.key()]))
      {
        LOG_WARN("found NaN feature value for: " << it.key());
      }
    }
  }

  return result;
}
/* DBOperationHelper takes an array of HelperSpecs.
   arg0: Length of Array
   arg1: Array of HelperSpecs
   arg2: DBTransactionContext *
   arg3: Old DBOperationSet wrapper (for recycling)

   Returns: DBOperationSet
*/
Handle<Value> DBOperationHelper(const Arguments &args) {
  HandleScope scope;

  int length = args[0]->Int32Value();
  const Local<Object> array = args[1]->ToObject();
  DBTransactionContext *txc = unwrapPointer<DBTransactionContext *>(args[2]->ToObject());
  Handle<Value> oldWrapper = args[3];

  DBOperationSet * pendingOps = new DBOperationSet(txc, length);

  for(int i = 0 ; i < length ; i++) {
    Handle<Object> spec = array->Get(i)->ToObject();

    int opcode  = spec->Get(HELPER_OPCODE)->Int32Value();
    bool is_vo  = spec->Get(HELPER_IS_VO)->ToBoolean()->Value();
    bool op_ok  = spec->Get(HELPER_IS_VALID)->ToBoolean()->Value();

    KeyOperation * op = pendingOps->getKeyOperation(i);
    
    if(op_ok) {
      op->opcode = opcode;
      if(is_vo) DBOperationHelper_VO(spec, *op);
      else      DBOperationHelper_NonVO(spec, *op);
    }
  }
  
  if(oldWrapper->IsObject()) {
    return DBOperationSet_Recycle(oldWrapper->ToObject(), pendingOps);
  } else {
    return DBOperationSet_Wrapper(pendingOps);
  }
}
void printV8Value(Handle<Value> value, bool force=false)
{
    Logging::Level level = force ? Logging::ERROR : Logging::INFO;

    if (!Logging::shouldShow(level)) return;

    HandleScope handleScope;

    if (value.IsEmpty())
        Logging::log(level, "Empty handle\r\n");
    else if (value->IsInt32())
        Logging::log(level, "INT: %d\r\n", value->IntegerValue());
    else if (value->IsNull())
        Logging::log(level, "NULL (null)\r\n");
    else if (value->IsUndefined())
        Logging::log(level, "VOID (undefined)\r\n");
    else if (value->IsBoolean())
        Logging::log(level, "BOOLEAN: %d\r\n", value->BooleanValue());
    else if (value->IsNumber())
        Logging::log(level, "NUMBER: %f\r\n", value->NumberValue());
    else if (value->IsString())
        Logging::log(level, "STRING: ?\r\n");
    else if (value->IsObject())
        Logging::log(level, "OBJECT (object)\r\n");
    else
        Logging::log(level, "Uncertain V8 value\n");
}
Esempio n. 5
0
/**
 * Gets an object parameter from the json config as an object
 */
Handle<Object> V8Config::getObjectParameter(Handle<Object> element,const char* key){

	Handle<Value> handleValue = getKeyHandle(element,key);
	assert(handleValue->IsObject());
	return handleValue->ToObject();

}
Esempio n. 6
0
    int V8Scope::type( const char *field ){
        V8_SIMPLE_HEADER
        Handle<Value> v = get( field );
        if ( v->IsNull() )
            return jstNULL;
        if ( v->IsUndefined() )
            return Undefined;
        if ( v->IsString() )
            return String;
        if ( v->IsFunction() )
            return Code;
        if ( v->IsArray() )
            return Array;
        if ( v->IsBoolean() )
            return Bool;
        if ( v->IsInt32() )
            return NumberInt;
        if ( v->IsNumber() )
            return NumberDouble;
        if ( v->IsExternal() ){
            uassert( 10230 ,  "can't handle external yet" , 0 );
            return -1;
        }
        if ( v->IsDate() )
            return Date;
        if ( v->IsObject() )
            return Object;

        throw UserException( 12509, (string)"don't know what this is: " + field );
    }
Esempio n. 7
0
/* DBOperationHelper takes an array of HelperSpecs.
   arg0: Length of Array
   arg1: Array of HelperSpecs
   arg2: TransactionImpl *
   arg3: Old BatchImpl wrapper (for recycling)

   Returns: BatchImpl
*/
void DBOperationHelper(const Arguments &args) {
  EscapableHandleScope scope(args.GetIsolate());

  int length = args[0]->Int32Value();
  const Local<Object> array = args[1]->ToObject();
  TransactionImpl *txc = unwrapPointer<TransactionImpl *>(args[2]->ToObject());
  Handle<Value> oldWrapper = args[3];

  BatchImpl * pendingOps = new BatchImpl(txc, length);

  for(int i = 0 ; i < length ; i++) {
    Handle<Object> spec = array->Get(i)->ToObject();

    int opcode  = spec->Get(HELPER_OPCODE)->Int32Value();
    bool is_vo  = spec->Get(HELPER_IS_VO)->ToBoolean()->Value();
    bool op_ok  = spec->Get(HELPER_IS_VALID)->ToBoolean()->Value();

    KeyOperation * op = pendingOps->getKeyOperation(i);
    
    if(op_ok) {
      op->opcode = opcode;
      if(is_vo) DBOperationHelper_VO(spec, *op);
      else      DBOperationHelper_NonVO(spec, *op);
    }
  }
  
  if(oldWrapper->IsObject()) {
    args.GetReturnValue().Set(BatchImpl_Recycle(oldWrapper->ToObject(), pendingOps));
  } else {
    args.GetReturnValue().Set(BatchImpl_Wrapper(pendingOps));
  }
}
Esempio n. 8
0
 BSONObj V8Scope::getObject( const char * field ){
     Handle<Value> v = get( field );
     if ( v->IsNull() || v->IsUndefined() )
         return BSONObj();
     uassert( "not an object" , v->IsObject() );
     return v8ToMongo( v->ToObject() );
 }
Esempio n. 9
0
	//*,{
	//	"type":"function",
	//	"name":"setConfig(callback,[filename])",
	//	"text":"读取或设置配置文件,配置文件是一个 Json 格式的文本文件,可以是 utf-8 获取 ansi 编码。",
	//	"param":[
	//		{
	//			"type":"function",
	//			"name":"callback(cfg)",
	//			"text":"setConfig 函数如果成功,会触发这个回调函数,cfg 是一个对象,它的属性就是配置内容,对这个对象的任何更改最后都会作为 Json 格式保存到配置文件。"
	//		},
	//		{
	//			"type":"string",
	//			"name":"[filename]",
	//			"text":"配置文件名,缺省是和脚本同路径同名的一个后缀为“.json”的文本文件,如果指定了文件名,则读取和保存对应的文件。"
	//		}
	//	],
	//	"return":{
	//		"type":"boolean",
	//		"text":"如果成功打开了配置文件,函数返回 true,否则返回 undefined。"
	//	}
	//}//*
	Handle<Value> setConfig(const Arguments& args){
		HandleScope stack;
		while(true){
			if(args.Length()<1) break;
			if(!args[0]->IsFunction()) break;
			cs::String file;
			if(args.Length()>1)
				GetString(args[1],file);
			cs::Config cfg(file);
			cs::Json* json = cfg.Lock();
			if(!json) break;

			json->ToString(file,false);
			Handle<Object> glb = GetGlobal();
			Handle<Object> JSON = glb->Get(NEW_STR(JSON))->ToObject();
			Handle<Function> parse = Handle<Function>::Cast(JSON->Get(NEW_STR(parse)));
			Handle<Function> stringify = Handle<Function>::Cast(JSON->Get(NEW_STR(stringify)));
			Handle<Function> callback = Handle<Function>::Cast(args[0]);
			Handle<Value> argv[3];
			argv[0] = NEW_WSTR(file.Handle());
			Handle<Value> v = parse->Call(JSON,1,argv);
			if(v.IsEmpty()||!v->IsObject()) v = Object::New();
			argv[0] = v;
			CallFunc(glb,callback,1,argv);
			v = stringify->Call(JSON,1,argv);
			GetString(v,file);
			json->Parse(file);
			return True();
		}
		return Undefined();
	}
Esempio n. 10
0
int Conv::ToJavaMap(JNIEnv *jniEnv, Handle<Value> val, int componentType, jobject *jVal) {
  Local<Object> oVal;
  Local<Array> aPropertyNames;
  if(val.IsEmpty() || val->IsNull() || val->IsUndefined()) {
    *jVal = 0;
    return OK;
  }
  if(!val->IsObject())
    return ErrorType;
  
  oVal = val->ToObject();
  aPropertyNames = oVal->GetOwnPropertyNames();
  int len = aPropertyNames->Length();

  jobject ob = jniEnv->NewObject(mapClass, mapCtor);
  if(ob) {
    int res = OK;
    for(int i = 0; i < len; i++) {
      Local<String> key = Local<String>::Cast(aPropertyNames->Get(i));
      jstring jKey; jobject item;
      res = ToJavaString(jniEnv, key, &jKey);
      if(res != OK) break;
      res = ToJavaObject(jniEnv, oVal->Get(key), componentType, &item);
      if(res != OK) break;
      jniEnv->CallObjectMethod(ob, mapPut, jKey, item);
    }
  }
  if(ob) {
    *jVal = ob;
    return OK;
  }
  if(jniEnv->ExceptionCheck())
    jniEnv->ExceptionClear();
  return ErrorVM;
}
Esempio n. 11
0
	Handle<Value> parseString(const Arguments& args)
	{
		Handle<Value> parsed;

		{
#if 0
			HandleScope scope;
			Persistent<Context> m_context = Context::New();
			assert(!m_context.IsEmpty());
			m_context->Enter();
#endif

			Handle<Function> keyValueConverter = Local<Function>::Cast(args[1]);

			{
				JV8Parser parser(keyValueConverter);
				if (!parser.parse(args[0]->ToString(), JSchemaFragment("{}"))) {
					Local<String> errMsg = String::Concat(args[0]->ToString(), String::New("is not valid JSON"));
					ThrowException(Exception::SyntaxError(errMsg));
				}

				parsed = parser.parsed();
				assert(parsed->IsObject());
			}

#if 0
			m_context->Exit();
			m_context.Dispose();
#endif
		}

		return parsed;
	}
Esempio n. 12
0
int Conv::GetNaturalType(Handle<Object> val) {
  if(val.IsEmpty()) return TYPE_INVALID;
  if(val->IsDate()) return TYPE_DATE;
  if(val->IsFunction()) return TYPE_FUNCTION;
  if(val->IsArray()) return TYPE_ARRAY;
  if(val->IsObject()) return TYPE_OBJECT;
  return TYPE_INVALID;
}
Esempio n. 13
0
/*
   DESCRIPTION
     Processing each bind varible

   PARAMETERS:
     Handle value, eBaton struct
*/
void Connection::GetBindUnit (Handle<Value> val, Bind* bind,
                                       eBaton* executeBaton)
{
  HandleScope scope;
  unsigned int dir   = BIND_IN;

  if(val->IsObject() && !val->IsDate())
  {
    Local<Object> bind_unit = val->ToObject();
    NJS_GET_UINT_FROM_JSON   ( dir, executeBaton->error,
                               bind_unit, "dir", 1, exitGetBindUnit );
    NJS_GET_UINT_FROM_JSON   ( bind->type, executeBaton->error,
                               bind_unit, "type", 1, exitGetBindUnit );
    bind->maxSize = NJS_MAX_OUT_BIND_SIZE;
    NJS_GET_UINT_FROM_JSON   ( bind->maxSize, executeBaton->error,
                               bind_unit, "maxSize", 1, exitGetBindUnit );
    if(!bind->maxSize && dir != BIND_IN)
    {
      executeBaton->error = NJSMessages::getErrorMsg (
                                           errInvalidPropertyValueInParam,
                                           "maxSize", 2 );
      goto exitGetBindUnit;
    }

    Local<Value> element = bind_unit->Get(String::New("val"));
    switch(dir)
    {
      case BIND_IN    :
        bind->isOut  = false;
        Connection::GetInBindParams(element, bind, executeBaton, BIND_IN );
        if(!executeBaton->error.empty()) goto exitGetBindUnit;
        break;
      case BIND_INOUT :
        bind->isOut  = true;
        Connection::GetInBindParams(element, bind, executeBaton, BIND_INOUT);
        if(!executeBaton->error.empty()) goto exitGetBindUnit;
        break;
      case BIND_OUT   :
        bind->isOut  = true;
        bind->ind  = 0;
        Connection::GetOutBindParams(bind->type, bind, executeBaton);
        if(!executeBaton->error.empty()) goto exitGetBindUnit;
        break;
      default         :
        executeBaton->error = NJSMessages::getErrorMsg (errInvalidBindDirection);
        goto exitGetBindUnit;
        break;
    }
  }
  else
  {
    bind->isOut  = false;
    Connection::GetInBindParams(val, bind, executeBaton, BIND_IN);
    if(!executeBaton->error.empty()) goto exitGetBindUnit;
  }
  exitGetBindUnit:
  ;
}
Esempio n. 14
0
int Conv::ToJavaInterface(JNIEnv *jniEnv, Handle<Value> val, classId clsid, jobject *jVal) {
  if(val.IsEmpty() || !val->IsObject())
    return ErrorType;
  Handle<Object> oVal = Handle<Object>::Cast(val);
  int result = UnwrapInterface(jniEnv, oVal, clsid, jVal);
  if(result == ErrorNotfound)
    result = WrapV8Interface(jniEnv, oVal, clsid, jVal);
  return result;
}
void TiObject::setTiObjectToJsObject(Handle<Value> jsObject, TiObject* tiObj)
{
    if (!jsObject->IsObject())
    {
        return;
    }
    Handle<Object> obj = Handle<Object>::Cast(jsObject);
    obj->SetHiddenValue(String::New(HIDDEN_TI_OBJECT_PROPERTY), External::New(tiObj));
}
Esempio n. 16
0
	bool IsInheritTemplate(Handle<Value> val,uint tid){
		if(!val->IsObject()) return false;
		Local<Function> func = GetEnv()->GetTemplate(tid)->GetFunction();
		Local<Object> obj = val->ToObject()->GetPrototype()->ToObject();
		while(true){
			if(obj->GetPrototype()->IsNull()) return false;
			if(obj->GetConstructorName()==func->GetName()->ToString()) return true;
			obj = obj->GetPrototype()->ToObject();
		}
	}
Esempio n. 17
0
bool JSValueIsObjectOfClass(JSContextRef context, JSValueRef value, JSClassRef jsClass)
{
    API_PROLOGUE(context);
    Handle<Value> jsValue = toV8(value);
    if (!jsValue->IsObject())
        return false;
    Handle<Object> object = jsValue->ToObject();
    ClassWrapper* objClass = V8JSCAPIShim::getClassOfObject(object);
    return objClass == toImpl(jsClass);
}
Esempio n. 18
0
/*
 * Returns -1 if lump is not an FLump object
 * otherwise it returns the Pointer attribute in lump
 *
 */
extern "C" int get_pointer_lump(Handle<Value> lump) {
    int result = -1;
    if (lump->IsObject()) {
	Handle<Object> lump_as_object = Handle<Object>::Cast(lump);
	Handle<Value> pointer = lump_as_object->Get(String::New("pointer"));
	if (!pointer.IsEmpty()) {
	    result = pointer->Uint32Value();
	}	
    }
    return result;
}
Esempio n. 19
0
bool Projection::HasInstance(Handle<Value> val)
{
    NanScope();
    if (!val->IsObject()) return false;
    Handle<Object> obj = val.As<Object>();

    if (NanNew(constructor)->HasInstance(obj))
        return true;

    return false;
}
Esempio n. 20
0
void ScriptMatch::_calculateClassification(const ConstOsmMapPtr& map, Handle<Object> plugin)
{
  Context::Scope context_scope(_script->getContext());
  HandleScope handleScope;

  // removing these two lines causes a crash when checking for conflicts. WTF?
  Handle<Object> global = _script->getContext()->Global();
  global->Get(String::NewSymbol("plugin"));

  if (_plugin->Has(String::NewSymbol("isWholeGroup")))
  {
    Handle<Value> v = _script->call(_plugin, "isWholeGroup");
    _isWholeGroup = v->BooleanValue();
  }

  try
  {
    Handle<Value> v = _call(map, plugin);

    if (v.IsEmpty() || v->IsObject() == false)
    {
      throw IllegalArgumentException("Expected matchScore to return an associative array.");
    }

    QVariantMap vm = toCpp<QVariantMap>(v);
    // grab the match, miss, review results. If they aren't populated they get a value of 0.
    _p.setMatchP(_script->toNumber(v, "match", 0));
    _p.setMissP(_script->toNumber(v, "miss", 0));
    _p.setReviewP(_script->toNumber(v, "review", 0));

    _explainText = vm["explain"].toString();
    if (_explainText.isEmpty())
    {
      _explainText = _threshold->getTypeDetail(_p);
    }
    if (_threshold->getType(_p) == MatchType::Review)
    {
      if (_explainText.isEmpty())
      {
        throw IllegalArgumentException("If the match is a review an appropriate explanation must "
                                       "be provided (E.g. { 'review': 1, "
                                       "'explain': 'some reason' }.");
      }
    }
  }
  catch (NeedsReviewException& ex)
  {
    LOG_VAR(ex.getClassName());
    _p.setReview();
    _explainText = ex.getWhat();
  }

  _p.normalize();
}
Esempio n. 21
0
std::map<QString, double> ScriptMatch::getFeatures(const ConstOsmMapPtr& map) const
{
  Isolate* current = v8::Isolate::GetCurrent();
  HandleScope handleScope(current);
  Context::Scope context_scope(_script->getContext(current));

  // removing these two lines causes a crash when checking for conflicts. WTF?
  Handle<Object> global = _script->getContext(current)->Global();
  global->Get(String::NewFromUtf8(current, "plugin"));

  std::map<QString, double> result;
  LOG_TRACE("Calling getMatchFeatureDetails...");
  Handle<Value> v = _callGetMatchFeatureDetails(map);

  if (v.IsEmpty() || v->IsObject() == false)
  {
    throw IllegalArgumentException(
      "Expected getMatchFeatureDetails to return an associative array.");
  }

  QVariantMap vm = toCpp<QVariantMap>(v);
  long valCtr = 0;
  LOG_VART(vm.size());
  for (QVariantMap::const_iterator it = vm.begin(); it != vm.end(); ++it)
  {
    if (it.value().isNull() == false)
    {
      double d = it.value().toDouble();
      result[it.key()] = d;
      if (::qIsNaN(result[it.key()]))
      {
        if (logWarnCount < Log::getWarnMessageLimit())
        {
          LOG_WARN("found NaN feature value for: " << it.key());
        }
        else if (logWarnCount == Log::getWarnMessageLimit())
        {
          LOG_WARN(className() << ": " << Log::LOG_WARN_LIMIT_REACHED_MESSAGE);
        }
        logWarnCount++;
      }
    }
    valCtr++;
  }

  if (vm.size() > 0)
  {
    LOG_DEBUG("Processed " << vm.size() << " sample values.");
  }

  return result;
}
Esempio n. 22
0
	void SerializeField(google::protobuf::Message *message, const Reflection *r, const FieldDescriptor *field, Handle<Value> val) {
		const EnumValueDescriptor *enumValue = NULL;
		bool repeated = field->is_repeated();

		switch (field->cpp_type()) {
		case FieldDescriptor::CPPTYPE_INT32:
			SET_VALUE(Int32, val->Int32Value());
			break;
		case FieldDescriptor::CPPTYPE_INT64:
			SET_VALUE(Int64, val->NumberValue());
			break;
		case FieldDescriptor::CPPTYPE_UINT32:
			SET_VALUE(UInt32, val->Uint32Value());
			break;
		case FieldDescriptor::CPPTYPE_UINT64:
			SET_VALUE(UInt64, val->NumberValue());
			break;
		case FieldDescriptor::CPPTYPE_DOUBLE:
			SET_VALUE(Double, val->NumberValue());
			break;
		case FieldDescriptor::CPPTYPE_FLOAT:
			SET_VALUE(Float, val->NumberValue());
			break;
		case FieldDescriptor::CPPTYPE_BOOL:
			SET_VALUE(Bool, val->BooleanValue());
			break;
		case FieldDescriptor::CPPTYPE_ENUM:
			enumValue = val->IsNumber() ? 
				field->enum_type()->FindValueByNumber(val->Int32Value()) :
				field->enum_type()->FindValueByName(*String::AsciiValue(val));
			if (enumValue != NULL)
				SET_VALUE(Enum, enumValue);
			break;
		case FieldDescriptor::CPPTYPE_MESSAGE:
			if (val->IsObject()) {
				Type* type = protobuf->GetType(field->message_type());
				type->SerializePart(repeated ?
					r->AddMessage(message, field) :
					r->MutableMessage(message, field), val.As<Object>());
			}
			break;
		case FieldDescriptor::CPPTYPE_STRING:
			if (Buffer::HasInstance(val)) {
				Local<Object> buf = val->ToObject();
				SET_VALUE(String, std::string(Buffer::Data(buf), Buffer::Length(buf)));
			} else {
				String::Utf8Value utf8(val);
				SET_VALUE(String, std::string(*utf8, utf8.length()));
			}
			break;
		}
	}
Esempio n. 23
0
/* for geomtransform, we don't have the mapObj */
shapeObj *msV8TransformShape(shapeObj *shape, const char* filename)
{
  TryCatch try_catch;
  Isolate *isolate = Isolate::GetCurrent();
  V8Context *v8context = (V8Context*)isolate->GetData();

  HandleScope handle_scope(v8context->isolate);

  /* execution context */
  Local<Context> context = Local<Context>::New(v8context->isolate, v8context->context);
  Context::Scope context_scope(context);
  Handle<Object> global = context->Global();

  Shape* shape_ = new Shape(shape);
  shape_->setLayer(v8context->layer);
  shape_->disableMemoryHandler();
  Handle<Value> ext = External::New(shape_);
  global->Set(String::New("shape"),
              Shape::Constructor()->NewInstance(1, &ext));

  msV8ExecuteScript(filename);
  Handle<Value> value = global->Get(String::New("geomtransform"));
  if (value->IsUndefined()) {
    msDebug("msV8TransformShape: Function 'geomtransform' is missing.\n");
    return NULL;
  }
  Handle<Function> func = Handle<Function>::Cast(value);
  Handle<Value> result = func->Call(global, 0, 0);
  if (result.IsEmpty() && try_catch.HasCaught()) {
    msV8ReportException(&try_catch);
  }

  if (!result.IsEmpty() && result->IsObject()) {
    Handle<Object> obj = result->ToObject();
    if (obj->GetConstructorName()->Equals(String::New("shapeObj"))) {
      Shape* new_shape = ObjectWrap::Unwrap<Shape>(result->ToObject());
      if (shape == new_shape->get()) {
        shapeObj *new_shape_ = (shapeObj *)msSmallMalloc(sizeof(shapeObj));
        msInitShape(new_shape_);
        msCopyShape(shape, new_shape_);
        return new_shape_;
      }
      else {
        new_shape->disableMemoryHandler();
        return new_shape->get();
      }
    }
  }

  return NULL;
}
Esempio n. 24
0
int ArrayConv::ToJavaArray(JNIEnv *jniEnv, Handle<Value> val, int componentType, jobject *jVal) {
  if(val.IsEmpty()) return ErrorNotfound;
  if(!val->IsObject()) return ErrorType;

  ArrayType *arr;
  Handle<Object> oVal = Handle<Object>::Cast(val);
  int result = GetRefsForComponentType(jniEnv, componentType, &arr);
  if(result == OK) {
    result = conv->UnwrapObject(jniEnv, oVal, arr->sHiddenKey, jVal);
    if(result == ErrorNotfound)
      result = WrapV8Array(jniEnv, oVal, componentType, arr, jVal);
  }
  return result;
}
Esempio n. 25
0
Susi::Util::Any Susi::JS::Engine::convertFromJS(Handle<Value> jsVal){
	if(jsVal->IsArray()){
		Susi::Util::Any::Array result;
		auto obj = jsVal->ToObject();
		const Local<Array> props = obj->GetPropertyNames();
		const uint32_t length = props->Length();
		for (uint32_t i=0 ; i<length ; ++i){
			const Local<Value> key = props->Get(i);
			const Local<Value> value = obj->Get(key);
			result.push_back(Susi::JS::Engine::convertFromJS(value));
		}
		return result;
	}
	if(jsVal->IsObject()){
		Susi::Util::Any result = Susi::Util::Any::Object{};
		auto obj = jsVal->ToObject();
		const Local<Array> props = obj->GetPropertyNames();
		const uint32_t length = props->Length();
		for (uint32_t i=0 ; i<length ; ++i){
			const Local<Value> key = props->Get(i);
			const Local<Value> value = obj->Get(key);
			String::Utf8Value keyStr(key);
			result[std::string(*keyStr)] = Susi::JS::Engine::convertFromJS(value);
		}
		return result;
	}
	if(jsVal->IsString()){
		String::Utf8Value val(jsVal);
		Susi::Util::Any result{std::string(*val)};
		return result;
	}
	if(jsVal->IsNumber()){
		Susi::Util::Any result{jsVal->ToNumber()->Value()};
		return result;
	}
	if(jsVal->IsBoolean()){
		Susi::Util::Any result{jsVal->ToBoolean()->Value()};
		return result;
	}
	if(jsVal->IsNativeError()){
		String::Utf8Value val(jsVal);
		Susi::Util::Any result{std::string(*val)};
		return result;
	}
	if(jsVal->IsUndefined()){
		Susi::Util::Any result;
		return result;
	}
	return Susi::Util::Any{"type not known"};
}
void ContactsPersonProxy::_setEmail(void* userContext, Handle<Value> value)
{
    ContactsPersonProxy *obj = (ContactsPersonProxy*) userContext;

    if(!value->IsObject()) return;

	Handle<Object> emailObject = value->ToObject();
	Local<Array> emailProperties = emailObject->GetPropertyNames();
	for(int i = 0, len = emailProperties->Length(); i < len; i++)
	{
		Local<String> allEmailsKey = emailProperties->Get(i)->ToString();
		Local<Value> allEmailsValue = emailObject->Get(allEmailsKey);

		AttributeSubKind::Type subKind = AttributeSubKind::Other;

		QString allEmailsKeyString = titanium::V8ValueToQString(allEmailsKey).toLower();
		if(allEmailsKeyString == "work")
		{
			subKind = AttributeSubKind::Work;
		}
		else
		if(allEmailsKeyString == "personal")
		{
			subKind = AttributeSubKind::Personal;
		}
		else
		if(allEmailsKeyString == "home")
		{
			subKind = AttributeSubKind::Home;
		}

		if(!allEmailsValue->IsArray()) return;

		Local<Array> emails = Local<Array>::Cast(allEmailsValue);
		for(int i = 0, len = emails->Length(); i < len; i++)
		{
			Local<Value> emailValue = emails->Get(Number::New(i));
			if(emailValue->IsString() || emailValue->IsNumber())
			{
				 obj->setContactDetails(AttributeKind::Email, subKind, emailValue);
			}
			else
			{
				// Something goes here, throw an error?
			}
		}
	}
}
Esempio n. 27
0
int Conv::ToJavaString(JNIEnv *jniEnv, Handle<Value> val, jstring *jVal) {
  Handle<String> vString;
  Handle<Value> empty, vRes;
  jstring ob;
  char buf[64];
  switch(GetNaturalType(val)) {
    default: {
      if(val->IsObject()) {
        /* call ToString() in javascript */
        Handle<Object> oVal = val->ToObject();
        Handle<Value> vToString = oVal->Get(sToString);
        if(!vToString.IsEmpty() && vToString->IsFunction()) {
          Handle<Function> fToString = Handle<Function>::Cast(vToString);
          vRes = fToString->CallAsFunction(oVal, 0, &empty);
          if(!vRes.IsEmpty() && (vRes->IsString() || vRes->IsStringObject())) {
            return ToJavaString(jniEnv, vRes->ToString(), jVal);
          }
        }
      }
      return ErrorType;
    }
    case TYPE_UNDEFINED:
    case TYPE_NULL:
      *jVal = 0;
      return OK;
    case TYPE_BOOL:
      return ToJavaString(jniEnv, (val->BooleanValue() ? "true" : "false"), jVal);
    case TYPE_INT:
      sprintf(buf, "%d", val->Int32Value());
      return ToJavaString(jniEnv, buf, jVal);
    case TYPE_LONG:
      sprintf(buf, "%lld", val->IntegerValue());
      return ToJavaString(jniEnv, buf, jVal);
    case TYPE_DOUBLE:
      sprintf(buf, "%g", val->NumberValue());
      return ToJavaString(jniEnv, buf, jVal);
    case TYPE_STRING:
      return ToJavaString(jniEnv, val->ToString(), (jstring *)jVal);
  }
  if(ob) {
    *jVal = ob;
    return OK;
  }
  if(jniEnv->ExceptionCheck())
    jniEnv->ExceptionClear();
  return ErrorVM;
}
Esempio n. 28
0
Handle<Value> isValueObject(const Arguments &args) {
  HandleScope scope;
  bool answer = false;  
  Handle<Value> v = args[0];

  if(v->IsObject()) {
    Local<Object> o = v->ToObject();
    if(o->InternalFieldCount() == 2) {
      Envelope * n = (Envelope *) o->GetPointerFromInternalField(0);
      if(n == & nroEnvelope) {
        answer = true;
      }
    }
  }

  return scope.Close(Boolean::New(answer));
}
Esempio n. 29
0
void
Session::formOptions(std::string* str, Handle<Value> value)
{
    // Use the HandleScope of the calling function for speed.

    if (value->IsUndefined() || value->IsNull())
        return;

    assert(value->IsObject());

    std::stringstream ss;

    if (value->IsArray()) {
        // Format each array value into the options string "V[&V]"
        Local<Object> object = value->ToObject();
        for (std::size_t i = 0; i < Array::Cast(*object)->Length(); ++i) {
            Local<String> key = object->Get(i)->ToString();
            String::Utf8Value valv(key);
            if (valv.length()) {
                if (i > 0)
                    ss << "&";
                ss << *valv;
            }
        }
    } else {
        // Format each KV pair into the options string "K=V[&K=V]"
        Local<Object> object = value->ToObject();
        Local<Array> keys = object->GetPropertyNames();
        for (std::size_t i = 0; i < keys->Length(); ++i) {
            Local<String> key = keys->Get(i)->ToString();
            String::Utf8Value keyv(key);
            if (keyv.length()) {
                if (i > 0)
                    ss << "&";
                ss << *keyv << "=";
            }

            Local<String> val = object->Get(key)->ToString();
            String::Utf8Value valv(val);
            if (valv.length())
                ss << *valv;
        }
    }

    *str = ss.str();
}
void TiProxy::setParametersFromObject(void* userContext, Local<Object> obj)
{
    HandleScope handleScope;
    Handle<Value> value;
    Handle<Value> controlValue = getValue();
    if (!controlValue->IsObject())
    {
        return;
    }
    Handle<Array> propNames = obj->GetPropertyNames();
    uint32_t props = propNames->Length();
    Local<Value> propValue;
    for (uint32_t i = 0; i < props; i++)
    {
        Handle<String> propString = Handle<String>::Cast(propNames->Get(Integer::New(i)));
        String::Utf8Value propNameUTF(propString);
        Local<Value> propValue = obj->Get(propString);
        TiObject* foundProp = onLookupMember(*propNameUTF);
        if (foundProp != NULL)
        {
            TiObject* addObj = getTiObjectFromJsObject(propValue);
            if (addObj)
            {
                TiProxy* obj = (TiProxy*) userContext;
                TiProxy* uiObj = (TiProxy*) addObj;
                NativeObject* childNO = uiObj->getNativeObject();
                NativeObject* parentNO = obj->getNativeObject();
                parentNO->addChildNativeObject(childNO);
                parentNO->release();
            }
            else
            {
                foundProp->setValue(propValue);
            }
        }
        else
        {
            // Set any custom properties onto the JS object.
            getValue()->ToObject()->ForceSet(propString, propValue);
        }
    }
}