Example #1
0
Handle<Value> WrappedScript::CreateContext(const Arguments& args)
{
	HandleScope scope;

	Persistent<Context> context = Context::New(NULL, WrappedContext::global_template);
	WrappedContext *wrappedContext = new WrappedContext(context);
	Local<Object> global = context->Global();

	// Allow current context access to newly created context's objects.
	context->SetSecurityToken(Context::GetCurrent()->GetSecurityToken());

	// If a sandbox is provided initial the new context's global with it.
	if (args.Length() > 0) {
		Local<Object> sandbox = args[0]->ToObject();
		Local<Array> keys = sandbox->GetPropertyNames();

		for (uint32_t i = 0; i < keys->Length(); i++) {
			Handle<String> key = keys->Get(Integer::New(i))->ToString();
			Handle<Value> value = sandbox->Get(key);
			if (value == sandbox) {
				value = global;
			}
			global->Set(key, value);
		}
	}

	return scope.Close(global);
}
Example #2
0
Handle<Value> WrappedScript::CreateContext(const Arguments& args)
{
	HandleScope scope;
	Local<Object> context = WrappedContext::NewInstance();
	WrappedContext *wrappedContext = NativeObject::Unwrap<WrappedContext>(context);

	if (args.Length() > 0) {
		Local<Object> sandbox = args[0]->ToObject();
		Local<Array> keys = sandbox->GetPropertyNames();

		for (uint32_t i = 0; i < keys->Length(); i++) {
			Handle<String> key = keys->Get(Integer::New(i))->ToString();
			Handle<Value> value = sandbox->Get(key);
			if (value == sandbox) {
				value = context;
			}
			context->Set(key, value);
		}

		if (args.Length() > 1 && args[1]->IsFunction()) {
			wrappedContext->SetInitCallback(Persistent<Function>::New(Handle<Function>::Cast(args[1])));
		}
	}

	wrappedContext->GetV8Context()->SetSecurityToken(
		Context::GetCurrent()->GetSecurityToken());

	return scope.Close(context);
}
Example #3
0
/**
 * @details This is the asynchronous method used to generate a mapserv
 * response. The response is a javascript object literal with the following
 * properties:
 *
 * - `data`: a `Buffer` object representing the response body
 * - `headers`: the HTTP headers as an object literal
 *
 * `args` should contain the following parameters:
 *
 * @param env A javascript object literal containing the CGI environment
 * variables which will direct the mapserv response.
 *
 * @param body The optional string or buffer object representing the body of an
 * HTTP request.
 *
 * @param callback A function that is called on error or when the
 * resource has been created. It should have the signature
 * `callback(err, resource)`.
 */
