Esempio n. 1
0
enum encoding ParseEncoding(Handle<Value> encoding_v, enum encoding _default) {
  HandleScope scope;

  if (!encoding_v->IsString()) return _default;

  String::Utf8Value encoding(encoding_v);

  if (strcasecmp(*encoding, "utf8") == 0) {
    return UTF8;
  } else if (strcasecmp(*encoding, "utf-8") == 0) {
    return UTF8;
  } else if (strcasecmp(*encoding, "ascii") == 0) {
    return ASCII;
  } else if (strcasecmp(*encoding, "base64") == 0) {
    return BASE64;
  } else if (strcasecmp(*encoding, "ucs2") == 0) {
    return UCS2;
  } else if (strcasecmp(*encoding, "ucs-2") == 0) {
    return UCS2;
  } else if (strcasecmp(*encoding, "binary") == 0) {
    return BINARY;
  } else if (strcasecmp(*encoding, "hex") == 0) {
    return HEX;
  } else if (strcasecmp(*encoding, "raw") == 0) {
    fprintf(stderr, "'raw' (array of integers) has been removed. "
                    "Use 'binary'.\n");
    return BINARY;
  } else if (strcasecmp(*encoding, "raws") == 0) {
    fprintf(stderr, "'raws' encoding has been renamed to 'binary'. "
                    "Please update your code.\n");
    return BINARY;
  } else {
    return _default;
  }
}
Esempio n. 2
0
Handle<String> V8Config::getStringParameter(Handle<Object> element,const char* key){

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

}
Esempio n. 3
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 );
    }
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");
}
JNIEXPORT jobject JNICALL Java_org_appcelerator_kroll_runtime_v8_V8Runtime_nativeEvalString
	(JNIEnv *env, jobject self, jstring source, jstring filename)
{
	ENTER_V8(V8Runtime::globalContext);
	titanium::JNIScope jniScope(env);

	Handle<Value> jsSource = TypeConverter::javaStringToJsString(env, source);
	if (jsSource.IsEmpty() || !jsSource->IsString()) {
		LOGE(TAG, "Error converting Javascript string, aborting evalString");
		return NULL;
	}

	Handle<Value> jsFilename = TypeConverter::javaStringToJsString(env, filename);

	TryCatch tryCatch;
	Handle<Script> script = Script::Compile(jsSource->ToString(), jsFilename);
	Local<Value> result = script->Run();

	if (tryCatch.HasCaught()) {
		V8Util::openJSErrorDialog(tryCatch);
		V8Util::reportException(tryCatch, true);
		return NULL;
	}

	return TypeConverter::jsValueToJavaObject(env, result);
}
Esempio n. 6
0
size_t length(Handle<Value> v) {
    if (v->IsString()) {
        return v->ToString()->Utf8Length();
    } else if (Buffer::HasInstance(v)) {
        return Buffer::Length(v->ToObject());
    } else {
        return 0;
    }
}
Esempio n. 7
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));
}
Esempio n. 8
0
void AstOptimizer::VisitLiteral(Literal* node) {
  Handle<Object> literal = node->handle();
  if (literal->IsSmi()) {
    node->type()->SetAsLikelySmi();
  } else if (literal->IsString()) {
    Handle<String> lit_str(Handle<String>::cast(literal));
    if (!Heap::prototype_symbol()->Equals(*lit_str)) {
      func_name_inferrer_.PushName(lit_str);
    }
  }
}
Esempio n. 9
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"};
}
Esempio n. 10
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;
}
std::vector<char>
NodeSandbox::mapFilename(std::vector<char> fname)
{
  Handle<Value> argv[1] = {
    String::NewSymbol (fname.data())
  };
  Handle<Value> callbackRet = node::MakeCallback (wrap->nodeThis, "mapFilename", 1, argv);
  if (callbackRet->IsString()) {
    std::vector<char> buf;
    buf.resize (callbackRet->ToString()->Utf8Length()+1);
    callbackRet->ToString()->WriteUtf8 (buf.data());
    buf[buf.size()-1] = 0;
    return buf;
  } else {
    ThrowException(Exception::TypeError(String::New("Expected a string return value")));
  }
  return std::vector<char>();
}
void v8_to_gvalue(Handle<Value> v, GValue *gv, GParamSpec *spec) {
	if(v->IsNumber()) {
		g_value_init(gv, G_TYPE_FLOAT);
		g_value_set_float(gv, v->NumberValue());
	} else if(v->IsString()) {
        String::Utf8Value value(v->ToString());
	    if(spec->value_type == GST_TYPE_CAPS) {
	        GstCaps* caps = gst_caps_from_string(*value);
	        g_value_init(gv, GST_TYPE_CAPS);
	        g_value_set_boxed(gv, caps);
	    } else {
	        g_value_init(gv, G_TYPE_STRING);
            g_value_set_string(gv, *value);
	    }
	} else if(v->IsBoolean()) {
		g_value_init(gv, G_TYPE_BOOLEAN);
		g_value_set_boolean(gv, v->BooleanValue());
	}

	return;
}
int NativeImageViewObject::setImage(TiObject* obj)
{
	Handle<Value> img = obj->getValue();
	imageView_->resetImage();
    if (img->IsString()) {
        QString imagePath = V8ValueToQString(obj->getValue());
        if(imagePath.startsWith("http://") || imagePath.startsWith("https://"))
        {
        	ImageLoader::loadImage(imageView_, QUrl(imagePath));
            return NATIVE_ERROR_OK;
        }
        if(!QFile(imagePath).exists())
        {
        	imagePath = getResourcePath(imagePath);
        }
        imageView_->setImage(QUrl(imagePath));
    } else {
        TiObject* obj = TiObject::getTiObjectFromJsObject(img);
        // Ok, this is the old blob object, so get it, use it, and return.
        if (obj != NULL && strcmp(obj->getName(), "Blob") == 0)
        {
			TiBlobObject* blob = static_cast<TiBlobObject*>(obj);
			Image image(blob->data());
			imageView_->setImage(image);
		    return NATIVE_ERROR_OK;
        }
        // This might be the new blob object
        Handle<External> proxyObject = Handle<External>::Cast(img->ToObject()->GetHiddenValue(String::New("proxy")));

        // But return if it's not
        if(proxyObject.IsEmpty())
    		return NATIVE_ERROR_OK;

    	Ti::TiBlob* blob = static_cast<Ti::TiBlob*>(proxyObject->Value());
		Image image(blob->getData());
		imageView_->setImage(image);

    }
    return NATIVE_ERROR_OK;
}
Esempio n. 14
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);  
}
Esempio n. 15
0
JNIEXPORT void JNICALL
Java_org_appcelerator_kroll_runtime_v8_V8Object_nativeUpdateProperties
	(JNIEnv *env, jobject object, jlong ptr, jobject jprops)
{
	ENTER_V8(V8Runtime::globalContext);
	titanium::JNIScope jniScope(env);

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


	Handle<Object> proxyProperties = jsProxy->Get(Proxy::propertiesSymbol)->ToObject();
	Handle<Object> properties = TypeConverter::javaHashMapToJsValue(env, jprops);
	
	Handle<Array> names = properties->GetOwnPropertyNames();
	int length = names->Length();

	for (int i = 0; i < length; ++i) {
		Handle<Value> name = names->Get(i);
		Handle<Value> value = properties->Get(name);
		bool isProperty = true;
		if (name->IsString()) {
			Handle<String> nameString = name->ToString();
			if (!jsProxy->HasRealNamedCallbackProperty(nameString)
				&& !jsProxy->HasRealNamedProperty(nameString)) {
				jsProxy->Set(name, value);
				isProperty = false;
			}
		}
		if (isProperty) {
			proxyProperties->Set(name, value);
		}
	}
}
Esempio n. 16
0
METHOD_RETURN_TYPE CreateWriterToContinue(const ARGS_TYPE& args)
{
    CREATE_ISOLATE_CONTEXT;
	CREATE_ESCAPABLE_SCOPE;
    Handle<Value> instance = PDFWriterDriver::GetNewInstance(args);
    
    PDFWriterDriver* driver = ObjectWrap::Unwrap<PDFWriterDriver>(instance->ToObject());
    
	if ((args.Length() != 2  && args.Length() !=3)||
            (!args[0]->IsString() && !args[0]->IsObject()) ||
            !args[1]->IsString() ||
            ((args.Length() == 3) && !args[2]->IsObject())) {
		THROW_EXCEPTION("Wrong arguments, provide 2 strings - path to file to continue, and path to state file (provided to the previous shutdown call. You may also add an options object");
		SET_FUNCTION_RETURN_VALUE(UNDEFINED);
	}
    
    std::string alternativePath;
    Handle<Object> alternativeStream;
    LogConfiguration logConfig = LogConfiguration::DefaultLogConfiguration;
   
    if(args.Length() == 2 && args[1]->IsObject())
    {
        Handle<Object> anObject = args[1]->ToObject();
        
        if(anObject->Has(NEW_STRING("modifiedFilePath")) && anObject->Get(NEW_STRING("modifiedFilePath"))->IsString())
            alternativePath = *String::Utf8Value(anObject->Get(NEW_STRING("modifiedFilePath"))->ToString());

        if(anObject->Has(NEW_STRING("modifiedStream")) && anObject->Get(NEW_STRING("modifiedStream"))->IsObject())
            alternativeStream = anObject->Get(NEW_STRING("modifiedStream"))->ToObject();
        
        
        if(anObject->Has(NEW_STRING("log")))
        {
            Handle<Value> value = anObject->Get(NEW_STRING("log"));
            if(value->IsString())
            {
                logConfig.ShouldLog = true;
                logConfig.LogFileLocation = *String::Utf8Value(anObject->Get(NEW_STRING("log"))->ToString());
                logConfig.LogStream = NULL;
            }
            else if(value->IsObject())
            {
                logConfig.ShouldLog = true;
                logConfig.LogFileLocation = "";
                ObjectByteWriter proxy(value->ToObject());
                logConfig.LogStream = &proxy;
            }
        }
    }
    
    EStatusCode status;
    
    if(args[0]->IsObject())
    {
        status = driver->ContinuePDF(args[0]->ToObject(),
                                     *String::Utf8Value(args[1]->ToString()),
                                     alternativeStream,
                                     logConfig);
    }
    else
    {
        status = driver->ContinuePDF(*String::Utf8Value(args[0]->ToString()),
                                             *String::Utf8Value(args[1]->ToString()),
                                             alternativePath,
                                             logConfig);
    }
    
    if(status != PDFHummus::eSuccess)
    {
		THROW_EXCEPTION("Unable to continue PDF file, make sure that output file target is available and state file exists");
		SET_FUNCTION_RETURN_VALUE(UNDEFINED);
    }
    SET_FUNCTION_RETURN_VALUE(instance);
}
Esempio n. 17
0
void SerializeField(google::protobuf::Message *message, const Reflection *r, const FieldDescriptor *field, Handle<Value> val) {
  Nan::HandleScope scope;
  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()) {
            Handle<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 if (preserve_int64 && val->IsString()) {
            String::Utf8Value temp(val->ToString());
            std::string value = std::string(*temp);
            r->AddInt64(message, field, std::stoll(value, nullptr, 10));
          } else
            r->AddInt64(message, field, val->NumberValue());
        else
          if (preserve_int64 && val->IsArray()) {
            Handle<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 if (preserve_int64 && val->IsString()) {
            String::Utf8Value temp(val->ToString());
            std::string value = std::string(*temp);
            r->SetInt64(message, field, std::stoll(value, nullptr, 10));
          } 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()) {
            Handle<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 if (preserve_int64 && val->IsString()) {
            String::Utf8Value temp(val->ToString());
            std::string value = std::string(*temp);
            r->AddUInt64(message, field, std::stoull(value, nullptr, 10));
          } else
            r->AddUInt64(message, field, val->NumberValue());
        else
          if (preserve_int64 && val->IsArray()) {
            Handle<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 if (preserve_int64 && val->IsString()) {
            String::Utf8Value temp(val->ToString());
            std::string value = std::string(*temp);
            r->SetUInt64(message, field, std::stoull(value, nullptr, 10));
          } 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(*String::Utf8Value(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)) {
          Handle<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()) {
          Handle<Object> val2 = val->ToObject();
          Handle<Value> converter = val2->Get(Nan::New<String>("toProtobuf").ToLocalChecked());
          if (converter->IsFunction()) {
            Handle<Function> toProtobuf = Handle<Function>::Cast(converter);
            Handle<Value> ret = toProtobuf->Call(val2,0,NULL);
            if (Buffer::HasInstance(ret)) {
              Handle<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;
    }
  }
}
Esempio n. 18
0
extern "C" bool isString(Handle<Value> n) {
    return n->IsString();
}
Esempio n. 19
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;
}
Esempio n. 20
0
Handle<Value> Proxy::proxyConstructor(const Arguments& args)
{
	HandleScope scope;
	JNIEnv *env = JNIScope::getEnv();
	Local<Object> jsProxy = args.Holder();

	Handle<Object> properties = Object::New();
	jsProxy->Set(propertiesSymbol, properties, PropertyAttribute(DontEnum));

	Handle<Object> prototype = jsProxy->GetPrototype()->ToObject();

	Handle<Function> constructor = Handle<Function>::Cast(prototype->Get(constructorSymbol));
	jclass javaClass = (jclass) External::Unwrap(constructor->Get(javaClassSymbol));

	// If ProxyFactory::createV8Proxy invoked us, unwrap
	// the pre-created Java proxy it sent.
	jobject javaProxy = ProxyFactory::unwrapJavaProxy(args);
	bool deleteRef = false;
	if (!javaProxy) {
		javaProxy = ProxyFactory::createJavaProxy(javaClass, jsProxy, args);
		deleteRef = true;
	}

	JNIUtil::logClassName("Create proxy: %s", javaClass);

	Proxy *proxy = new Proxy(javaProxy);
	proxy->Wrap(jsProxy);

	int length = args.Length();

	if (length > 0 && args[0]->IsObject()) {
		/*
		Handle<Value> argsStr = V8Util::jsonStringify(args[0]);
		String::Utf8Value str(argsStr);
		LOGV(TAG, "    with args: %s", *str);
		*/

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

		if (extend) {
			Handle<Array> names = createProperties->GetOwnPropertyNames();
			int length = names->Length();

			for (int i = 0; i < length; ++i) {
				Handle<Value> name = names->Get(i);
				Handle<Value> value = createProperties->Get(name);
				bool isProperty = true;
				if (name->IsString()) {
					Handle<String> nameString = name->ToString();
					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()) {
		Handle<Function> proxyFn = Handle<Function>::Cast(args.Data());
		Handle<Value> *fnArgs = new Handle<Value>[length];
		for (int i = 0; i < length; ++i) {
			fnArgs[i] = args[i];
		}
		proxyFn->Call(jsProxy, length, fnArgs);
	}

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

	return jsProxy;
}
Esempio n. 21
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:
  ;
}