Exemplo n.º 1
0
void ColumnProxy::set(Handle<Value> newValue) {
  Dispose();
  isNull = (newValue->IsNull());
  isLoaded = isDirty = true;
  jsValue = Persistent<Value>::New(newValue);
  DEBUG_PRINT("set %s", handler->column->getName());
}
Exemplo n.º 2
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 );
    }
Exemplo n.º 3
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;
}
Exemplo n.º 4
0
JNIEXPORT void JNICALL
Java_org_appcelerator_kroll_runtime_v8_V8Object_nativeSetWindow
	(JNIEnv *env, jobject javaKrollWindow, jlong ptr, jobject javaWindow)
{
	ENTER_V8(V8Runtime::globalContext);
	titanium::JNIScope jniScope(env);

	Handle<Object> jsKrollWindow;
	if (ptr != 0) {
		jsKrollWindow = Persistent<Object>((Object *) ptr);
	} else {
		jsKrollWindow = TypeConverter::javaObjectToJsValue(env, javaKrollWindow)->ToObject();
	}

	Handle<Value> setWindowValue = jsKrollWindow->Get(String::New("setWindow"));
	if (!setWindowValue->IsFunction()) {
		return;
	}

	Handle<Function> setWindow = Handle<Function>::Cast(setWindowValue->ToObject());

	Handle<Value> jsWindow = TypeConverter::javaObjectToJsValue(env, javaWindow);

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

	if (tryCatch.HasCaught()) {
		V8Util::openJSErrorDialog(tryCatch);
		V8Util::reportException(tryCatch);
	}
}
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");
}
Exemplo n.º 6
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() );
 }
Exemplo n.º 7
0
	Handle<Object> ParsePart(const google::protobuf::Message &message) {
		HandleScope scope;
		const Reflection* r = message.GetReflection();
		const Descriptor* descriptor = message.GetDescriptor();

		Local<Array> properties = Array::New(descriptor->field_count());
		for (int i = 0; i < descriptor->field_count(); i++) {
			const FieldDescriptor* field = descriptor->field(i);
			bool repeated = field->is_repeated();
			if (repeated && !r->FieldSize(message, field)) continue;
			if (!repeated && !r->HasField(message, field)) continue;

			Handle<Value> value;
			if (field->is_repeated()) {
				int size = r->FieldSize(message, field);
				Handle<Array> array = Array::New(size);
				for (int j = 0; j < size; j++)
					array->Set(j, ParseField(message, r, field, j));
				value = array;
			} else {
				value = ParseField(message, r, field, -1);
			}

			if (value->IsNull()) continue;

			properties->Set(i, value);
		}

		Local<Function> from_array = handle_->GetInternalField(2).As<Function>();

		Handle<Value> args = properties;
		return scope.Close(from_array->NewInstance(1, &args));
	}
Exemplo n.º 8
0
	void setPersistentFunc(Persistent<Function>& pf,Handle<Value>& v){
		if(v->IsFunction()){
			if(!pf.IsEmpty()) pf.Dispose();
			pf = Persistent<Function>::New(Handle<Function>::Cast(v));
		}else if(v->IsNull()||v->IsUndefined()){
			if(pf.IsEmpty()) return;
			pf.Dispose();
			pf.Clear();
		}
	}