Handle<Value> Map::MapservAsync(const Arguments& args) {
  HandleScope scope;
  string body;
  Local<Object> env;
  Local<Function> callback;

  switch (args.Length()) {
  case 2:
    ASSIGN_OBJ_ARG(0, env);
    ASSIGN_FUN_ARG(1, callback);
    break;
  case 3:
    ASSIGN_OBJ_ARG(0, env);

    if (args[1]->IsString()) {
      body = *String::Utf8Value(args[1]->ToString());
    } else if (Buffer::HasInstance(args[1])) {
      Local<Object> buffer = args[1]->ToObject();
      body = string(Buffer::Data(buffer), Buffer::Length(buffer));
    } else if (!args[1]->IsNull() && !args[1]->IsUndefined()) {
      THROW_CSTR_ERROR(TypeError, "Argument 1 must be one of a string; buffer; null; undefined");
    }

    ASSIGN_FUN_ARG(2, callback);
    break;
  default:
    THROW_CSTR_ERROR(Error, "usage: Map.mapserv(env, [body], callback)");
  }

  Map* self = ObjectWrap::Unwrap<Map>(args.This());
  MapBaton *baton = new MapBaton();

  baton->request.data = baton;
  baton->self = self;
  baton->callback = Persistent<Function>::New(callback);
  baton->map = self->map;
  baton->error = NULL;
  baton->body = body;

  // Convert the environment object to a `std::map`
  const Local<Array> properties = env->GetPropertyNames();
  const uint32_t length = properties->Length();
  for (uint32_t i = 0; i < length; ++i) {
    const Local<Value> key = properties->Get(i);
    const Local<Value> value = env->Get(key);
    baton->env.insert(pair<string, string>(string(*String::Utf8Value(key->ToString())),
                                           string(*String::Utf8Value(value->ToString())))
                      );
  }

  self->Ref(); // increment reference count so map is not garbage collected

  uv_queue_work(uv_default_loop(),
                &baton->request,
                MapservWork,
                (uv_after_work_cb) MapservAfter);

  return Undefined();
}
Example #4
0
Handle<Value> xhr_send(const Arguments &args) {
	LOGFN("calling xhr send");
	String::Utf8Value arg0(args[0]);
	String::Utf8Value arg1(args[1]);

	const char *method = ToCString(arg0);
	const char *url = ToCString(arg1);

	bool async = args[2]->BooleanValue();
	const char *data = NULL;
	String::Utf8Value arg3(args[3]);
	data = ToCString(arg3);

	int state = args[4]->Int32Value();

	int id = args[5]->Int32Value();

	request_header *headers = NULL;
	if(!args[6].IsEmpty() && !args[6]->IsUndefined() && !args[6]->IsNull()) {
		Local<Object> requestHeadersObj = args[6]->ToObject();
		Local<Array> requestHeaderNames = requestHeadersObj->GetPropertyNames();
		int length = requestHeaderNames->Get(STRING_CACHE_length)->Int32Value();

		for (int i = 0; i < length; i++) {
			request_header * rh = (request_header*) malloc(sizeof(request_header));
			Local<Value> prop = requestHeaderNames->Get(i);
			String::Utf8Value header(prop);
			String::Utf8Value value(requestHeadersObj->Get(prop));
			int hLen = strlen(ToCString(header)) + 1;
			rh->header = (char *) malloc(hLen);
			strlcpy(rh->header, ToCString(header), hLen);
			int vLen = strlen(ToCString(value)) + 1;
			rh->value = (char *) malloc(vLen);
			strlcpy(rh->value, ToCString(value), vLen);
			HASH_ADD(hh, headers, header, strlen(rh->header)+1, rh);
		}
	}

	xhr req;
	req.id = id;
	req.method = method;
	req.url = url;
	req.data = data;
	req.async = async;
	req.state = state;
	req.request_headers = headers;
	xhr_send(&req);

	if(headers != NULL) {
		request_header *currentHeader, *tmp;

		HASH_ITER(hh, headers, currentHeader, tmp) {
			HASH_DEL(headers, currentHeader);
			free(currentHeader->header);
			free(currentHeader->value);
			free(currentHeader);
		}
Example #5
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 #6
0
	v8::Handle<v8::Value> _BeaScript::enumProperties(const v8::Arguments& args){

		HandleScope scope; 
		
		Local<Object> obj = args[0]->ToObject();
		v8::Local<v8::Array> keys = obj->GetPropertyNames();

		for (uint32_t i = 0; i < keys->Length(); i++) {
			v8::Handle<v8::String> key = keys->Get(i)->ToString();
			v8::Handle<v8::Value> value = obj->Get(key);
			std::cout << toString(key) << " : " << toString(value) << std::endl;
		}
		return args.This(); 
	}
Example #7
0
bson encodeObject(const Local<Value> element) {
    HandleScope scope;
    bson_buffer bb;
    bson_buffer_init(&bb);

    Local<Object> object = element->ToObject();
    Local<Array> properties = object->GetPropertyNames();

    for (int i = 0; i < properties->Length(); i++) {
        // get the property name and value
        Local<Value> prop_name = properties->Get(Integer::New(i));
        Local<Value> prop_val = object->Get(prop_name->ToString());

        // convert the property name to a c string
        String::Utf8Value n(prop_name);
        const char *pname = ToCString(n);

        // append property using appropriate appender
        if (prop_val->IsString()) {
            encodeString(&bb, pname, prop_val);
        }
        else if (prop_val->IsInt32()) {
            encodeInteger(&bb, pname, prop_val);
        }
        else if (prop_val->IsNumber()) {
            encodeNumber(&bb, pname, prop_val);
        }
        else if (prop_val->IsBoolean()) {
            encodeBoolean(&bb, pname, prop_val);
        }
        else if (prop_val->IsArray()) {
            encodeArray(&bb, pname, prop_val);
        }
        else if (prop_val->IsObject()
                 && ObjectID::constructor_template->HasInstance(prop_val)) {
            encodeObjectID(&bb, pname, prop_val);
	    }
        else if (prop_val->IsObject()) {
            bson bson(encodeObject(prop_val));
            bson_append_bson(&bb, pname, &bson);
            bson_destroy(&bson);
        }
    }

    bson bson;
    bson_from_buffer(&bson, &bb);

    return bson;
}
Example #8
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();
}
Example #9
0
SV*
V8Context::object2blessed(Handle<Object> obj) {
    char package[128];

    snprintf(
        package,
        128,
        "%s%s::N%d",
        bless_prefix.c_str(),
        *String::AsciiValue(obj->Get(String::New("__perlPackage"))->ToString()),
        number
    );

    HV *stash = gv_stashpv(package, 0);

    if (!stash) {
        Local<Object> prototype = obj->GetPrototype()->ToObject();

        stash = gv_stashpv(package, GV_ADD);

        Local<Array> properties = prototype->GetPropertyNames();
        for (int i = 0; i < properties->Length(); i++) {
            Local<String> name = properties->Get(i)->ToString();
            Local<Value> property = prototype->Get(name);

            if (!property->IsFunction())
                continue;

            Local<Function> fn = Local<Function>::Cast(property);

            CV *code = newXS(NULL, v8method, __FILE__);
            V8ObjectData *data = new V8FunctionData(this, fn, (SV*)code);

            GV* gv = (GV*)*hv_fetch(stash, *String::AsciiValue(name), name->Length(), TRUE);
            gv_init(gv, stash, *String::AsciiValue(name), name->Length(), GV_ADDMULTI); /* vivify */
            my_gv_setsv(aTHX_ gv, (SV*)code);
        }
    }

    SV* rv = newSV(0);
    SV* sv = newSVrv(rv, package);
    V8ObjectData *data = new V8ObjectData(this, obj, sv);
    sv_setiv(sv, PTR2IV(data));

    return rv;
}
Handle<Value> MemoryDatasource::New(const Arguments& args)
{
    HandleScope scope;

    if (!args.IsConstructCall())
        return ThrowException(String::New("Cannot call constructor as function, you need to use 'new' keyword"));

    if (args[0]->IsExternal())
    {
        //std::clog << "external!\n";
        Local<External> ext = Local<External>::Cast(args[0]);
        void* ptr = ext->Value();
        MemoryDatasource* d =  static_cast<MemoryDatasource*>(ptr);
        d->Wrap(args.This());
        return args.This();
    }
    if (args.Length() != 1){
        return ThrowException(Exception::TypeError(
                                  String::New("accepts only one argument, an object of key:value datasource options")));
    }

    if (!args[0]->IsObject())
        return ThrowException(Exception::TypeError(
                                  String::New("Must provide an object, eg {type: 'shape', file : 'world.shp'}")));

    Local<Object> options = args[0]->ToObject();

    mapnik::parameters params;
    Local<Array> names = options->GetPropertyNames();
    unsigned int i = 0;
    unsigned int a_length = names->Length();
    while (i < a_length) {
        Local<Value> name = names->Get(i)->ToString();
        Local<Value> value = options->Get(name);
        params[TOSTR(name)] = TOSTR(value);
        i++;
    }

    //memory_datasource cache;
    MemoryDatasource* d = new MemoryDatasource();
    d->Wrap(args.This());
    d->datasource_ = MAPNIK_MAKE_SHARED<mapnik::memory_datasource>();
    return args.This();
}
void TiProxy::setParametersFromObject(void* userContext, Local<Object> obj)
{
    HandleScope handleScope;
    Handle<Value> value;
    Handle<Value> controlValue = getValue();
    if (!controlValue->IsObject())
    {
        return;
    }
    Handle<Array> propNames = obj->GetPropertyNames();
    uint32_t props = propNames->Length();
    Local<Value> propValue;
    for (uint32_t i = 0; i < props; i++)
    {
        Handle<String> propString = Handle<String>::Cast(propNames->Get(Integer::New(i)));
        String::Utf8Value propNameUTF(propString);
        Local<Value> propValue = obj->Get(propString);
        TiObject* foundProp = onLookupMember(*propNameUTF);
        if (foundProp != NULL)
        {
            TiObject* addObj = getTiObjectFromJsObject(propValue);
            if (addObj)
            {
                TiProxy* obj = (TiProxy*) userContext;
                TiProxy* uiObj = (TiProxy*) addObj;
                NativeObject* childNO = uiObj->getNativeObject();
                NativeObject* parentNO = obj->getNativeObject();
                parentNO->addChildNativeObject(childNO);
                parentNO->release();
            }
            else
            {
                foundProp->setValue(propValue);
            }
        }
        else
        {
            // Set any custom properties onto the JS object.
            getValue()->ToObject()->ForceSet(propString, propValue);
        }
    }
}
bool
createTXTRecord(scopedTXTRecord& txtRecord, Local<Object>& object) {
    HandleScope scope;
    Local<Array> names = object->GetPropertyNames();
    uint32_t length = names->Length();

    for (uint32_t index = 0; index<length; ++index) {
        Local<Value> key = names->Get(index);

        if (key->IsString()) {
            // Local<Value> buffer = object->Get(key);
            Handle<Value> buffer = object->Get(key);
            String::Utf8Value string_value( buffer->ToString());

            // A DNS-SD key is 7-bit ascii
            String::AsciiValue keyString(key);
            std::string buf(*keyString, keyString.length());

 /*           Local<Object> obj;
            uint8_t valLen = 0;
            const void *value = NULL;

            if (Buffer::HasInstance(buffer)) {
                obj = buffer->ToObject();
                valLen = Buffer::Length(obj);
                value = Buffer::Data(obj);
            }

            if (txtRecord.setValue(buf.c_str(), valLen, value) != kDNSServiceErr_NoError) {
                return false;
            }
*/        
            if (txtRecord.setValue(buf.c_str(), buffer->ToString()->Utf8Length(), *string_value) != kDNSServiceErr_NoError) {
                return false;
            }
        } else {
            return false;
        }
    }
    return true;
}
Example #13
0
Handle<Value> JSDatasource::New(const Arguments& args)
{
    if (!args.IsConstructCall())
        return ThrowException(String::New("Cannot call constructor as function, you need to use 'new' keyword"));

    if (args[0]->IsExternal())
    {
        //std::clog << "external!\n";
        Local<External> ext = Local<External>::Cast(args[0]);
        void* ptr = ext->Value();
        JSDatasource* d =  static_cast<JSDatasource*>(ptr);
        d->Wrap(args.This());
        return args.This();
    }
    
    if (!args.Length() == 2){
        return ThrowException(Exception::TypeError(
          String::New("two argument required: an object of key:value datasource options and a callback function for features")));
    }

    if (!args[0]->IsObject())
        return ThrowException(Exception::TypeError(
          String::New("Must provide an object, eg {extent: '-180,-90,180,90'}")));

    Local<Object> options = args[0]->ToObject();

    // function callback
    if (!args[args.Length()-1]->IsFunction())
        return ThrowException(Exception::TypeError(
                  String::New("last argument must be a callback function")));

    // TODO - maybe validate in js?

    bool bind=true;
    if (options->Has(String::New("bind")))
    {
        Local<Value> bind_opt = options->Get(String::New("bind"));
        if (!bind_opt->IsBoolean())
          return ThrowException(Exception::TypeError(
            String::New("'bind' must be a Boolean")));

        bind = bind_opt->BooleanValue();
    }

    mapnik::parameters params;
    params["type"] = "js";
    Local<Array> names = options->GetPropertyNames();
    uint32_t i = 0;
    uint32_t a_length = names->Length();
    while (i < a_length) {
        Local<Value> name = names->Get(i)->ToString();
        Local<Value> value = options->Get(name);
        params[TOSTR(name)] = TOSTR(value);
        i++;
    }

    mapnik::datasource_ptr ds;
    try
    {

        ds = mapnik::datasource_ptr(new js_datasource(params,bind,args[args.Length()-1]));
        
    }
    catch (const std::exception & ex)
    {
        return ThrowException(Exception::Error(
          String::New(ex.what())));
    }
    catch (...)
    {
        return ThrowException(Exception::Error(
          String::New("unknown exception happened, please file bug")));
    }
    if (ds)
    {
        JSDatasource* d = new JSDatasource();
        d->Wrap(args.This());
        d->ds_ptr_ = ds;
        return args.This();
    }

    return Undefined();
}
Example #14
0
/*-----------------------------------------------------------------------------
 * Parse options
 */
bool ConnectParseOptions(Local<Object> options, ConnectRequest* request)
{
  // Get options data
  std::vector<std::string> optionNames = cvv8::CastFromJS<std::vector<std::string> >(options->GetPropertyNames());
  for (size_t i = 0; i < optionNames.size(); i++)
  {
    char* optionName = (char*)(optionNames[i].c_str());
    Local<Value> optionValue = options->Get(String::NewSymbol(optionName));

    if (optionValue->IsUndefined())
    {
      continue;
    }

    if (tva_str_casecmp(optionName, "username") == 0)
    {
      String::AsciiValue val(optionValue->ToString());
      request->username = strdup(*val);
    }
    else if (tva_str_casecmp(optionName, "password") == 0)
    {
      String::AsciiValue val(optionValue->ToString());
      request->password = strdup(*val);
    }
    else if (tva_str_casecmp(optionName, "tmx") == 0)
    {
      if (optionValue->IsString())
      {
        String::AsciiValue val(optionValue->ToString());
        request->primaryTmx = strdup(*val);
      }
      else if (optionValue->IsArray())
      {
        Handle<Array> tmxs = Handle<Array>::Cast(optionValue);
        char** p_tmx = &request->primaryTmx;
        Local<Value> element;
        
        element = tmxs->Get(0);
        if (!element->IsUndefined())
        {
          String::AsciiValue tmx(element->ToString());
          *p_tmx = strdup(*tmx);
          p_tmx = &request->secondaryTmx;
        }

        if (tmxs->Length() > 1)
        {
          element = tmxs->Get(1);
          if (!element->IsUndefined())
          {
            String::AsciiValue tmx(element->ToString());
            *p_tmx = strdup(*tmx);
          }
        }
      }
    }
    else if (tva_str_casecmp(optionName, "name") == 0)
    {
      String::AsciiValue val(optionValue->ToString());
      request->gdClientName = strdup(*val);
    }
    else if (tva_str_casecmp(optionName, "timeout") == 0)
    {
      request->timeout = optionValue->Int32Value() * 1000;
    }
    else if (tva_str_casecmp(optionName, "gdMaxOut") == 0)
    {
      request->gdMaxOut = optionValue->Int32Value();
    }
    else if (tva_str_casecmp(optionName, "config") == 0)
    {
      if (optionValue->IsObject())
      {
        Local<Object> config = Local<Object>::Cast(optionValue);
        std::vector<std::string> configNames = cvv8::CastFromJS<std::vector<std::string> >(config->GetPropertyNames());
        for (size_t j = 0; j < configNames.size(); j++)
        {
          char* configName = (char*)(configNames[j].c_str());
          Local<Value> configValue = config->Get(String::NewSymbol(configName));

          if (configValue->IsUndefined())
          {
            continue;
          }

          for (size_t c = 0; c < NUM_PARAMS; c++)
          {
            ConnectConfigParam* cp = &g_connectConfig[c];
            if (tva_str_casecmp(configName, cp->jsName) == 0)
            {
              switch (cp->configType)
              {
              case ConfigTypeBool:
                {
                  bool bVal;
                  if (configValue->IsBoolean())
                  {
                    bVal = configValue->BooleanValue();
                  }
                  else if (configValue->IsNumber())
                  {
                    bVal = (configValue->NumberValue() != 0);
                  }
                  else if (configValue->IsString())
                  {
                    String::AsciiValue bStrVal(config->ToString());
                    bVal = (tva_str_casecmp(*bStrVal, "true") == 0);
                  }

                  tvaAppCfgSet(cp->tvaParam, &bVal, (TVA_INT32)sizeof(bVal));
                }
                break;

              case ConfigTypeInt:
                {
                  int intVal = configValue->Int32Value();
                  tvaAppCfgSet(cp->tvaParam, &intVal, (TVA_INT32)sizeof(intVal));
                }
                break;

              case ConfigTypeString:
                {
                  String::AsciiValue strVal(configValue->ToString());
                  tvaAppCfgSet(cp->tvaParam, *strVal, (TVA_INT32)strlen(*strVal));
                }
                break;

              case ConfigTypeCustom:
                if (cp->tvaParam == TVA_APPCFG_DATA_TRANSPORT_TYPE)
                {
                  TVA_DATATRANSPORT_TYPE transportType = TVA_DATATRANSPORT_UDP;

                  if (configValue->IsString())
                  {
                    String::AsciiValue strVal(config->ToString());
                    if (tva_str_casecmp(*strVal, "TCP"))
                    {
                      transportType = TVA_DATATRANSPORT_TCP;
                    }
                    else if (tva_str_casecmp(*strVal, "SSL"))
                    {
                      transportType = TVA_DATATRANSPORT_SSL;
                    }
                  }
                  else if (configValue->IsNumber())
                  {
                    int numVal = (int)configValue->NumberValue();
                    if ((numVal == TVA_DATATRANSPORT_TCP) || (numVal == TVA_DATATRANSPORT_SSL))
                    {
                      transportType = (TVA_DATATRANSPORT_TYPE)numVal;
                    }
                  }

                  tvaAppCfgSet(cp->tvaParam, &transportType, (TVA_INT32)sizeof(transportType));
                }
                break;
              }

              break;
            }
          }
        }
      }
    }
  }

  // Make sure required arguments were specified
  if (!request->username || !request->password || !request->primaryTmx)
  {
    return false;
  }

  return true;
}
Handle<Value> Feature::addAttributes(const Arguments& args)
{
    HandleScope scope;

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

    if (args.Length() > 0 ) {
        Local<Value> val = args[0];
        if (val->IsNull() || val->IsUndefined()) {
            return ThrowException(Exception::TypeError(String::New("object expected")));
        } else {
            Local<Object> attr = val->ToObject();
            try
            {
                Local<Array> names = attr->GetPropertyNames();
                unsigned int i = 0;
                unsigned int 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()) {
                        mapnik::value_unicode_string ustr = tr->transcode(TOSTR(value));
#if MAPNIK_VERSION >= 200100
                        fp->get()->put_new(TOSTR(name),ustr);
#else
                        boost::put(*fp->get(),TOSTR(name),ustr);
#endif
                    } else if (value->IsNumber()) {
                        double num = value->NumberValue();
                        // todo - round
                        if (num == value->IntegerValue()) {
#if MAPNIK_VERSION >= 200100
                            fp->get()->put_new(TOSTR(name),static_cast<node_mapnik::value_integer>(value->IntegerValue()));
#else
                            boost::put(*fp->get(),TOSTR(name),static_cast<int>(value->IntegerValue()));
#endif

                        } else {
                            double dub_val = value->NumberValue();
#if MAPNIK_VERSION >= 200100
                            fp->get()->put_new(TOSTR(name),dub_val);
#else
                            boost::put(*fp->get(),TOSTR(name),dub_val);
#endif
                        }
                    } else if (value->IsNull()) {
#if MAPNIK_VERSION >= 200100
                        fp->get()->put_new(TOSTR(name),mapnik::value_null());
#else
                        boost::put(*fp->get(),TOSTR(name),mapnik::value_null());
#endif
                    } else {
                        std::clog << "unhandled type for property: " << TOSTR(name) << "\n";
                    }
                    i++;
                }
            }
            catch (std::exception const& ex )
            {
                return ThrowException(Exception::Error(
                                          String::New(ex.what())));
            }
        }
    }

    return Undefined();
}
Example #16
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 #17
0
Handle<Value> Datasource::New(const Arguments& args)
{
    HandleScope scope;

    if (!args.IsConstructCall())
        return ThrowException(String::New("Cannot call constructor as function, you need to use 'new' keyword"));

    if (args[0]->IsExternal())
    {
        //std::clog << "external!\n";
        Local<External> ext = Local<External>::Cast(args[0]);
        void* ptr = ext->Value();
        Datasource* d =  static_cast<Datasource*>(ptr);
        if (d->datasource_->type() == mapnik::datasource::Raster)
        {
            args.This()->Set(String::NewSymbol("type"),
                             String::NewSymbol("raster"),
                             static_cast<v8::PropertyAttribute>(v8::ReadOnly|v8::DontDelete));
        }
        else
        {
            args.This()->Set(String::NewSymbol("type"),
                             String::NewSymbol("vector"),
                             static_cast<v8::PropertyAttribute>(v8::ReadOnly|v8::DontDelete));
        }
        d->Wrap(args.This());
        return args.This();
    }
    if (args.Length() != 1){
        return ThrowException(Exception::TypeError(
                                  String::New("accepts only one argument, an object of key:value datasource options")));
    }

    if (!args[0]->IsObject())
        return ThrowException(Exception::TypeError(
                                  String::New("Must provide an object, eg {type: 'shape', file : 'world.shp'}")));

    Local<Object> options = args[0]->ToObject();

    mapnik::parameters params;
    Local<Array> names = options->GetPropertyNames();
    unsigned int i = 0;
    unsigned int a_length = names->Length();
    while (i < a_length) {
        Local<Value> name = names->Get(i)->ToString();
        Local<Value> value = options->Get(name);
        // TODO - don't treat everything as strings
        params[TOSTR(name)] = TOSTR(value);
        i++;
    }

    mapnik::datasource_ptr ds;
    try
    {
#if MAPNIK_VERSION >= 200200
        ds = mapnik::datasource_cache::instance().create(params);
#else
        ds = mapnik::datasource_cache::instance()->create(params);
#endif
    }
    catch (std::exception const& ex)
    {
        return ThrowException(Exception::Error(
                                  String::New(ex.what())));
    }

    if (ds)
    {
        if (ds->type() == mapnik::datasource::Raster)
        {
            args.This()->Set(String::NewSymbol("type"),
                             String::NewSymbol("raster"),
                             static_cast<v8::PropertyAttribute>(v8::ReadOnly|v8::DontDelete));
        }
        else
        {
            args.This()->Set(String::NewSymbol("type"),
                             String::NewSymbol("vector"),
                             static_cast<v8::PropertyAttribute>(v8::ReadOnly|v8::DontDelete));
        }
        Datasource* d = new Datasource();
        d->Wrap(args.This());
        d->datasource_ = ds;
        return args.This();
    }
    return Undefined();
}
Handle<Value> Datasource::New(const Arguments& args)
{
    HandleScope scope;

    if (!args.IsConstructCall())
        return ThrowException(String::New("Cannot call constructor as function, you need to use 'new' keyword"));

    if (args[0]->IsExternal())
    {
        //std::clog << "external!\n";
        Local<External> ext = Local<External>::Cast(args[0]);
        void* ptr = ext->Value();
        Datasource* d =  static_cast<Datasource*>(ptr);
        d->Wrap(args.This());
        return args.This();
    }
    if (!args.Length() == 1){
        return ThrowException(Exception::TypeError(
          String::New("accepts only one argument, an object of key:value datasource options")));
    }

    if (!args[0]->IsObject())
        return ThrowException(Exception::TypeError(
          String::New("must provide an object, eg {type: 'shape', file : 'world.shp'}")));

    Local<Object> options = args[0]->ToObject();

    // TODO - maybe validate in js?

    bool bind=true;
    if (options->Has(String::New("bind")))
    {
        Local<Value> bind_opt = options->Get(String::New("bind"));
        if (!bind_opt->IsBoolean())
          return ThrowException(Exception::TypeError(
            String::New("'bind' must be a Boolean")));

        bind = bind_opt->BooleanValue();
    }

    mapnik::parameters params;
    Local<Array> names = options->GetPropertyNames();
    uint32_t i = 0;
    uint32_t a_length = names->Length();
    while (i < a_length) {
        Local<Value> name = names->Get(i)->ToString();
        Local<Value> value = options->Get(name);
        params[TOSTR(name)] = TOSTR(value);
        i++;
    }

    mapnik::datasource_ptr ds;
    try
    {
        ds = mapnik::datasource_cache::create(params, bind);
    }
    catch (const mapnik::config_error & ex )
    {
        return ThrowException(Exception::Error(
          String::New(ex.what())));
    }
    catch (const mapnik::datasource_exception & ex )
    {
        return ThrowException(Exception::Error(
          String::New(ex.what())));
    }
    catch (const std::runtime_error & ex )
    {
        return ThrowException(Exception::Error(
          String::New(ex.what())));
    }
    catch (const std::exception & ex)
    {
        return ThrowException(Exception::Error(
          String::New(ex.what())));
    }
    catch (...)
    {
        return ThrowException(Exception::Error(
          String::New("unknown exception happened, please file bug")));
    }
    if (ds)
    {
        Datasource* d = new Datasource();
        d->Wrap(args.This());
        d->datasource_ = ds;
        return args.This();
    }

    return Undefined();
}
Example #19
0
Handle<Value> WrappedScript::EvalMachine(const Arguments& args)
{
	HandleScope scope;

	if (input_flag == compileCode && args.Length() < 1) {
		return ThrowException(Exception::TypeError(String::New("needs at least 'code' argument.")));
	}

	const int sandbox_index = input_flag == compileCode ? 1 : 0;
	if (context_flag == userContext && args.Length() < (sandbox_index + 1)) {
		return ThrowException(Exception::TypeError(String::New("needs a 'context' argument.")));
	}

	Local<String> code;
	if (input_flag == compileCode) code = args[0]->ToString();

	Local<Object> sandbox;
	if (context_flag == newContext) {
		sandbox = args[sandbox_index]->IsObject() ? args[sandbox_index]->ToObject() : Object::New();
	} else if (context_flag == userContext) {
		sandbox = args[sandbox_index]->ToObject();
	}

	const int filename_index = sandbox_index + (context_flag == newContext ? 1 : 0);
	Local<String> filename =
			args.Length() > filename_index ? args[filename_index]->ToString() : String::New("evalmachine.<anonymous>");

	const int display_error_index = args.Length() - 1;
	bool display_error = false;
	if (args.Length() > display_error_index && args[display_error_index]->IsBoolean()
		&& args[display_error_index]->BooleanValue() == true) {
		display_error = true;
	}

	Persistent<Context> context;

	Local<Array> keys;
	unsigned int i;
	WrappedContext *nContext = NULL;
	Local<Object> contextArg;

	if (context_flag == newContext) {
		// Create the new context
		context = Context::New();

	} else if (context_flag == userContext) {
		// Use the passed in context
		contextArg = args[sandbox_index]->ToObject();
		nContext = NativeObject::Unwrap<WrappedContext>(contextArg);
		context = nContext->GetV8Context();
	}

	// New and user context share code. DRY it up.
	if (context_flag == userContext || context_flag == newContext) {
		// Enter the context
		context->Enter();

		// Call the initCallback, if it exists
		if (nContext) {
			Persistent<Function> initCallback = nContext->GetInitCallback();

			if (!initCallback.IsEmpty()) {
				Handle<Value> callbackArgs[] = { contextArg, context->Global() };
				initCallback->Call(contextArg, 2, callbackArgs);
			}
		}

		// Copy everything from the passed in sandbox (either the persistent
		// context for runInContext(), or the sandbox arg to runInNewContext()).
		keys = sandbox->GetPropertyNames();

		for (i = 0; i < keys->Length(); i++) {
			Handle<String> key = keys->Get(Integer::New(i))->ToString();
			Handle<Value> value = sandbox->Get(key);
			if (value == sandbox) {
				value = context->Global();
			}
			context->Global()->Set(key, value);
		}
	}

	Handle<Value> result;
	Handle<Script> script;

	if (input_flag == compileCode) {
		// well, here WrappedScript::New would suffice in all cases, but maybe
		// Compile has a little better performance where possible
		script = output_flag == returnResult ? Script::Compile(code, filename) : Script::New(code, filename);
		if (script.IsEmpty()) {
			// Hack because I can't get a proper stacktrace on SyntaxError
			return Undefined();
		}
	} else {
		WrappedScript *n_script = NativeObject::Unwrap<WrappedScript>(args.Holder());
		if (!n_script) {
			return ThrowException(Exception::Error(String::New("Must be called as a method of Script.")));
		} else if (n_script->script_.IsEmpty()) {
			return ThrowException(Exception::Error(String::New("'this' must be a result of previous "
				"new Script(code) call.")));
		}

		script = n_script->script_;
	}

	if (output_flag == returnResult) {
		result = script->Run();
		if (result.IsEmpty()) {
			if (context_flag == newContext) {
				context->DetachGlobal();
				context->Exit();
				context.Dispose();
			}
			return Undefined();
		}
	} else {
		WrappedScript *n_script = NativeObject::Unwrap<WrappedScript>(args.Holder());
		if (!n_script) {
			return ThrowException(Exception::Error(String::New("Must be called as a method of Script.")));
		}
		n_script->script_ = Persistent<Script>::New(script);
		result = args.This();
	}

	if (context_flag == userContext || context_flag == newContext) {
		// success! copy changes back onto the sandbox object.
		keys = context->Global()->GetPropertyNames();
		for (i = 0; i < keys->Length(); i++) {
			Handle<String> key = keys->Get(Integer::New(i))->ToString();
			Handle<Value> value = context->Global()->Get(key);
			if (value == context->Global()) {
				value = sandbox;
			}
			sandbox->Set(key, value);
		}
	}

	if (context_flag == newContext) {
		// Clean up, clean up, everybody everywhere!
		context->DetachGlobal();
		context->Exit();
		context.Dispose();
	} else if (context_flag == userContext) {
		// Exit the passed in context.
		context->Exit();
	}

	if (result->IsObject()) {
		Local<Context> creation = result->ToObject()->CreationContext();
	}

	return result == args.This() ? result : scope.Close(result);
}
Example #20
0
/*-----------------------------------------------------------------------------
 * Get the current logger instance (will be created if it doesn't exist)
 *
 * var logger = tervela.getLogger({loggerOptions});
 *
 * loggerOptions = {
 *     filename       : [log file name],                        (string, optional)
 *     tagname        : [tag for log messages in file],         (string, optional (default: "TVA"[pid]))
 * };
 */
