Example #1
0
void Msg_Struct::build_http_msg_buffer(Isolate* isolate, v8::Local<v8::Object> object, std::string &str) {
    std::stringstream stream;
    for(std::vector<Field_Info>::const_iterator iter = field_vec().begin();
            iter != field_vec().end(); iter++) {
        stream.str("");
        stream << "\"" << iter->field_name << "\":";
        Local<Value> value = object->Get(isolate->GetCurrentContext(), String::NewFromUtf8(isolate, iter->field_name.c_str(), NewStringType::kNormal).ToLocalChecked()).ToLocalChecked();
        if(iter->field_type == "int8" || iter->field_type == "int16" ||
                iter->field_type == "int32") {
            int32_t val = 0;
            if (value->IsInt32()) {
                val = value->Int32Value(isolate->GetCurrentContext()).FromJust();
            }
            stream << val << ",";
        }
        else if(iter->field_type == "int64") {
            int64_t val = 0;
            if (value->IsNumber()) {
                val = value->NumberValue(isolate->GetCurrentContext()).FromJust();
            }
            stream << val << ",";
        }
        else if(iter->field_type == "double") {
            double val = 0;
            if (value->IsNumber()) {
                val = value->NumberValue(isolate->GetCurrentContext()).FromJust();
            }
            stream << val << ",";
        }
        else if(iter->field_type == "bool") {
            bool val = 0;
            if (value->IsBoolean()) {
                val = value->BooleanValue(isolate->GetCurrentContext()).FromJust();
            }
            stream << val << ",";
        }
        else if(iter->field_type == "string") {
            if (value->IsString()) {
                String::Utf8Value str(value->ToString(isolate->GetCurrentContext()).ToLocalChecked());
                stream << "\"" << ToCString(str) << "\",";
            } else {
                stream << "\"\",";
            }
        }
        else {
            LOG_ERROR("Can not find the field_type:%s, struct_name:%s", iter->field_type.c_str(), struct_name().c_str());
        }

        str += stream.str();
    }
}
Example #2
0
void vectorTemplate::setVectorY(Local<String> property, Local<Value> value, const AccessorInfo &info){
	Local<External> data = Local<External>::Cast(info.Data());
	vector<double> *vect = reinterpret_cast<vector<double> *>(data->Value());
	if(value->IsNumber()){
		vect->y = value->ToNumber()->Value();
	}
}
Example #3
0
Handle<Value> AddOne(const Arguments& args) {
  do_check_eq(args.Length(), 1);
  Local<Value> v = args[0];
  do_check_true(v->IsNumber());
  Local<Number> n = v->ToNumber();
  return Number::New(n->Value() + 1.0);
}
Example #4
0
	Handle<Value> Texture::On(const Arguments &args)
	{
		HandleScope scope;
		Local<Value> Event;
		Local<Value> Options;
		Local<Value> Callback;
		ClutterActor *instance = ObjectWrap::Unwrap<Texture>(args.This())->_actor;
#if 0
		/* Check arguments */
		if (args.Length() == 2) {
			Event = args[0];
			Callback = args[1];
		} else if (args.Length() == 3) {
			Event = args[0];
			Options = args[1];
			Callback = args[2];
		} else
			return args.This();

		if (!Event->IsNumber()) {
			return ThrowException(Exception::TypeError(
				String::New("first argument must be integer")));
		}

		if (!Callback->IsFunction()) {
			return ThrowException(Exception::TypeError(
				String::New("Second argument must be a callback function")));
		}
#endif
		Actor::On(args);

		return args.This();
	}
Example #5
0
/* Set the shared PRU RAM to an input array
 *	Takes an integer array as input, writes it to PRU shared memory
 *	Not much error checking here, don't pass in large arrays or seg faults will happen
 *	TODO: error checking and allow user to select range to set
 */