Exemplo n.º 9
0
int Conv::GetNaturalType(Handle<Value> val) {
  if(val.IsEmpty()) return TYPE_INVALID;
  if(val->IsUndefined()) return TYPE_UNDEFINED;
  if(val->IsNull()) return TYPE_NULL;
  if(val->IsBoolean() || val->IsBooleanObject()) return TYPE_BOOL;
  if(val->IsInt32()) return TYPE_INT;
  if(val->IsUint32()) return TYPE_LONG;
  if(val->IsNumber() || val->IsNumberObject()) return TYPE_DOUBLE;
  if(val->IsString() || val->IsStringObject()) return TYPE_STRING;
  return GetNaturalType(Handle<Object>::Cast(val));
}
Exemplo n.º 10
0
void ColumnProxy::set(Handle<Value> newValue) {
  HandleScope scope;
    
  /* Drop our claim on the old value */
  if(! jsValue.IsEmpty()) jsValue.Dispose();
  
  isNull = (newValue->IsNull());
  isLoaded = isDirty = true;
  jsValue = Persistent<Value>::New(newValue);
  DEBUG_PRINT("set %s", handler->column->getName());
}
Exemplo n.º 11
0
inline bool setField(OGRFeature* f, int field_index, Handle<Value> val){
	if (val->IsInt32()) {
		f->SetField(field_index, val->Int32Value());
	} else if (val->IsNumber()) {
		f->SetField(field_index, val->NumberValue());
	} else if (val->IsString()) {
		std::string str = *NanUtf8String(val);
		f->SetField(field_index, str.c_str());
	} else if(val->IsNull() || val->IsUndefined()) {
		f->UnsetField(field_index);
	} else {
		return true;
	}
	return false;
}
Exemplo n.º 12
0
JNIEXPORT jboolean JNICALL
Java_org_appcelerator_kroll_runtime_v8_V8Object_nativeFireEvent
	(JNIEnv *env, jobject jEmitter, jlong ptr, jstring event, jobject data)
{
	ENTER_V8(V8Runtime::globalContext);
	JNIScope jniScope(env);

	Handle<Value> jsEvent = TypeConverter::javaStringToJsString(event);

#ifdef TI_DEBUG
	String::Utf8Value eventName(jsEvent);
	LOGV(TAG, "firing event \"%s\"", *eventName);
#endif

	Handle<Object> emitter;
	if (ptr != 0) {
		emitter = Persistent<Object>((Object *) ptr);
	} else {
		emitter = TypeConverter::javaObjectToJsValue(jEmitter)->ToObject();
	}

	Handle<Value> fireEventValue = emitter->Get(EventEmitter::emitSymbol);
	if (!fireEventValue->IsFunction()) {
		return JNI_FALSE;
	}

	Handle<Function> fireEvent = Handle<Function>::Cast(fireEventValue->ToObject());

	Handle<Value> jsData = TypeConverter::javaObjectToJsValue(data);
	Handle<Value> result;

	TryCatch tryCatch;
	if (jsData->IsNull()) {
		Handle<Value> args[] = { jsEvent };
		result = fireEvent->Call(emitter, 1, args);
	} else {
		Handle<Value> args[] = { jsEvent, jsData };
		result = fireEvent->Call(emitter, 2, args);
	}

	if (tryCatch.HasCaught()) {
		V8Util::openJSErrorDialog(tryCatch);
		V8Util::reportException(tryCatch);
	} else if (result->IsTrue()) {
		return JNI_TRUE;
	}
	return JNI_FALSE;
}
Exemplo n.º 13
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();
}
Exemplo n.º 14
0
Handle<Value> GeoJSONReader::getCoordsArray(Handle<Object> geojson) {
    Isolate* isolate = Isolate::GetCurrent();

    Handle<String> coordsKey = String::NewFromUtf8(isolate, "coordinates");
    if (!geojson->HasOwnProperty(coordsKey))
        throw "Property \"coordinates\" is missing";


    Handle<Value> coords = geojson->Get(coordsKey);
    if (
        !coords->IsArray()
        && !coords->IsNull()
        && !coords->IsUndefined()
    )
        throw "Property \"coordinates\" must be an instance of Array or null";


    return coords;
}
Exemplo n.º 15
0
geos::geom::Coordinate GeoJSONReader::getCoordinate(Handle<Value> value, bool acceptArrayOnly) {

    bool isArray = value->IsArray();

    if (acceptArrayOnly) {
        if (!isArray)
            throw "A coordinate must be an instance of Array";


    }
    else {
        if (
            !isArray
            && !value->IsNull()
            && !value->IsUndefined()
        )
            throw "A coordinate must be an instance of Array or null";


        if (!isArray)
            return geos::geom::Coordinate::getNull();
    }


    Handle<Array> array = Handle<Array>::Cast(value);
    uint32_t length = array->Length();
    if (length < 2)
        throw "A coordinate's length must be >= 2";


    geos::geom::Coordinate coord;

    coord.x = valueToDouble(array->Get(0));
    coord.y = valueToDouble(array->Get(1));
    if (length > 2) {
        coord.z = valueToDouble(array->Get(2));
    }
    precisionModel->makePrecise(&coord);

    return coord;
}
Exemplo n.º 16
0
	Thread Process::CreateRemoteThread(LPTHREAD_START_ROUTINE proc, PVOID param, CreationThreadFlags flags) const
	{
		auto currentProcId = ::GetCurrentProcess();
		// TODO: throw exception if currentProcId == m_handle

		DWORD threadId = 0;
		Handle threadHandle = ::CreateRemoteThread(
			m_handle,
			NULL,
			0,
			proc,
			param,
			(DWORD)flags,
			&threadId);
		if (threadHandle.IsNull())
		{
			THROW_LAST_ERROR_EXCEPTION();
		}

		return Thread(threadId, std::move(threadHandle));
	}