Handle<Value> GetLogger(const Arguments& args)
{
  HandleScope scope;
  static Local<Value> _logger;
  static bool _isCreated = false;

  if (!_isCreated)
  {
    // Ready arguments
    char* filename = NULL;
    char* tagname = NULL;

    if (args.Length() >= 1)
    {
      PARAM_REQ_OBJECT(0, args);          // options
      Local<Object> options = Local<Object>::Cast(args[0]);
      std::vector<std::string> optionNames = cvv8::CastFromJS<std::vector<std::string> >(options->GetPropertyNames());
      for (size_t i = 0; i < optionNames.size(); i++)
      {
        char* optionName = (char*)(optionNames[i].c_str());
        Local<Value> optionValue = options->Get(String::NewSymbol(optionName));

        if (optionValue->IsUndefined())
        {
          continue;
        }

        if (tva_str_casecmp(optionName, "filename") == 0)
        {
          String::AsciiValue val(optionValue->ToString());
          filename = strdup(*val);
        }
        else if (tva_str_casecmp(optionName, "tagname") == 0)
        {
          String::AsciiValue val(optionValue->ToString());
          tagname = strdup(*val);
        }
      }
    }

    _logger = Local<Value>::New(Logger::NewInstance(filename, tagname));
    _isCreated = true;

    if (filename) free(filename);
    if (tagname) free(tagname);
  }

  return scope.Close(_logger);
}
void ContactsPersonProxy::_setAddress(void* userContext, Handle<Value> value)
{
    ContactsPersonProxy *obj = (ContactsPersonProxy*) userContext;
    if(!obj->isEditing) {
    	obj->builder_ = obj->contact_.edit();
    }

    // The value passed in *MUST* be an object containing arrays of objects
    // http://docs.appcelerator.com/titanium/latest/#!/api/Titanium.Contacts.Person-property-address
    if(!value->IsObject()) return;

	// Get the JS Object and it's properties
	Local<Object> addressObject = value->ToObject();
	Local<Array> addressProperties = addressObject->GetPropertyNames();

	// Look for properties, such as "work", "home", or "other"
	for(int i = 0, len = addressProperties->Length(); i < len; i++)
	{
		// Get the key and value or each main object
		// { work: [ ... ] }"
		Local<String> addressKey = addressProperties->Get(i)->ToString();
		Local<Value> addressValue = addressObject->Get(addressKey);

		// Create the subkind from the key of the object
		AttributeSubKind::Type subKind = AttributeSubKind::Other;
		QString _key = titanium::V8ValueToQString(addressKey);
		if(_key.toLower() == "work") {
			subKind = AttributeSubKind::Work;
		}
		if(_key.toLower() == "home") {
			subKind = AttributeSubKind::Home;
		}

		// The value of the individual address object *MUST* be an array of address objects
		// [ { street: '12 Main St' }, { street: '21 Meh St' } ]
		if(!addressValue->IsArray()) return;
		// Cast the value of the array to a v8 Array and look for addresses
		Local<Array> addresses = Local<Array>::Cast(addressValue);
		for(int i = 0, len = addresses->Length(); i < len; i++)
		{
			// Create the new address builder object and set the subkind
			ContactPostalAddressBuilder addressBuilder;
			addressBuilder.setSubKind(subKind);

			// Get the actual address object from the array of address objects
			// This *MUST* be an object with keys and values
			// { street: '12 Main St' }
			Local<Value> currentAddress = addresses->Get(Number::New(i));
			if(!currentAddress->IsObject()) return;
			// Get the individual address object and look for it's properties
			Local<Object> currentAddressObject = currentAddress->ToObject();
			Local<Array> currentAddressProperties = currentAddressObject->GetPropertyNames();

			// Go through the keys and value of this object, one at a time
			for(int i = 0, len = currentAddressProperties->Length(); i < len; i++)
			{
				Local<String> currentAddressKey = currentAddressProperties->Get(i)->ToString();
				Local<Value> currentAddressValue = currentAddressObject->Get(currentAddressKey);

				// The value *MUST* be a string
				if(!currentAddressValue->IsString()) return;

				// Cast it to a String and get the UTF8 strings
				Local<String> currentAddressStringValue = currentAddressValue->ToString();

				// Convert them to QStrings for better manipulation
				QString _key = titanium::V8ValueToQString(currentAddressKey);
				QString _value = titanium::V8ValueToQString(currentAddressStringValue);

				// Start populating the address builder
				if(_key.toLower() == "city"){
					addressBuilder.setCity(_value);
				}
				if(_key.toLower() == "label"){
					addressBuilder.setLabel(_value);
				}
				if(_key.toLower() == "line1"){
					addressBuilder.setLine1(_value);
				}
				if(_key.toLower() == "line2") {
					addressBuilder.setLine2(_value);
				}
				if(_key.toLower() == "street") {
					if(_value.contains("\n")) {
						QStringList l = _value.split('\n');
						addressBuilder.setLine1(l.at(0));
						l.removeAt(0);
						addressBuilder.setLine2(l.join(""));
					} else {
						addressBuilder.setLine1(_value);
					}
				}
				if(_key.toLower() == "zip"){
					addressBuilder.setPostalCode(_value);
				}
				if(_key.toLower() == "county"){
					addressBuilder.setRegion(_value);
				}
				if(_key.toLower() == "country"){
					addressBuilder.setCountry(_value);
				}
			}
			// Once finished with an address, add it to the contact
				obj->builder_.addPostalAddress(addressBuilder);
		}
	 }
    // Once done, update the contact
    if(!obj->isEditing) {
    	ContactService().updateContact(obj->contact_);
    }
}