Handle<Value> setSharedRAM(const Arguments& args) {
	HandleScope scope;
	
	//Check we have a single argument
	if (args.Length() != 1) {
		ThrowException(Exception::TypeError(String::New("Wrong number of arguments")));
		return scope.Close(Undefined());
	}
	
	//Check that it's an array
	if (!args[0]->IsArray()) {
		ThrowException(Exception::TypeError(String::New("Argument must be array")));
		return scope.Close(Undefined());
	}
	
	//Get array
	Local<Array> a = Array::Cast(*args[0]);
	
	//Iterate over array
	for (unsigned int i = 0; i<a->Length(); i++) {
		//Get element and check it's numeric
		Local<Value> element = a->Get(i);
		if (!element->IsNumber()) {
			ThrowException(Exception::TypeError(String::New("Array must be integer")));
			return scope.Close(Undefined());
		}
		
		//Set corresponding memory bytes
		sharedMem_int[OFFSET_SHAREDRAM + i] = (unsigned int) element->NumberValue();
	}
	
	//Return nothing
	return scope.Close(Undefined());
};
bool ArgConverter::TryConvertToJavaLong(const Local<Value>& value, jlong& javaLong)
{
	bool success = false;

	if (!value.IsEmpty())
	{
		if (value->IsNumber() || value->IsNumberObject())
		{
			javaLong = (jlong)value->IntegerValue();
			success = true;
		}
		else if (value->IsObject())
		{
			auto obj = Local<Object>::Cast(value);
			auto isJavaLongValue = obj->GetHiddenValue(V8StringConstants::GetJavaLong());
			if (!isJavaLongValue.IsEmpty() && isJavaLongValue->BooleanValue())
			{
				javaLong = (jlong)ConvertToJavaLong(value);
				success = true;
			}
		}
	}

	return success;
}
Example #7
0
Handle<Value> Dataset::setGeoTransform(const Arguments& args)
{
	Dataset *ds = ObjectWrap::Unwrap<Dataset>(args.This());
	if(!ds->this_) return NODE_THROW("Dataset object has already been destroyed");

	Handle<Array> transform;
	NODE_ARG_ARRAY(0, "transform", transform);

	if (transform->Length() != 6) {
		return NODE_THROW("Transform array must have 6 elements")
	}

	double buffer[6];
	for (int i = 0; i < 6; i++) {
		Local<Value> val = transform->Get(i);
		if (!val->IsNumber()) {
			return NODE_THROW("Transform array must only contain numbers");
		}
		buffer[i] = val->NumberValue();
	}

	CPLErr err = ds->this_->SetGeoTransform(buffer);
	if (err) return NODE_THROW_CPLERR(err);

	return Undefined();
}
Example #8
0
void
encodeArray(bson_buffer *bb, const char *name, const Local<Value> element) {
    Local<Array> a = Array::Cast(*element);
    bson_buffer *arr = bson_append_start_array(bb, name);

    for (int i = 0, l=a->Length(); i < l; i++) {
        Local<Value> val = a->Get(Number::New(i));
        stringstream keybuf;
        string keyval;
        keybuf << i << endl;
        keybuf >> keyval;

        if (val->IsString()) {
            encodeString(arr, keyval.c_str(), val);
        }
        else if (val->IsInt32()) {
            encodeInteger(arr, keyval.c_str(), val);
        }
        else if (val->IsNumber()) {
            encodeNumber(arr, keyval.c_str(), val);
        }
        else if (val->IsBoolean()) {
            encodeBoolean(arr, keyval.c_str(), val);
        }
        else if (val->IsArray()) {
            encodeArray(arr, keyval.c_str(), val);
        }
        else if (val->IsObject()) {
            bson bson(encodeObject(val));
            bson_append_bson(arr, keyval.c_str(), &bson);
            bson_destroy(&bson);
        }
    }
    bson_append_finish_object(arr);
}
Example #9
0
void
test_BasicCall()
{
  HandleScope handle_scope;
  Handle<ObjectTemplate> templ = ObjectTemplate::New();
  Handle<FunctionTemplate> fnT = v8::FunctionTemplate::New(AddOne);
  templ->Set("AddOne", fnT);

  Persistent<Context> context = Context::New(NULL, templ);
  Context::Scope context_scope(context);
  Local<Value> addone = context->Global()->Get(String::New("AddOne"));
  do_check_true(!addone.IsEmpty());
  do_check_true(!addone->IsUndefined());
  do_check_true(addone->IsObject());
  do_check_true(addone->IsFunction());
  Local<Function> fn = addone.As<Function>();
  do_check_eq(fn, fnT->GetFunction());
  Local<Number> n = Number::New(0.5);
  Handle<Value> args[] = { n };
  Local<Value> v = fn->Call(context->Global(), 1, args);
  do_check_true(!v.IsEmpty());
  do_check_true(v->IsNumber());
  Local<Number> n2 = v->ToNumber();
  do_check_eq(n2->Value(), 1.5);
  context.Dispose();
}
Example #10
0
void UiWindow::SetState(Local<String> property, Local<Value> value, const PropertyCallbackInfo<void>& info) {
    Isolate* isolate = Isolate::GetCurrent();
    HandleScope scope(isolate);
    UiWindow* _this = Unwrap<UiWindow>(info.This());
    if (value->IsNumber()) {
        WINDOW_STATE state = (WINDOW_STATE)value->Int32Value();
        _this->SetState(state);
    }
}
Example #11
0
void ODBCResult::FetchModeSetter(Local<String> property, Local<Value> value, const AccessorInfo &info) {
  HandleScope scope;

  ODBCResult *obj = ObjectWrap::Unwrap<ODBCResult>(info.Holder());
  
  if (value->IsNumber()) {
    obj->m_fetchMode = value->Int32Value();
  }
}
Example #12
0
	void BoxLayout::SpacingSetter(Local<String> name, Local<Value> value, const AccessorInfo& info)
	{
		HandleScope scope;

		if (value->IsNumber()) {
			ClutterActor *instance = ObjectWrap::Unwrap<BoxLayout>(info.This())->_actor;

			mx_box_layout_set_spacing(MX_BOX_LAYOUT(instance), value->ToInteger()->Value());
		}
	}