Exemplo n.º 17
0
VALUE rr_v82rb(Handle<Value> value) {
  if (value.IsEmpty()) {
    return rr_v8_value_empty();
  }
  if (value->IsUndefined() || value->IsNull()) {
    return Qnil;
  }
  if (value->IsExternal()) {
    return rr_reflect_v8_external(value);
  }
  if (value->IsUint32()) {
    return UINT2NUM(value->Uint32Value());
  }
  if (value->IsInt32()) {
    return INT2FIX(value->Int32Value());
  }
  if (value->IsBoolean()) {
    return value->BooleanValue() ? Qtrue : Qfalse;
  }
  if (value->IsNumber()) {
    return rb_float_new(value->NumberValue());
  }  
  if (value->IsString()) {
    return rr_reflect_v8_string(value);
  }
  if (value->IsFunction()) {
    return rr_reflect_v8_function(value);
  }
  if (value->IsArray()) {
    return rr_reflect_v8_array(value);
  }
  if (value->IsDate()) {
    return rr_reflect_v8_date(value);
  }
  if (value->IsObject()) {
    return rr_reflect_v8_object(value);
  }
  return rr_wrap_v8_value(value);  
}
Exemplo n.º 18
0
bool rtNodeContext::has(const char *name)
{
  if(name == NULL)
  {
    rtLogError(" rtNodeContext::has() - no symbolic name for rtValue");
    return false;
  }

  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();

#ifdef ENABLE_NODE_V_6_9
  TryCatch try_catch(mIsolate);
#else
  TryCatch try_catch;
#endif // ENABLE_NODE_V_6_9

  Handle<Value> value = global->Get(String::NewFromUtf8(mIsolate, name) );

  if (try_catch.HasCaught())
  {
     rtLogError("\n ## has() - HasCaught()  ... ERROR");
     return false;
  }

  // No need to check if |value| is empty because it's taken care of
  // by TryCatch above.

  return ( !value->IsUndefined() && !value->IsNull() );
}
int main(int argc, const char * argv[])
{
    using namespace v8::bridge;
    
    /* Create a scripting engine */
    ScriptingEngine *engine = new ScriptingEngine();
    
    /* Execute simple script which contains some variable declarations in the global scope */
    std::stringstream io;
    io << "var intVar          = 10;" << std::endl;
    io << "var numberVar       = 10.5;" << std::endl;
    io << "var stringVar       = 'Hello, World!';" << std::endl;
    io << "var boolVar         = false;" << std::endl;
    io << "var nullVar         = null;" << std::endl;
    io << "var undefinedVar    = undefined;" << std::endl;
    io << "var arrayVar        = [1, 2, 3];" << std::endl;
    io << "var objectVar       = { 'foo': 1, 'bar': 2 };" << std::endl;
    io << "var callbackVar     = function() { };" << std::endl;
    
    engine->execute(io.str());
    
    /*
     * Access each variable. Since the variables was defined
     * in the global scope, we can easly access them using
     * ScriptingEngine::getFromGlobalScope and ScriptingEngine::getValueFromGlobalScope<TType>.
     *
     * Note that you should may use getFromGlobalScope<TType> only when you're sure that the given variable
     * is in your desired type, otherwsie an runtime_error will raise.
     */
    
    /* Lets start by retriving variables using the Conversion API: */
    
    // Int:
    int intVar = engine->getValueFromGlobalScope<int>("intVar");
    std::cout << "intVal: " << intVar << std::endl;
    
    // Number (double/float):
    double numberVar = engine->getValueFromGlobalScope<double>("numberVar");
    std::cout << "numberVar: " << numberVar << std::endl;
    
    // String:
    std::string stringVar = engine->getValueFromGlobalScope<std::string>("stringVar");
    std::cout << "stringVar: " << stringVar << std::endl;
    
    // Bool:
    bool boolVar = engine->getValueFromGlobalScope<bool>("boolVar");
    std::cout << "boolVar: " << boolVar << std::endl;
    
    /* To retrive null and undefined, we must retrive the Handle<Value> */
    
    // Note: since we're going to interact with raw handles,
    // and we're in main, we must create a new handle scope.
    //
    // Note 2: We don't need to open a scope when interacting with raw values
    // in functions and methods that was exposed to JS since v8bridge
    // opens one for us before triggering our function.
    HandleScope handle_scope(engine->getActiveIsolationScope());
    
    // Null:
    Handle<Value> nullVar = engine->getFromGlobalScope("nullVar");
    std::cout << "nullVar (is null?): " << (nullVar->IsNull()) << std::endl;
    
    // Undefined:
    Handle<Value> undefinedVar = engine->getFromGlobalScope("undefinedVar");
    std::cout << "undefinedVar (is undefined?): " << (undefinedVar->IsUndefined()) << std::endl;
    
    /*
     * Array:
     * There're two ways to interact with arrays:
     *  1. JS arrays are been converted automaticly to list. So we can use the
     *  conversion API to convert the Handle<Array> to a native list type. The con
     *  of this action is that the array must contain a specific type (e.g. strings only, ints only). 
     *  2. We can receive the array as raw Handle<Array>. To make things simpler
     *  we can avoid the type-verification by requesting from the Conversion API to get Handle<Array>.
     *  this will make sure that we're dealing with an array (and not with string or undefined variable, for instance).
     */
#if 0 // std::list<T> approch:
    std::list<int> arrayVar = engine->getValueFromGlobalScope<std::list<int> >("arrayVar");
    std::cout << "arrayVar (size: " << arrayVar.size() << "): [";
    for (int i = 0; i < arrayVar.size(); i++)
    {
        if (i < arrayVar.size() - 1)
            std::cout << i << ", ";
        else
            std::cout << i;
    }
    std::cout << "]" << std::endl;
#elif 1 // Handle<Array>
    Handle<Array> arrayVar = engine->getHandleFromGlobalScope<Handle<Array> >("arrayVar");
    String::Utf8Value arrayVarStringRep(arrayVar); // We're using v8::String::Utf8Value to evaluate the array contents into a string
    std::cout << "arrayVar (size: " << arrayVar->Length() << "):"
    << "[" << *arrayVarStringRep << "]" << std::endl;
#else // Handle<Value> raw parsing
    Handle<Value> arrayVar = engine->getFromGlobalScope("arrayVar");
    assert(arrayVar->IsArray());
    String::Utf8Value arrayVarStringRep(arrayVar);
    std::cout << "arrayVar (size: " << Handle<Array>::Cast(arrayVar)->Length() << "):"
   
    << "[" << *arrayVarStringRep << "]" << std::endl;
#endif
    
    /* Free */
    delete engine;
    
    /* Done. */
    return 0;
}
Exemplo n.º 20
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();

	if (*val != NULL) {
		if (field->is_optional() && (val->IsNull() || val->IsUndefined()))
			return;
		
		switch (field->cpp_type()) {
			case FieldDescriptor::CPPTYPE_INT32: {
				if (repeated)
					r->AddInt32(message, field, val->Int32Value());
				else
					r->SetInt32(message, field, val->Int32Value());
				break;
			}
			case FieldDescriptor::CPPTYPE_INT64:
				if (repeated)
					if (preserve_int64 && val->IsArray()) {
						Local<Object> n64_array = val->ToObject();
						uint64 n64;
						uint32 hi = n64_array->Get(0)->Uint32Value(), lo = n64_array->Get(1)->Uint32Value();
						n64 = ((uint64)hi << 32) + (uint64)lo;
						r->AddInt64(message, field, n64);
					} else
						r->AddInt64(message, field, val->NumberValue());
				else
					if (preserve_int64 && val->IsArray()) {
						Local<Object> n64_array = val->ToObject();
						uint64 n64;
						uint32 hi = n64_array->Get(0)->Uint32Value(), lo = n64_array->Get(1)->Uint32Value();
						n64 = ((uint64)hi << 32) + (uint64)lo;
						r->SetInt64(message, field, n64);
					} else
						r->SetInt64(message, field, val->NumberValue());
				break;
			case FieldDescriptor::CPPTYPE_UINT32:
				if (repeated)
					r->AddUInt32(message, field, val->Uint32Value());
				else
					r->SetUInt32(message, field, val->Uint32Value());
				break;
			case FieldDescriptor::CPPTYPE_UINT64:
				if (repeated)
					if (preserve_int64 && val->IsArray()) {
						Local<Object> n64_array = val->ToObject();
						uint64 n64;
						uint32 hi = n64_array->Get(0)->Uint32Value(), lo = n64_array->Get(1)->Uint32Value();
						n64 = ((uint64)hi << 32) + (uint64)lo;
						r->AddUInt64(message, field, n64);
					} else
						r->AddUInt64(message, field, val->NumberValue());
				else
					if (preserve_int64 && val->IsArray()) {
						Local<Object> n64_array = val->ToObject();
						uint64 n64;
						uint32 hi = n64_array->Get(0)->Uint32Value(), lo = n64_array->Get(1)->Uint32Value();
						n64 = ((uint64)hi << 32) + (uint64)lo;
						r->SetUInt64(message, field, n64);
					} else
						r->SetUInt64(message, field, val->NumberValue());
				break;
			case FieldDescriptor::CPPTYPE_DOUBLE:
				if (repeated)
					r->AddDouble(message, field, val->NumberValue());
				else
					r->SetDouble(message, field, val->NumberValue());
				break;
			case FieldDescriptor::CPPTYPE_FLOAT:
				if (repeated)
					r->AddFloat(message, field, val->NumberValue());
				else
					r->SetFloat(message, field, val->NumberValue());
				break;
			case FieldDescriptor::CPPTYPE_BOOL:
				if (repeated)
					r->AddBool(message, field, val->BooleanValue());
				else
					r->SetBool(message, field, val->BooleanValue());
				break;
			case FieldDescriptor::CPPTYPE_ENUM:
				// TODO: possible memory leak?
				enumValue =
					val->IsNumber() ?
						field->enum_type()->FindValueByNumber(val->Int32Value()) :
						field->enum_type()->FindValueByName(*NanAsciiString(val));

				if (enumValue != NULL) {
					if (repeated)
						r->AddEnum(message, field, enumValue);
					else
						r->SetEnum(message, field, enumValue);
				}
				break;
			case FieldDescriptor::CPPTYPE_MESSAGE:
				if (val->IsObject()) {
					if (repeated)
						SerializePart(r->AddMessage(message, field), val.As<Object>());
					else
						SerializePart(r->MutableMessage(message, field), val.As<Object>());
				}
				break;
			case FieldDescriptor::CPPTYPE_STRING:
				if (Buffer::HasInstance(val)) {
					Local<Object> buf = val->ToObject();
					if (repeated)
						r->AddString(message, field, std::string(Buffer::Data(buf), Buffer::Length(buf)));
					else
						r->SetString(message, field, std::string(Buffer::Data(buf), Buffer::Length(buf)));
					break;
				}

				if (val->IsObject()) {
					Local<Object> val2 = val->ToObject();
					Local<Value> converter = val2->Get(NanNew<String>("toProtobuf"));
					if (converter->IsFunction()) {
						Local<Function> toProtobuf = Local<Function>::Cast(converter);
						Local<Value> ret = toProtobuf->Call(val2,0,NULL);
						if (Buffer::HasInstance(ret)) {
							Local<Object> buf = ret->ToObject();
							if (repeated)
								r->AddString(message, field, std::string(Buffer::Data(buf), Buffer::Length(buf)));
							else
								r->SetString(message, field, std::string(Buffer::Data(buf), Buffer::Length(buf)));
							break;
						}
					}
				}
				String::Utf8Value temp(val->ToString());
				std::string value = std::string(*temp);
				if (repeated)
					r->AddString(message, field, value);
				else
					r->SetString(message, field, value);
				break;
		}
	}
}
Exemplo n.º 21
0
jsvalue JsEngine::AnyFromV8(Handle<Value> value, Handle<Object> thisArg)
{
    jsvalue v;
    
    // Initialize to a generic error.
    v.type = JSVALUE_TYPE_UNKNOWN_ERROR;
    v.length = 0;
    v.value.str = 0;
    
    if (value->IsNull() || value->IsUndefined()) {
        v.type = JSVALUE_TYPE_NULL;
    }                
    else if (value->IsBoolean()) {
        v.type = JSVALUE_TYPE_BOOLEAN;
        v.value.i32 = value->BooleanValue() ? 1 : 0;
    }
    else if (value->IsInt32()) {
        v.type = JSVALUE_TYPE_INTEGER;
        v.value.i32 = value->Int32Value();            
    }
    else if (value->IsUint32()) {
        v.type = JSVALUE_TYPE_INDEX;
        v.value.i64 = value->Uint32Value();            
    }
    else if (value->IsNumber()) {
        v.type = JSVALUE_TYPE_NUMBER;
        v.value.num = value->NumberValue();
    }
    else if (value->IsString()) {
        v = StringFromV8(value);
    }
    else if (value->IsDate()) {
        v.type = JSVALUE_TYPE_DATE;
        v.value.num = value->NumberValue();
    }
    else if (value->IsArray()) {
        Handle<Array> object = Handle<Array>::Cast(value->ToObject());
        v.length = object->Length();
        jsvalue* array = new jsvalue[v.length];
        if (array != NULL) {
            for(int i = 0; i < v.length; i++) {
                array[i] = AnyFromV8(object->Get(i));
            }
            v.type = JSVALUE_TYPE_ARRAY;
            v.value.arr = array;
        }
    }
    else if (value->IsFunction()) {
		Handle<Function> function = Handle<Function>::Cast(value);
		jsvalue* array = new jsvalue[2];
        if (array != NULL) { 
			array[0].value.ptr = new Persistent<Object>(Persistent<Function>::New(function));
			array[0].length = 0;
			array[0].type = JSVALUE_TYPE_WRAPPED;
			if (!thisArg.IsEmpty()) {
				array[1].value.ptr = new Persistent<Object>(Persistent<Object>::New(thisArg));
				array[1].length = 0;
				array[1].type = JSVALUE_TYPE_WRAPPED;
			} else {
				array[1].value.ptr = NULL;
				array[1].length = 0;
				array[1].type = JSVALUE_TYPE_NULL;
			}
	        v.type = JSVALUE_TYPE_FUNCTION;
            v.value.arr = array;
        }
    }
    else if (value->IsObject()) {
        Handle<Object> obj = Handle<Object>::Cast(value);
        if (obj->InternalFieldCount() == 1)
            v = ManagedFromV8(obj);
        else
            v = WrappedFromV8(obj);
    }

    return v;
}
Exemplo n.º 22
0
int Conv::ToJavaSequence(JNIEnv *jniEnv, Handle<Value> val, int componentType, jarray *jVal) {
  Local<Object> oVal;
  Local<Value> vLength;
  if(val.IsEmpty() || val->IsNull() || val->IsUndefined()) {
    *jVal = 0;
    return OK;
  }
  if(!val->IsObject())
    return ErrorType;
  
  oVal = val->ToObject();
  vLength = oVal->Get(sLength);
  if(vLength.IsEmpty() || !vLength->IsNumber())
    return ErrorType;
  
  jarray ob;
  jint len = vLength->Int32Value();
  if(isJavaObject(componentType)) {
    jclass componentClass;
    if(isInterfaceOrDict(componentType)) {
      Interface *interface = env->getInterface(getClassId(componentType));
      componentClass = interface->getDeclaredClass();
    } else {
      switch(componentType) {
        default:
          return ErrorType;
        case TYPE_STRING:
          componentClass = jni.java.lang.String.class_;
          break;
        case TYPE_DATE:
          componentClass = jni.java.util.Date.class_;
          break;
        case TYPE_OBJECT:
          componentClass = jni.anode.js.JSObject.class_;
          break;
      }
    }
    ob = jniEnv->NewObjectArray(len, componentClass, 0);
    if(ob) {
      int res = OK;
      for(int i = 0; i < len; i++) {
        jobject item;
        res = ToJavaObject(jniEnv, oVal->Get(i), componentType, &item);
        if(res != OK) break;
        jniEnv->SetObjectArrayElement((jobjectArray)ob, i, item);
        jniEnv->DeleteLocalRef(item);
      }
    }
  } else {
    switch(componentType) {
      default:
        return ErrorType;
      case TYPE_BYTE:
        ob = jniEnv->NewByteArray(len);
        if(ob) {
          /* FIXME: see if this case can be optimised */
          jbyte *buf = jniEnv->GetByteArrayElements((jbyteArray)ob, 0);
          for(int i = 0; i < len; i++)
            buf[i] = (jbyte)oVal->Get(i)->Uint32Value();
          
          jniEnv->ReleaseByteArrayElements((jbyteArray)ob, buf, 0);
          break;
        }
      case TYPE_INT:
        ob = jniEnv->NewIntArray(len);
        if(ob) {
          jint *buf = jniEnv->GetIntArrayElements((jintArray)ob, 0);
          for(int i = 0; i < len; i++)
            buf[i] = oVal->Get(i)->Int32Value();
          
          jniEnv->ReleaseIntArrayElements((jintArray)ob, buf, 0);
          break;
        }
      case TYPE_LONG:
        ob = jniEnv->NewLongArray(len);
        if(ob) {
          jlong *buf = jniEnv->GetLongArrayElements((jlongArray)ob, 0);
          for(int i = 0; i < len; i++)
            buf[i] = oVal->Get(i)->IntegerValue();
          
          jniEnv->ReleaseLongArrayElements((jlongArray)ob, buf, 0);
          break;
        }
      case TYPE_DOUBLE:
        ob = jniEnv->NewDoubleArray(len);
        if(ob) {
          jdouble *buf = jniEnv->GetDoubleArrayElements((jdoubleArray)ob, 0);
          if(!buf) return ErrorMem;
          for(int i = 0; i < len; i++)
            buf[i] = oVal->Get(i)->NumberValue();
          
          jniEnv->ReleaseDoubleArrayElements((jdoubleArray)ob, buf, 0);
          break;
        }
    }
  }
  if(ob) {
    *jVal = ob;
    return OK;
  }
  if(jniEnv->ExceptionCheck())
    jniEnv->ExceptionClear();
  return ErrorVM;
}
Exemplo n.º 23
0
int Conv::ToJavaObject(JNIEnv *jniEnv, Handle<Value> val, int expectedType, jobject *jVal) {

  /* empty, null and undefined convert to null for any nullable type */
  if((expectedType >= TYPE__OB_START) && (val.IsEmpty() || val->IsNull() || val->IsUndefined())) {
    *jVal = 0;
    return OK;
  }

  if(isSequence(expectedType))
    return ToJavaSequence(jniEnv, val, getComponentType(expectedType), (jarray *)jVal);
  
  if(isArray(expectedType))
    return arrayConv->ToJavaArray(jniEnv, val, getComponentType(expectedType), jVal);
  
  if(isMap(expectedType))
    return ToJavaMap(jniEnv, val, getComponentType(expectedType), jVal);
  
  if(isInterface(expectedType))
    return ToJavaInterface(jniEnv, val, getClassId(expectedType), jVal);
  
  if(isDict(expectedType))
    return ToJavaDict(jniEnv, val, getClassId(expectedType), jVal);
  
  HandleScope scope;
  jobject ob;
  switch(expectedType) {
    default:
      return ErrorType;
    case TYPE_BOOL: {
      bool isVoid = val.IsEmpty() ? false : val->BooleanValue();
      ob = jniEnv->CallStaticObjectMethod(jni.anode.js.JSValue_Bool.class_, jni.anode.js.JSValue_Bool.ctor, isVoid);
      break;
    }
    case TYPE_BYTE:
    case TYPE_INT: {
      jint intValue = val.IsEmpty() ? 0 : val->Int32Value();
      ob = jniEnv->CallStaticObjectMethod(jni.anode.js.JSValue_Long.class_, jni.anode.js.JSValue_Long.ctor, (jlong)intValue);
      break;
    }
    case TYPE_LONG: {
      jlong longValue = val.IsEmpty() ? 0 : val->IntegerValue();
      ob = jniEnv->CallStaticObjectMethod(jni.anode.js.JSValue_Long.class_, jni.anode.js.JSValue_Long.ctor, longValue);
      break;
    }
    case TYPE_DOUBLE: {
      jdouble doubleValue = val.IsEmpty() ? 0 : val->NumberValue();
      ob = jniEnv->CallStaticObjectMethod(jni.anode.js.JSValue_Double.class_, jni.anode.js.JSValue_Double.ctor, doubleValue);
      break;
    }
    case TYPE_STRING:
      return ToJavaString(jniEnv, val, (jstring *)jVal);
    case TYPE_DATE:
      return ToJavaDate(jniEnv, val, jVal);
    case TYPE_OBJECT:
      return ToNaturalJavaObject(jniEnv, val, jVal);
    case TYPE_OBJECT|TYPE_BOOL: {
      bool isVoid = val->BooleanValue();
      ob = jniEnv->NewObject(jni.java.lang.Boolean.class_, jni.java.lang.Boolean.ctor, isVoid);
      break;
    }
    case TYPE_OBJECT|TYPE_BYTE: {
      jbyte byteValue = val->Int32Value();
      ob = jniEnv->NewObject(jni.java.lang.Byte.class_, jni.java.lang.Byte.ctor, byteValue);
      break;
    }
    case TYPE_OBJECT|TYPE_INT: {
      jint intValue = val->Int32Value();
      ob = jniEnv->NewObject(jni.java.lang.Integer.class_, jni.java.lang.Integer.ctor, intValue);
      break;
    }
    case TYPE_OBJECT|TYPE_LONG: {
      jlong longValue = val->IntegerValue();
      ob = jniEnv->NewObject(jni.java.lang.Long.class_, jni.java.lang.Long.ctor, longValue);
      break;
    }
    case TYPE_OBJECT|TYPE_DOUBLE: {
      jdouble doubleValue = val->NumberValue();
      ob = jniEnv->NewObject(jni.java.lang.Double.class_, jni.java.lang.Double.ctor, doubleValue);
      break;
    }
  }
  if(ob) {
    *jVal = ob;
    return OK;
  }
  if(jniEnv->ExceptionCheck())
    jniEnv->ExceptionClear();
  return ErrorVM;
}
Exemplo n.º 24
0
/*
   DESCRIPTION
     Processing in binds

   PARAMETERS:
     Handle value, bind struct, eBaton struct
*/
void Connection::GetInBindParams (Handle<Value> v8val, Bind* bind,
                                           eBaton* executeBaton, BindType type)
{
  bind->ind  = 0;
  if(v8val->IsUndefined() || v8val->IsNull())
  {
    bind->value = NULL;
    bind->ind   = -1;
    bind->type        = dpi::DpiVarChar;
  }
  else if(v8val->IsString())
  {
    if( bind->type && bind->type != DATA_STR )
    {
      executeBaton->error= NJSMessages::getErrorMsg(
                             errBindValueAndTypeMismatch, 2);
      goto exitGetInBindParams;
    }

    v8::String::Utf8Value str(v8val->ToString());

    bind->type = dpi::DpiVarChar;
    if(type == BIND_INOUT)
    {
      bind->len = str.length();
    }
    else // IN
    {
      bind->maxSize = bind->len = str.length();
    }
    DPI_SZ_TYPE size = (bind->maxSize >= bind->len ) ?
                        bind->maxSize : bind->len;
    if(size)
    {
      bind->value = (char*)malloc(size);
      if(str.length())
        memcpy(bind->value, *str, str.length());
    }
  }
  else if(v8val->IsInt32())
  {
    if( bind->type && bind->type != DATA_NUM )
    {
      executeBaton->error= NJSMessages::getErrorMsg(
                             errBindValueAndTypeMismatch, 2);
      goto exitGetInBindParams;
    }
    bind->type = dpi::DpiInteger;
    bind->maxSize = bind->len = sizeof(int);
    bind->value = (int*)malloc(bind->len);
    *(int*)(bind->value) = v8val->ToInt32()->Value();
  }
  else if(v8val->IsUint32())
  {
    if( bind->type && bind->type != DATA_NUM )
    {
      executeBaton->error= NJSMessages::getErrorMsg(
                             errBindValueAndTypeMismatch, 2);
      goto exitGetInBindParams;
    }
    bind->type = dpi::DpiUnsignedInteger;
    bind->maxSize = bind->len = sizeof(unsigned int);
    bind->value = (unsigned int*)malloc(bind->len);
    *(unsigned int*)(bind->value) = v8val->ToUint32()->Value();
  }
  else if(v8val->IsNumber())
  {
    if( bind->type && bind->type != DATA_NUM )
    {
      executeBaton->error= NJSMessages::getErrorMsg(errBindValueAndTypeMismatch, 2);
      goto exitGetInBindParams;
    }
    bind->type = dpi::DpiDouble;
    bind->maxSize = bind->len = sizeof(double);
    bind->value = (double*)malloc(bind->len);
    *(double*)(bind->value) = v8val->NumberValue();
  }
  else if(v8val->IsDate ())
  {
    if( bind->type && bind->type != DATA_DATE )
    {
      executeBaton->error= NJSMessages::getErrorMsg(errBindValueAndTypeMismatch, 2);
      goto exitGetInBindParams;
    }
    /* This has to be allocated after stmt is initialized */
    bind->dttmarr = NULL ;
    bind->extvalue = (long double *) malloc (sizeof ( long double ) );
    bind->value = (long double *)malloc (sizeof ( long double ));
    bind->type = dpi::DpiTimestampLTZ;
    bind->len = 0;
    bind->maxSize = 0;
    /* Convert v8::Date value to long double */
    Connection::v8Date2OraDate ( v8val, bind);
  }
  else
  {
    executeBaton->error= NJSMessages::getErrorMsg(errInvalidBindDataType,2);
    goto exitGetInBindParams;
  }
  executeBaton->binds.push_back(bind);
  exitGetInBindParams:
  ;
}
Handle<Object> MetadataNode::GetImplementationObject(const Handle<Object>& object)
{
	DEBUG_WRITE("GetImplementationObject called  on object:%d", object->GetIdentityHash());

	auto target = object;
	Handle<Value> currentPrototype = target;

	Handle<Object> implementationObject;

	implementationObject = object->GetHiddenValue(ConvertToV8String("t::implObj")).As<Object>();
	if (!implementationObject.IsEmpty())
	{
		return implementationObject;
	}

	if (object->HasOwnProperty(V8StringConstants::GetIsPrototypeImplementationObject()))
	{
		auto v8Prototype = V8StringConstants::GetPrototype();
		if (!object->HasOwnProperty(v8Prototype))
		{
			return Handle<Object>();
		}

		DEBUG_WRITE("GetImplementationObject returning the prototype of the object :%d", object->GetIdentityHash());
		return object->Get(v8Prototype).As<Object>();
	}

	auto obj = V8GetHiddenValue(object, "t::ActivityImplementationObject").As<Object>();
	if (!obj.IsEmpty())
	{
		DEBUG_WRITE("GetImplementationObject returning ActivityImplementationObject property on object: %d", object->GetIdentityHash());
		return obj;
	}

	Handle<Value> lastPrototype;
	bool prototypeCycleDetected = false;
	while (implementationObject.IsEmpty())
	{
		//
		currentPrototype = currentPrototype.As<Object>()->GetPrototype();

		if (currentPrototype->IsNull())
			break;

		//DEBUG_WRITE("GetImplementationObject currentPrototypeObject:%d", (currentPrototype.IsEmpty() || currentPrototype.As<Object>().IsEmpty()) ? -1 :  currentPrototype.As<Object>()->GetIdentityHash());
		//DEBUG_WRITE("GetImplementationObject lastPrototypeObject:%d", (lastPrototype.IsEmpty() || lastPrototype.As<Object>().IsEmpty()) ? -1 :  lastPrototype.As<Object>()->GetIdentityHash());

		if (currentPrototype == lastPrototype)
		{
			auto abovePrototype = currentPrototype.As<Object>()->GetPrototype();
			prototypeCycleDetected = abovePrototype == currentPrototype;
		}

		if (currentPrototype.IsEmpty() || prototypeCycleDetected)
		{
			//Handle<Value> abovePrototype = currentPrototype.As<Object>()->GetPrototype();
			//DEBUG_WRITE("GetImplementationObject not found since cycle parents reached abovePrototype:%d", (abovePrototype.IsEmpty() || abovePrototype.As<Object>().IsEmpty()) ? -1 :  abovePrototype.As<Object>()->GetIdentityHash());
			return Handle<Object>();
		}
		else
		{
			auto value = currentPrototype.As<Object>()->GetHiddenValue(V8StringConstants::GetClassImplementationObject());

			if (!value.IsEmpty())
			{
				implementationObject = currentPrototype.As<Object>();
			}
		}

		lastPrototype = currentPrototype;
	}

	return implementationObject;
}