Example #13
0
	void Texture::FilterQualitySetter(Local<String> name, Local<Value> value, const AccessorInfo& info)
	{
		HandleScope scope;

		if (value->IsNumber()) {
			ClutterActor *instance = ObjectWrap::Unwrap<Actor>(info.This())->_actor;

			clutter_texture_set_filter_quality(CLUTTER_TEXTURE(instance), (ClutterTextureQuality)value->ToInteger()->Value());
		}
	}
Example #14
0
	void Image::ScaleModeSetter(Local<String> name, Local<Value> value, const AccessorInfo& info)
	{
		HandleScope scope;

		if (value->IsNumber()) {
			ClutterActor *instance = ObjectWrap::Unwrap<Image>(info.This())->_actor;

			mx_image_set_scale_mode(MX_IMAGE(instance), (MxImageScaleMode)value->ToInteger()->Value());
		}
	}
Example #15
0
	void Table::ColumnSpacingSetter(Local<String> name, Local<Value> value, const AccessorInfo& info)
	{
		HandleScope scope;

		if (value->IsNumber()) {
			ClutterActor *instance = ObjectWrap::Unwrap<Table>(info.This())->_actor;

			mx_table_set_column_spacing(MX_TABLE(instance), value->ToInteger()->Value());
		}
	}
Example #16
0
Handle<Value> Feature::addAttributes(const Arguments& args)
{
    HandleScope scope;

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

    if (args.Length() > 0 ) {
        Local<Value> value = args[0];
        if (value->IsNull() || value->IsUndefined()) {
            return ThrowException(Exception::TypeError(String::New("object expected")));
        } else {
            Local<Object> attr = value->ToObject();
            try
            {
                Local<Array> names = attr->GetPropertyNames();
                uint32_t i = 0;
                uint32_t a_length = names->Length();
                boost::scoped_ptr<mapnik::transcoder> tr(new mapnik::transcoder("utf8"));
                while (i < a_length) {
                    Local<Value> name = names->Get(i)->ToString();
                    Local<Value> value = attr->Get(name);
                    if (value->IsString()) {
                        UnicodeString ustr = tr->transcode(TOSTR(value));
                        boost::put(*fp->get(),TOSTR(name),ustr);
                    } else if (value->IsNumber()) {
                        double num = value->NumberValue();
                        // todo - round
                        if (num == value->IntegerValue()) {
                            int integer = value->IntegerValue();
                            boost::put(*fp->get(),TOSTR(name),integer);
                        } else {
                            double dub_val = value->NumberValue();
                            boost::put(*fp->get(),TOSTR(name),dub_val);
                        }
                    } else {
                        std::clog << "unhandled type for property: " << TOSTR(name) << "\n";
                    }
                    i++;
                }
            }
            catch (const std::exception & ex )
            {
                return ThrowException(Exception::Error(
                  String::New(ex.what())));
            }
            catch (...) {
                return ThrowException(Exception::Error(
                  String::New("Unknown exception happended - please report bug")));
            }
        }
    }

    return Undefined();
}
Example #17
0
void Point::zSetter(Local<String> property, Local<Value> value, const AccessorInfo &info)
{
	Point *geom = ObjectWrap::Unwrap<Point>(info.This());

	if (!value->IsNumber()) {
		NODE_THROW("z must be a number");
		return;
	}
	double z = value->NumberValue();

	((OGRPoint* )geom->this_)->setZ(z);
}
Example #18
0
void Grid::set_prop(Local<String> property,
                    Local<Value> value,
                    const AccessorInfo& info)
{
    HandleScope scope;
    Grid* g = ObjectWrap::Unwrap<Grid>(info.Holder());
    std::string a = TOSTR(property);
    if (a == "key") {
        if (!value->IsNumber())
            ThrowException(Exception::TypeError(
                               String::New("width must be an integer")));
        g->get()->set_key(TOSTR(value));
    }
}
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?
			}
		}
	}
}
static void Set_DialogState_height(Local<String> property, Local<Value> value, const AccessorInfo& info)
{
    HandleScope scope;

    Local<Object> self = info.Holder();
    Local<External> wrap = Local<External>::Cast(self->GetInternalField(0));
    if (wrap.IsEmpty())
        return;

    DialogState *tmp = (DialogState *) wrap->Value();
    if (tmp == NULL)
        return;

    if (!value.IsEmpty() && value->IsNumber())
        tmp->setHeight(value->Int32Value());
}
bool JSWrapper::execute( const char *scr, JSWrapperData *data, const char *fileName )
{
    HandleScope handle_scope( m_isolate );

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

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

    bool success=false;

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

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

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

            success=true;
        } 
    }

    return success;
}
Example #22
0
static GetdnsType getGetdnsType(Local<Value> value) {
    if (value->IsNumber() || value->IsNumberObject()) {
        return IntType;
    } else if (value->IsBoolean() || value->IsBooleanObject()) {
        return BoolType;
    } else if (value->IsString() || value->IsStringObject()) {
        return StringType;
    } else if (value->IsObject()) {
        // could be a node buffer or array
        if (node::Buffer::HasInstance(value)) {
            return BinDataType;
        } else if (value->IsArray()) {
            return ListType;
        } else if (GNUtil::isDictionaryObject(value)) {
            return DictType;
        }
    }
    return UnknownType;
}
void Color::set_prop(Local<String> property,
                     Local<Value> value,
                     const AccessorInfo& info)
{
    HandleScope scope;
    Color* c = ObjectWrap::Unwrap<Color>(info.This());
    std::string a = TOSTR(property);
    if (!value->IsNumber())
        ThrowException(Exception::TypeError(
                           String::New("color channel value must be an integer")));
    if (a == "a") {
        c->get()->set_alpha(value->IntegerValue());
    } else if (a == "r") {
        c->get()->set_red(value->IntegerValue());
    } else if (a == "g") {
        c->get()->set_green(value->IntegerValue());
    } else if (a == "b") {
        c->get()->set_blue(value->IntegerValue());
    }
}
  static double getNumber(Handle<Object> obj, QString key, double minValue, double defaultValue)
  {
    double result = defaultValue;
    Handle<String> cdtKey = String::New(key.toUtf8());
    if (obj->Has(cdtKey))
    {
      Local<Value> v = obj->Get(cdtKey);
      if (v->IsNumber() == false)
      {
        throw IllegalArgumentException("Expected " + key + " to be a number.");
      }
      result = v->NumberValue();

      if (result < minValue)
      {
        throw IllegalArgumentException(QString("Expected %1 to be greater than %2.")
                                       .arg(key).arg(minValue));
      }
    }
    return result;
  }
Example #25
0
  static double getNumber(Handle<Object> obj, QString key, double minValue, double defaultValue)
  {
    Isolate* current = v8::Isolate::GetCurrent();
    HandleScope handleScope(current);
    double result = defaultValue;
    Handle<String> cdtKey = String::NewFromUtf8(current, key.toUtf8());
    if (obj->Has(cdtKey))
    {
      Local<Value> v = obj->Get(cdtKey);
      if (v->IsNumber() == false || ::qIsNaN(v->NumberValue()))
      {
        throw IllegalArgumentException("Expected " + key + " to be a number.");
      }
      result = v->NumberValue();

      if (result < minValue)
      {
        throw IllegalArgumentException(QString("Expected %1 to be greater than %2.")
                                       .arg(key).arg(minValue));
      }
    }
    return result;
  }
void PassArray(const FunctionCallbackInfo<Value>& args) {
    Isolate * isolate = args.GetIsolate();
    Local<Array> array = Local<Array>::Cast(args[0]);

    if ( args.Length() < 1 || ! args[0]->IsArray()) {
        return;
    }

    if (array->Length() < 3) {
        return;
    }

    Local<String> prop = String::NewFromUtf8(isolate, "not_index");
    if (array->Get(prop)->IsUndefined() ){
        return;
    }

    for (unsigned int i = 0; i < 3; i++ ) {
      if (array->Has(i)) {
        Local<Value> v = array->Get(i);
        if ( !v->IsNumber()) return;

        double value = v->NumberValue();
        array->Set(i, Number::New(isolate, value + 1));
      }
      else {
        return;
      }
    }

    Local<Array> a = Array::New(isolate);
    a->Set(0, array->Get(0));
    a->Set(1, array->Get(prop));
    a->Set(2, array->Get(2));

    args.GetReturnValue().Set(a);
}
Example #27
0
Handle<Value>
Session::Request(const Arguments& args)
{
    HandleScope scope;

    if (args.Length() < 1 || !args[0]->IsString()) {
        return ThrowException(Exception::Error(String::New(
                "Service URI string must be provided as first parameter.")));
    }
    if (args.Length() < 2 || !args[1]->IsString()) {
        return ThrowException(Exception::Error(String::New(
                "String request name must be provided as second parameter.")));
    }
    if (args.Length() < 3 || !args[2]->IsObject()) {
        return ThrowException(Exception::Error(String::New(
                "Object containing request parameters must be provided "
                "as third parameter.")));
    }
    if (args.Length() < 4 || !args[3]->IsInt32()) {
        return ThrowException(Exception::Error(String::New(
                "Integer correlation identifier must be provided "
                "as fourth parameter.")));
    }
    if (args.Length() >= 5 && !args[4]->IsUndefined() && !args[4]->IsString()) {
        return ThrowException(Exception::Error(String::New(
                "Optional request label must be a string.")));
    }
    if (args.Length() > 5) {
        return ThrowException(Exception::Error(String::New(
                "Function expects at most five arguments.")));
    }

    int cidi = args[3]->Int32Value();

    Session* session = ObjectWrap::Unwrap<Session>(args.This());

    BLPAPI_EXCEPTION_TRY

    Local<String> uri = args[0]->ToString();
    String::AsciiValue uriv(uri);

    blpapi::Service service = session->d_session->getService(*uriv);

    Local<String> name = args[1]->ToString();
    String::Utf8Value namev(name);

    blpapi::Request request = service.createRequest(*namev);

    // Loop over object properties, appending/setting into the request.
    Local<Object> obj = args[2]->ToObject();
    Local<Array> props = obj->GetPropertyNames();

    for (std::size_t i = 0; i < props->Length(); ++i) {
        // Process the key.
        Local<Value> keyval = props->Get(i);
        Local<String> key = keyval->ToString();
        String::Utf8Value keyv(key);

        // Process the value.
        //
        // The values present on the outer object are marshalled into the
        // blpapi::Request by setting values using 'set'.  Arrays indicate
        // values which should be marshalled using 'append'.
        Local<Value> val = obj->Get(keyval);
        if (val->IsString()) {
            Local<String> s = val->ToString();
            String::Utf8Value valv(s);
            request.set(*keyv, *valv);
        } else if (val->IsBoolean()) {
            request.set(*keyv, val->BooleanValue());
        } else if (val->IsNumber()) {
            request.set(*keyv, val->NumberValue());
        } else if (val->IsInt32()) {
            request.set(*keyv, val->Int32Value());
        } else if (val->IsUint32()) {
            request.set(*keyv,
                static_cast<blpapi::Int64>(val->Uint32Value()));
        } else if (val->IsDate()) {
            blpapi::Datetime dt;
            mkdatetime(&dt, val);
            request.set(*keyv, dt);
        } else if (val->IsArray()) {
            // Arrays are marshalled into the blpapi::Request by appending
            // value types using the key of the array in the outer object.
            Local<Object> subarray = val->ToObject();
            int jmax = Array::Cast(*val)->Length();
            for (int j = 0; j < jmax; ++j) {
                Local<Value> subval = subarray->Get(j);
                // Only strings, booleans, and numbers are marshalled.
                if (subval->IsString()) {
                    Local<String> s = subval->ToString();
                    String::Utf8Value subvalv(s);
                    request.append(*keyv, *subvalv);
                } else if (subval->IsBoolean()) {
                    request.append(*keyv, subval->BooleanValue());
                } else if (subval->IsNumber()) {
                    request.append(*keyv, subval->NumberValue());
                } else if (subval->IsInt32()) {
                    request.append(*keyv, subval->Int32Value());
                } else if (subval->IsUint32()) {
                    request.append(*keyv,
                        static_cast<blpapi::Int64>(subval->Uint32Value()));
                } else if (subval->IsDate()) {
                    blpapi::Datetime dt;
                    mkdatetime(&dt, subval);
                    request.append(*keyv, dt);
                } else {
                    return ThrowException(Exception::Error(String::New(
                                "Array contains invalid value type.")));
                }
            }
        } else {
            return ThrowException(Exception::Error(String::New(
                        "Object contains invalid value type.")));
        }
    }

    blpapi::CorrelationId cid(cidi);

    if (args.Length() == 5) {
        String::Utf8Value labelv(args[4]->ToString());
        session->d_session->sendRequest(request, session->d_identity,
                                        cid, 0, *labelv, labelv.length());
    } else {
        session->d_session->sendRequest(request, session->d_identity, cid);
    }

    BLPAPI_EXCEPTION_CATCH_RETURN

    return scope.Close(Integer::New(cidi));
}
Example #28
0
static bool check_number(Local<Value> obj) {
	return obj->IsNumber();
}
bool JsArgToArrayConverter::ConvertArg(const Local<Value>& arg, int index)
{
	bool success = false;
	stringstream s;

	JEnv env;

	Type returnType = JType::getClassType(m_return_type);

	if (arg.IsEmpty())
	{
		s << "Cannot convert empty JavaScript object";
		success = false;
	}
	else if (arg->IsInt32() && (returnType == Type::Int || returnType == Type::Null))
	{
		jint value = arg->Int32Value();
		JniLocalRef javaObject(JType::NewInt(env, value));
		SetConvertedObject(env, index, javaObject);

		success = true;
	}
	else if (arg->IsNumber() || arg->IsNumberObject())
	{
		double d = arg->NumberValue();
		int64_t i = (int64_t)d;
		bool isInteger = d == i;

		if (isInteger)
		{
			jobject obj;

			//if returnType is long it will cast to long
			//if there is no return type specified it will cast to int
			//because default return type is null (ref type)
			if ((INT_MIN <= i) && (i <= INT_MAX) && (returnType == Type::Int || returnType == Type::Null))
			{
				obj = JType::NewInt(env, (jint)d);
			}
			else /*isLong*/
			{
				obj = JType::NewLong(env, (jlong)d);
			}

			JniLocalRef javaObject(obj);
			SetConvertedObject(env, index, javaObject);

			success = true;
		}
		else
		{
			jobject obj;

			//if returnType is double it will cast to double
			//if there is no return type specified it will cast to float
			//because default return type is null (ref type)
			if((FLT_MIN <= d) && (d <= FLT_MAX) && (returnType == Type::Float || returnType == Type::Null)) {
				obj = JType::NewFloat(env, (jfloat)d);
			}
			else {/*isDouble*/
				obj = JType::NewDouble(env, (jdouble)d);
			}

			JniLocalRef javaObject(obj);
			SetConvertedObject(env, index, javaObject);

			success = true;
		}
	}
	else if (arg->IsBoolean())
	{
		jboolean value = arg->BooleanValue();
		JniLocalRef javaObject(JType::NewBoolean(env, value));
		SetConvertedObject(env, index, javaObject);
		success = true;
	}
	else if (arg->IsBooleanObject())
	{
		auto boolObj = Local<BooleanObject>::Cast(arg);
		jboolean value = boolObj->BooleanValue() ? JNI_TRUE : JNI_FALSE;
		JniLocalRef javaObject(JType::NewBoolean(env, value));
		SetConvertedObject(env, index, javaObject);

		success = true;
	}
	else if (arg->IsString() || arg->IsStringObject())
	{
		JniLocalRef stringObject(ConvertToJavaString(arg));
		SetConvertedObject(env, index, stringObject);

		success = true;
	}
	else if (arg->IsObject())
	{
		auto objectWithHiddenID = arg->ToObject();

		auto hidden = objectWithHiddenID->GetHiddenValue(V8StringConstants::GetMarkedAsLong());
		if (!hidden.IsEmpty())
		{
			jlong value = 0;
			if (hidden->IsString())
			{
				auto strValue = ConvertToString(hidden->ToString());
				value = atoll(strValue.c_str());
			}
			else if (hidden->IsInt32())
			{
				value = hidden->ToInt32()->Int32Value();
			}

			JniLocalRef javaObject(JType::NewLong(env, value));
			SetConvertedObject(env, index, javaObject);
			return true;
		}

		hidden = objectWithHiddenID->GetHiddenValue(V8StringConstants::GetMarkedAsByte());
		if (!hidden.IsEmpty())
		{
			jbyte value = 0;
			if (hidden->IsString())
			{
				string value = ConvertToString(hidden->ToString());
				int byteArg = atoi(value.c_str());
				value = (jbyte)byteArg;
			}
			else if (hidden->IsInt32())
			{
				int byteArg = hidden->ToInt32()->Int32Value();
				value = (jbyte)byteArg;
			}

			JniLocalRef javaObject(JType::NewByte(env, value));
			SetConvertedObject(env, index, javaObject);
			return true;
		}

		hidden = objectWithHiddenID->GetHiddenValue(V8StringConstants::GetMarkedAsShort());
		if (!hidden.IsEmpty())
		{
			jshort value = 0;
			if (hidden->IsString())
			{
				string value = ConvertToString(hidden->ToString());
				int shortArg = atoi(value.c_str());
				value = (jshort)shortArg;
			}
			else if (hidden->IsInt32())
			{
				jlong shortArg = hidden->ToInt32()->Int32Value();
				value = (jshort)shortArg;
			}

			JniLocalRef javaObject(JType::NewShort(env, value));
			SetConvertedObject(env, index, javaObject);
			return true;
		}

		hidden = objectWithHiddenID->GetHiddenValue(V8StringConstants::GetMarkedAsDouble());
		if (!hidden.IsEmpty())
		{
			jdouble value = 0;
			if (hidden->IsNumber())
			{
				double doubleArg = hidden->ToNumber()->NumberValue();
				value = (jdouble)doubleArg;
			}

			JniLocalRef javaObject(JType::NewDouble(env, value));
			SetConvertedObject(env, index, javaObject);
			return true;
		}

		hidden = objectWithHiddenID->GetHiddenValue(V8StringConstants::GetMarkedAsFloat());
		if (!hidden.IsEmpty())
		{
			jfloat value = 0;
			if (hidden->IsNumber())
			{
				double floatArg = hidden->ToNumber()->NumberValue();
				value = (jfloat)floatArg;
			}

			JniLocalRef javaObject(JType::NewFloat(env, value));
			SetConvertedObject(env, index, javaObject);
			return true;
		}

		hidden = objectWithHiddenID->GetHiddenValue(V8StringConstants::GetMarkedAsChar());
		if (!hidden.IsEmpty())
		{
			jchar value = '\0';
			if (hidden->IsString())
			{
				string str = ConvertToString(hidden->ToString());
				value = (jchar)str[0];
			}

			JniLocalRef javaObject(JType::NewChar(env, value));
			SetConvertedObject(env, index, javaObject);
			return true;
		}

		jweak obj = ObjectManager::GetJavaObjectByJsObjectStatic(objectWithHiddenID);
		success = obj != nullptr;
		if (success)
		{
			SetConvertedObject(env, index, obj, true);
		}
		else
		{
			s << "Cannot convert JavaScript object with id " << objectWithHiddenID->GetIdentityHash() << " at index " << index;
		}
	}
	else if (arg->IsUndefined() || arg->IsNull())
	{
		SetConvertedObject(env, index, nullptr);
		success = true;
	}
	else
	{
		s << "Cannot convert JavaScript object at index " << index;
		success = false;
	}

	if (!success)
	{
		m_error.index = index;
		m_error.msg = s.str();
	}

	return success;
}
Example #30
0
    mapnik::feature_ptr next()
    {

        HandleScope scope;
        
        TryCatch try_catch;
        Local<Value> argv[2] = { Integer::New(feature_id_), obj_ };
        Local<Value> val = ds_->cb_->Call(Context::GetCurrent()->Global(), 2, argv);
        if (try_catch.HasCaught()) {
            FatalException(try_catch);
        }
        else
        {
            if (!val->IsUndefined())
            {
                if (val->IsObject())
                {
                    Local<Object> obj = val->ToObject();
                    if (obj->Has(String::New("x")) && obj->Has(String::New("y")))
                    {
                        Local<Value> x = obj->Get(String::New("x"));
                        Local<Value> y = obj->Get(String::New("y"));
                        if (!x->IsUndefined() && x->IsNumber() && !y->IsUndefined() && y->IsNumber())
                        {
                            mapnik::geometry_type * pt = new mapnik::geometry_type(mapnik::Point);
                            pt->move_to(x->NumberValue(),y->NumberValue());
                            mapnik::feature_ptr feature(mapnik::feature_factory::create(feature_id_));
                            ++feature_id_;
                            feature->add_geometry(pt);
                            if (obj->Has(String::New("properties")))
                            {
                                Local<Value> props = obj->Get(String::New("properties"));
                                if (props->IsObject())
                                {
                                    Local<Object> p_obj = props->ToObject();
                                    Local<Array> names = p_obj->GetPropertyNames();
                                    uint32_t i = 0;
                                    uint32_t a_length = names->Length();
                                    while (i < a_length)
                                    {
                                        Local<Value> name = names->Get(i)->ToString();
                                        // if name in q.property_names() ?
                                        Local<Value> value = p_obj->Get(name);
                                        if (value->IsString()) {
                                            UnicodeString ustr = tr_->transcode(TOSTR(value));
                                            boost::put(*feature,TOSTR(name),ustr);
                                        } else if (value->IsNumber()) {
                                            double num = value->NumberValue();
                                            // todo - round
                                            if (num == value->IntegerValue()) {
                                                int integer = value->IntegerValue();
                                                boost::put(*feature,TOSTR(name),integer);
                                            } else {
                                                double dub_val = value->NumberValue();
                                                boost::put(*feature,TOSTR(name),dub_val);
                                            }
                                        }
                                        i++;
                                    }
                                }
                            }
                            return feature;                
                        }
                    }
                }
            }        
        }

        return mapnik::feature_ptr();
    }