Esempio n. 1
0
Handle<Value> ZipFile::Open(const Arguments& args)
{
    if (args.Length() != 1 || !args[0]->IsString())
        return ThrowException(Exception::TypeError(
          String::New("Argument must be a file name inside the zip")));

    std::string name = TOSTR(args[0]);
  
    // TODO - enforce valid index
    ZipFile* zf = ObjectWrap::Unwrap<ZipFile>(args.This());

    if (zf->Busy())
      return ThrowException(Exception::Error(String::New("Zipfile already in use..")));

    zf->file_index = -1;

    std::vector<std::string>::iterator it = std::find(zf->names.begin(), zf->names.end(), name);
    if (it!=zf->names.end()) {
        zf->file_index = distance(zf->names.begin(), it);
    }

    if (zf->file_index == -1) {
        std::stringstream s;
        s << "No file found by the name of: '" << name << "\n";
        return ThrowException(Exception::Error(String::New(s.str().c_str())));
    }

    if ((zf->file=zip_fopen_index(zf->archive, zf->file_index, 0)) == NULL) {
        zip_fclose(zf->file);
        zf->file = NULL;
        std::stringstream s;
        s << "cannot open file #" << zf->file_index << " in " << name << ": archive error: " << zip_strerror(zf->archive) << "\n";
        return ThrowException(Exception::Error(String::New(s.str().c_str())));
    }

    return Undefined();
}
Handle<Value> OracleClient::Connect(const Arguments& args) {
  HandleScope scope;

  REQ_OBJECT_ARG(0, settings);
  REQ_FUN_ARG(1, callback);

  OracleClient* client = ObjectWrap::Unwrap<OracleClient>(args.This());
  ConnectBaton* baton = new ConnectBaton(client, client->m_environment, &callback);

  OBJ_GET_STRING(settings, "hostname", baton->hostname);
  OBJ_GET_STRING(settings, "user", baton->user);
  OBJ_GET_STRING(settings, "password", baton->password);
  OBJ_GET_STRING(settings, "database", baton->database);
  OBJ_GET_NUMBER(settings, "port", baton->port, 1521);
  OBJ_GET_STRING(settings, "tns", baton->tns);

  client->Ref();

  uv_work_t* req = new uv_work_t();
  req->data = baton;
  uv_queue_work(uv_default_loop(), req, EIO_Connect, (uv_after_work_cb)EIO_AfterConnect);

  return scope.Close(Undefined());
}
Esempio n. 3
0
/**
 * @details This is an asynchronous factory method creating a new `Map`
 * instance from a mapserver mapfile.
 *
 * `args` should contain the following parameters:
 *
 * @param mapfile A string representing the mapfile path.
 *
 * @param callback A function that is called on error or when the map has been
 * created. It should have the signature `callback(err, map)`.
 */
Handle<Value> Map::FromFileAsync(const Arguments& args) {
  HandleScope scope;

  if (args.Length() != 2) {
    THROW_CSTR_ERROR(Error, "usage: Map.FromFile(mapfile, callback)");
  }
  REQ_STR_ARG(0, mapfile);
  REQ_FUN_ARG(1, callback);

  MapfileBaton *baton = new MapfileBaton();

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

  uv_queue_work(uv_default_loop(),
                &baton->request,
                FromFileWork,
                (uv_after_work_cb) FromFileAfter);

  return Undefined();
}
Esempio n. 4
0
Handle<Value> resourceExists(const Arguments &args) {

	bool exists;
	if (args.Length() < 1) {

		exists = false;
	}
	else {

		exists = boost::filesystem::exists(
			System::resourceLocation() + V8::StringToStdString(args[0]->ToString())
		);
	}

	Handle<Value> callbackArgs[] = {
		Boolean::New(exists)
	};

	Handle<Function> callback = args[1].As<Function>();

	callback->Call(Context::GetCurrent()->Global(), 1, callbackArgs);

	return Undefined();
}
Esempio n. 5
0
Handle<Value> Dataset::setGCPs(const Arguments& args)
{
	Dataset *ds = ObjectWrap::Unwrap<Dataset>(args.This());
	if(!ds->this_) return NODE_THROW("Dataset object has already been destroyed");

	Handle<Array> gcps;
	std::string projection("");
	NODE_ARG_ARRAY(0, "gcps", gcps);
	NODE_ARG_OPT_STR(1, "projection", projection);

	GDAL_GCP* list = new GDAL_GCP [gcps->Length()];
	GDAL_GCP* gcp = list;
	for (unsigned int i = 0; i < gcps->Length(); ++i) {
		Local<Value> val = gcps->Get(i);
		if (!val->IsObject()) {
			return NODE_THROW("list of GCPs must only contain objects");
		}
		Local<Object> obj = val->ToObject();

		NODE_STR_FROM_OBJ_OPT(obj, "pszId", gcp->pszId);
		NODE_STR_FROM_OBJ_OPT(obj, "pszInfo", gcp->pszInfo);
		NODE_DOUBLE_FROM_OBJ(obj, "dfGCPPixel", gcp->dfGCPPixel);
		NODE_DOUBLE_FROM_OBJ(obj, "dfGCPLine", gcp->dfGCPLine);
		NODE_DOUBLE_FROM_OBJ(obj, "dfGCPX", gcp->dfGCPX);
		NODE_DOUBLE_FROM_OBJ(obj, "dfGCPY", gcp->dfGCPY);
		NODE_DOUBLE_FROM_OBJ_OPT(obj, "dfGCPZ", gcp->dfGCPZ);
		gcp++;
	}

	if (list) delete [] list;

	CPLErr err = ds->this_->SetGCPs(gcps->Length(), list, projection.c_str());
	if(err) return NODE_THROW_CPLERR(err);

	return Undefined();
}
Handle<Value> TiUIBase::_animate(void* userContext, TiObject*, const Arguments& args)
{
    HandleScope handleScope;

    TiUIBase* self = static_cast<TiUIBase*>(userContext);
    NativeControlObject *native = static_cast<NativeControlObject*>(self->getNativeObject());
    TiObject* tiObject = TiObject::getTiObjectFromJsObject(args[0]);

    if(!tiObject) {
        Local<Object> jsObject = Local<Object>::Cast(args[0]);
        if(args.Length() > 1 && args[1]->IsFunction()) {
        	Handle<Function> callback = Handle<Function>::Cast(args[1]);
        	Handle<Object> source = Handle<Object>::Cast(self->getValue());
            TiV8Event* event = TiV8Event::createEvent("complete", callback, source);
        	native->animate(jsObject, event);
        } else {
            native->animate(jsObject);
        }
    } else {
        native->animate(tiObject->getNativeObject());
    }

    return Undefined();
}
Esempio n. 7
0
Handle<Value> Datasource::featureset(const Arguments& args)
{

    HandleScope scope;

    Datasource* ds = node::ObjectWrap::Unwrap<Datasource>(args.This());

    mapnik::featureset_ptr fs;
    try
    {
        mapnik::query q(ds->datasource_->envelope());
        mapnik::layer_descriptor ld = ds->datasource_->get_descriptor();
        std::vector<mapnik::attribute_descriptor> const& desc = ld.get_descriptors();
        std::vector<mapnik::attribute_descriptor>::const_iterator itr = desc.begin();
        std::vector<mapnik::attribute_descriptor>::const_iterator end = desc.end();
        while (itr != end)
        {
            q.add_property_name(itr->get_name());
            ++itr;
        }

        fs = ds->datasource_->features(q);
    }
    catch (std::exception const& ex)
    {
        return ThrowException(Exception::Error(
                                  String::New(ex.what())));
    }

    if (fs)
    {
        return scope.Close(Featureset::New(fs));
    }

    return Undefined();
}
Esempio n. 8
0
	//*,{
	//	"type":"function",
	//	"name":"startMsgLoop([qMsg])",
	//	"text":"启动消息循环。startMsgLoop 函数执行后会一直运行,而不会执行它后面的语句,直到运行了 exitMsgLoop 函数。窗口程序必须运行 startMsgLoop 函数,否则程序会立即退出,且无法响应用户操作。",
	//	"param":[
	//		{
	//			"type":"boolean",
	//			"name":"[qMsg]",
	//			"text":"启动消息循环的种类,是否是非窗口消息循环,默认是 false。"
	//		}
	//	],
	//	"return":{
	//		"type":"void",
	//		"text":"函数没有返回值。"
	//	},
	//	"remark":[
	//		"startMsgLoop 内部启动两种消息循环,窗口类和非窗口类。非窗口类的消息循环效率更高,但是非窗口类消息循环必须没有使用任何窗口的时候调用,而且需要启用了对应的机制,否则函数失败立即返回。",
	//		"当一个应用程序含有窗口的时候,关闭主窗口会自动调用 exitMsgLoop 机制,从而退出应用程序。如果应用程序没有窗口,则必须自己处理在哪里调用 exitMsgLoop,否则程序被挂起,永远不会退出。"
	//	],
	//	"example":[
	//		"setTimer(function(){",
	//		"	//这里每 3 秒调用一次,一般 alert 会阻止程序继续运行直到用户关闭了对话框,但是它不会阻止 Timer 的调用,对话框会持续的弹出。",
	//		"	alert(\"click to call exitMsgLoop\");",
	//		"	//退出消息循环,startMsgLoop 返回,程序退出。",
	//		"	exitMsgLoop();",
	//		"},3000);",
	//		"startMsgLoop();"
	//	]
	//}//*
	Handle<Value> startMsgLoop(const Arguments& args){
		bool qMsg = GET_ARGS_VALUE(0,false,Boolean);
		_env->queue.Start(qMsg);
		return Undefined();
	}
Esempio n. 9
0
 Handle<Value> LogWarning(const Arguments& args)
 {
    LOG_WARNING(ToStdString(args[0]));
    return Undefined();
 }
Esempio n. 10
0
 Handle<Value> LogInfo(const Arguments& args)
 {
    LOG_INFO(ToStdString(args[0]));
    return Undefined();
 }
Esempio n. 11
0
 Handle<Value> LogError(const Arguments& args)
 {
    LOG_ERROR(ToStdString(args[0]));
    return Undefined();
 }
Esempio n. 12
0
 Handle<Value> LogAlways(const Arguments& args)
 {
    LOG_ALWAYS(ToStdString(args[0]));
    return Undefined();
 }
Esempio n. 13
0
 Handle<Value> LogDebug(const Arguments& args)
 {
    LOG_DEBUG(ToStdString(args[0]));
    return Undefined();
 }
Esempio n. 14
0
   Handle<Value> MSAddSpawner(const Arguments& args)
   {
      HandleScope scope;
      dtEntity::MapSystem* ms = UnwrapMapSystem(args.This());

      if(args.Length() != 1)
      {
         return ThrowError("Usage: addSpawner({components, name, guicategory, mapname, addtospawnerstore, iconpath})");
      }

      Handle<Object> obj = Handle<Object>::Cast(args[0]);

      Handle<Value> vname = obj->Get(String::New("name"));
      Handle<Value> vcomponents = obj->Get(String::New("components"));

      if(vname.IsEmpty() || vcomponents.IsEmpty())
      {
         return ThrowError("Usage: addSpawner({components, name, guicategory, mapname, addtospawnerstore, iconpath, parentname})");
      }

      Handle<Value> vguicategory = obj->Get(String::New("guicategory"));
      Handle<Value> vmapname = obj->Get(String::New("mapname"));
      Handle<Value> vaddtospawnerstore = obj->Get(String::New("addtospawnerstore"));
      Handle<Value> viconpath = obj->Get(String::New("iconpath"));
      Handle<Value> vparentname = obj->Get(String::New("parentname"));

      std::string name = ToStdString(vname);
      std::string mapname = vmapname.IsEmpty() ? "" : ToStdString(vmapname);

      Handle<Object> components = Handle<Object>::Cast(vcomponents);

      dtEntity::Spawner* parent = NULL;

      if(!vparentname.IsEmpty() && !vparentname->IsUndefined())
      {
         ms->GetSpawner(ToStdString(vparentname), parent);
      }

      osg::ref_ptr<dtEntity::Spawner> spawner = new dtEntity::Spawner(name, mapname, parent);

      if(!vguicategory.IsEmpty() && !vguicategory->IsUndefined())
      {
         spawner->SetGUICategory(ToStdString(vguicategory));
      }

      if(!vaddtospawnerstore.IsEmpty() && !vaddtospawnerstore->IsUndefined())
      {
         spawner->SetAddToSpawnerStore(vaddtospawnerstore->BooleanValue());
      }

      if(!viconpath.IsEmpty() && !viconpath->IsUndefined())
      {
         spawner->SetIconPath(ToStdString(viconpath));
      }

      Handle<Array> keys = components->GetPropertyNames();
      
      for(unsigned int i = 0; i < keys->Length(); ++i)
      {
         Handle<Value> key = keys->Get(Integer::New(i));
         std::string keyname = ToStdString(key);

         dtEntity::StringId ctype = dtEntity::SIDHash(keyname);

         dtEntity::ComponentPluginManager::GetInstance().StartEntitySystem(ms->GetEntityManager(), ctype);

         if(ms->GetEntityManager().HasEntitySystem(ctype))
         {
            Handle<Value> val = components->Get(key);
            if(val->IsObject())
            {
               Handle<Object> compobj = Handle<Object>::Cast(val);
               Handle<Array> compkeys = compobj->GetPropertyNames();

               dtEntity::GroupProperty props;
               for(unsigned int j = 0; j < compkeys->Length(); ++j)
               {
                  Handle<Value> compkey = compkeys->Get(Integer::New(j));
                  std::string compkeystr = ToStdString(compkey);
                  Handle<Value> compval = compobj->Get(compkey);
                  dtEntity::Property* prop = ConvertValueToProperty(compval);
                  props.Add(dtEntity::SIDHash(compkeystr), prop);
               }
               spawner->AddComponent(ctype, props);
            }
         }
      }
      
      ms->AddSpawner(*spawner);
      return Undefined();
   }
Handle<Value> TiObject::onFunctionCall(const Arguments&)
{
    // Default function call returns "Undefined"
    return Undefined();
}
Esempio n. 16
0
	//*,{
	//	"type":"function",
	//	"name":"exitMsgLoop()",
	//	"text":"退出消息循环,执行这个函数会让 startMsgLoop 函数返回。",
	//	"param":[
	//	],
	//	"return":{
	//		"type":"void",
	//		"text":"函数没有返回值。"
	//	}
	//}//*
	Handle<Value> exitMsgLoop(const Arguments& args){
		_env->queue.Close();
		return Undefined();
	}
Handle<Value> SublineStringMatcherJs::extractMatchingSublines(const Arguments& args)
{
    HandleScope scope;

    SublineStringMatcherJs* smJs = ObjectWrap::Unwrap<SublineStringMatcherJs>(args.This());
    SublineStringMatcherPtr sm = smJs->getSublineStringMatcher();

    OsmMapJs* mapJs = ObjectWrap::Unwrap<OsmMapJs>(args[0]->ToObject());
    ElementJs* e1Js = ObjectWrap::Unwrap<ElementJs>(args[1]->ToObject());
    ElementJs* e2Js = ObjectWrap::Unwrap<ElementJs>(args[2]->ToObject());
    ConstOsmMapPtr m = mapJs->getConstMap();
    ConstElementPtr e1 = e1Js->getConstElement();
    ConstElementPtr e2 = e2Js->getConstElement();

    Handle<Value> result;

    try
    {
        WaySublineMatchString match = sm->findMatch(m, e1, e2);

        if (match.isEmpty())
        {
            return Undefined();
        }

        // convert match into elements in a new map.
        set<ElementId> eids;
        eids.insert(e1->getElementId());
        eids.insert(e2->getElementId());
        OsmMapPtr copiedMap(new OsmMap(m->getProjection()));
        CopySubsetOp(m, eids).apply(copiedMap);
        WaySublineMatchString copiedMatch(match, copiedMap);

        // split the shared line based on the matching subline
        ElementPtr match1, scraps1;
        ElementPtr match2, scraps2;
        WaySublineString string1 = copiedMatch.getSublineString1();
        WaySublineString string2 = copiedMatch.getSublineString2();

        try
        {
            MultiLineStringSplitter().split(copiedMap, string1, copiedMatch.getReverseVector1(), match1,
                                            scraps1);
            MultiLineStringSplitter().split(copiedMap, string2, copiedMatch.getReverseVector2(), match2,
                                            scraps2);
        }
        catch (const IllegalArgumentException& e)
        {
            // this is unusual print out some information useful to debugging.
            MapReprojector::reprojectToWgs84(copiedMap);
            LOG_WARN(OsmWriter::toString(copiedMap));
            throw e;
        }

        if (!match1 || !match2)
        {
            result = Undefined();
        }
        else
        {
            Handle<Object> obj = Object::New();
            obj->Set(String::NewSymbol("map"), OsmMapJs::create(copiedMap));
            obj->Set(String::NewSymbol("match1"), ElementJs::New(match1));
            obj->Set(String::NewSymbol("match2"), ElementJs::New(match2));
            result = obj;
        }
    }
    catch (const HootException& e)
    {
        return v8::ThrowException(HootExceptionJs::create(e));
    }

    return scope.Close(result);
}
Handle<Value> TiUIBase::_remove(void* userContext, TiObject*, const Arguments& args)
{
    HandleScope handleScope;
    // JavaScript usage:
    //
    // arg[0] = Titanium.UI.View
    //
    if (args.Length() < 1)
    {
        return ThrowException(String::New(Ti::Msg::Missing_argument));
    }
    if (!args[0]->IsObject())
    {
        return ThrowException(String::New(Ti::Msg::Invalid_remove_argument));
    }

    TiUIBase* obj = (TiUIBase*) userContext;
    TiObject* removeObject = TiObject::getTiObjectFromJsObject(args[0]);
    if (removeObject == NULL)
    {
        return ThrowException(String::New(Ti::Msg::Invalid_remove_argument));
    }
    NativeObject* parentControl = obj->getNativeObject();
    if (parentControl == NULL)
    {
        return ThrowException(String::New(Ti::Msg::INTERNAL__Missing_native_object));
    }
    vector<ObjectEntry>::const_iterator it;
    bool foundChild = false;
    for (it = obj->childControls_.begin(); it != obj->childControls_.end(); it++)
    {
        if ((*it).isSameInstance(removeObject))
        {
            NativeObject* childControl = (*it)->getNativeObject();
            if (childControl == NULL)
            {
                parentControl->release();
                return ThrowException(String::New(Ti::Msg::INTERNAL__Missing_native_object));
            }
            parentControl->removeChildNativeObject(childControl);
            int len = obj->jsChildren_->Length();
            for(int i = 0; i < len; i++)
            {
            	if(obj->jsChildren_->Get(i) == removeObject->getValue())
            	{
                    obj->jsChildren_->Delete(i);
                    break;
            	}
            }
            childControl->release();
            foundChild = true;
            break;
        }
    }
    parentControl->release();
    if (!foundChild)
    {
        TI_WARNING(Ti::Msg::Remove_child_warning);
    }
    return Undefined();
}
Esempio n. 19
0
 Handle<Value> JSHandler::on(const Arguments& args) {
     HandleScope scope;
     if (args.Length() != 2 || !args[0]->IsString() || !args[1]->IsFunction()) {
         return ThrowException(Exception::TypeError(String::New("please provide an event name and callback function")));
     }
     std::string callback_name = *String::Utf8Value(args[0]->ToString());
     Local<Function> callback = Local<Function>::Cast(args[1]);
     if (callback->IsNull() || callback->IsUndefined()) {
         return ThrowException(Exception::TypeError(String::New("please provide a valid callback function for second arg")));
     }
     JSHandler* handler = node::ObjectWrap::Unwrap<JSHandler>(args.This());
     if (callback_name == "node") {
         if (!handler->node_cb.IsEmpty()) {
             handler->node_cb.Dispose();
         }
         handler->node_cb = Persistent<Function>::New(callback);
     } else if (callback_name == "way") {
         if (!handler->way_cb.IsEmpty()) {
             handler->way_cb.Dispose();
         }
         handler->way_cb = Persistent<Function>::New(callback);
     } else if (callback_name == "relation") {
         if (!handler->relation_cb.IsEmpty()) {
             handler->relation_cb.Dispose();
         }
         handler->relation_cb = Persistent<Function>::New(callback);
     } else if (callback_name == "init") {
         if (!handler->init_cb.IsEmpty()) {
             handler->init_cb.Dispose();
         }
         handler->init_cb = Persistent<Function>::New(callback);
     } else if (callback_name == "before_nodes") {
         if (!handler->before_nodes_cb.IsEmpty()) {
             handler->before_nodes_cb.Dispose();
         }
         handler->before_nodes_cb = Persistent<Function>::New(callback);
     } else if (callback_name == "after_nodes") {
         if (!handler->after_nodes_cb.IsEmpty()) {
             handler->after_nodes_cb.Dispose();
         }
         handler->after_nodes_cb = Persistent<Function>::New(callback);
     } else if (callback_name == "before_ways") {
         if (!handler->before_ways_cb.IsEmpty()) {
             handler->before_ways_cb.Dispose();
         }
         handler->before_ways_cb = Persistent<Function>::New(callback);
     } else if (callback_name == "after_ways") {
         if (!handler->after_ways_cb.IsEmpty()) {
             handler->after_ways_cb.Dispose();
         }
         handler->after_ways_cb = Persistent<Function>::New(callback);
     } else if (callback_name == "before_relations") {
         if (!handler->before_relations_cb.IsEmpty()) {
             handler->before_relations_cb.Dispose();
         }
         handler->before_relations_cb = Persistent<Function>::New(callback);
     } else if (callback_name == "after_relations") {
         if (!handler->after_relations_cb.IsEmpty()) {
             handler->after_relations_cb.Dispose();
         }
         handler->after_relations_cb = Persistent<Function>::New(callback);
     } else if (callback_name == "done") {
         if (!handler->done_cb.IsEmpty()) {
             handler->done_cb.Dispose();
         }
         handler->done_cb = Persistent<Function>::New(callback);
     }
     return scope.Close(Undefined());
 }
Esempio n. 20
0
static JSVAL log(JSARGS args) {
	HandleScope scope;
	String::AsciiValue s(args[0]);
	fprintf(stdout, "%s\n", *s);
	return Undefined();
}
Esempio n. 21
0
/**
 * @function net.sendfile
 * 
 * ### Synopsis
 * 
 * net.sendFile(sock, path);
 * net.sendFile(sock, path, offset);
 * net.sendFile(sock, path, offset, size);
 * 
 * This function calls the OS sendfile() function to send a complete or partial file to the network entirely within kernel space.  It is a HUGE speed win for HTTP and FTP type servers.
 * 
 * @param {int} sock - file descriptor of socket to send the file to.
 * @param {string} path - file system path to file to send.
 * @param {int} offset - offset from beginning of file to send (for partial).  If omitted, the entire file is sent.
 * @param {int} size - number of bytes of the file to send.  If omitted, the remainder of the file is sent (or all of it).
 * 
 * ### Exceptions
 * An exception is thrown if the file cannot be opened or if there is a sendfile(2) OS call error.
 */
 static JSVAL net_sendfile (JSARGS args) {
    HandleScope handle_scope;
    int sock = args[0]->IntegerValue();
    String::AsciiValue filename(args[1]);
    off_t offset = 0;
    if (args.Length() > 2) {
        offset = args[2]->IntegerValue();
    }
    size_t size;
    if (args.Length() > 3) {
        size = args[3]->IntegerValue();
    }
    else 
	{
        struct stat buf;
        if (stat(*filename, &buf)) 
		{
            printf("%s\n", *filename);
            perror("SendFile stat");
			{ FILE* fp=fopen("c:\\error.txt", "a+b"); fprintf(fp, "%d", __LINE__); fclose(fp); }
            return handle_scope.Close(False());
        }
        size = buf.st_size - offset;
    }

#ifdef WIN32
	HANDLE fd = CreateFile(*filename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN | FILE_ATTRIBUTE_NORMAL, NULL);
    if (fd == INVALID_HANDLE_VALUE) {
#else
    int fd = open(*filename, O_RDONLY);
    if (fd < 0) {
#endif
        return ThrowException(String::Concat(String::New("sendFile open Error: "), String::New(strerror(errno))));
    }

    while (size > 0) {
#ifdef __APPLE__
        off_t count = size;
        if (sendfile(fd, sock, offset, &count, NULL, 0) == -1) {
            close(fd);
            return ThrowException(String::Concat(String::New("sendFile Error: "), String::New(strerror(errno))));
        }
#else
#ifdef WIN32
		SetFilePointer(fd, offset, NULL, FILE_BEGIN);
		TransmitFile(sock, fd, size, 0, NULL, NULL,0);
		ssize_t count = size;
        if (count == -1) {
            CloseHandle(fd);
            return ThrowException(String::Concat(String::New("sendFile Error: "), String::New(strerror(errno))));
        }
#else
        ssize_t count = sendfile(sock, fd, &offset, size);
        if (count == -1) {
            close(fd);
            return ThrowException(String::Concat(String::New("sendFile Error: "), String::New(strerror(errno))));
        }
#endif
#endif
        size -= count;
        offset += count;
    }
#ifdef WIN32
	CloseHandle(fd);
    int flag = 0;
    setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (char*)&flag, sizeof (flag));
    flag = 1;
    setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (char*)&flag, sizeof (flag));
#else
    close(fd);
    int flag = 0;
    setsockopt(fd, IPPROTO_TCP, TCP_CORK, &flag, sizeof (flag));
    flag = 1;
    setsockopt(fd, IPPROTO_TCP, TCP_CORK, &flag, sizeof (flag));
#endif

    return Undefined();
}

void init_net_object () {
    HandleScope scope;

    Handle<ObjectTemplate>net = ObjectTemplate::New();
    net->Set(String::New("connect"), FunctionTemplate::New(net_connect));
    net->Set(String::New("listen"), FunctionTemplate::New(net_listen));
    net->Set(String::New("accept"), FunctionTemplate::New(net_accept));
    net->Set(String::New("remote_addr"), FunctionTemplate::New(net_remote_addr));
    net->Set(String::New("cork"), FunctionTemplate::New(net_cork));
    net->Set(String::New("close"), FunctionTemplate::New(net_close));
    net->Set(String::New("read"), FunctionTemplate::New(net_read));
    net->Set(String::New("write"), FunctionTemplate::New(net_write));
    net->Set(String::New("writeBuffer"), FunctionTemplate::New(net_writebuffer));
    net->Set(String::New("sendFile"), FunctionTemplate::New(net_sendfile));

	net->Set(String::New("duplicateSocket"), FunctionTemplate::New(net_duplicateSocket));
	net->Set(String::New("getSocketDescriptor"), FunctionTemplate::New(net_getSocketDescriptor));

    builtinObject->Set(String::New("net"), net);
}
Esempio n. 22
0
static JSVAL close(JSARGS args) {
    redisContext *c = (redisContext *)JSOPAQUE(args[0]);
    redisFree(c);
    return Undefined();
}
Esempio n. 23
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();
}
Esempio n. 24
0
Handle<Value>
DNSServiceResolve(Arguments const& args) {
    HandleScope scope;

    if (argumentCountMismatch(args, 8)) {
        return throwArgumentCountMismatchException(args, 8);
    }

    if ( ! ServiceRef::HasInstance(args[0])) {
        return throwTypeError("argument 1 must be a DNSServiceRef (sdRef)");
    }
    ServiceRef * serviceRef = ObjectWrap::Unwrap<ServiceRef>(args[0]->ToObject());
    if (serviceRef->IsInitialized()) {
        return throwError("DNSServiceRef is already initialized");
    }

    if ( ! args[1]->IsInt32()) {
        return throwError("argument 2 must be an integer (DNSServiceFlags)");
    }
    DNSServiceFlags flags = args[1]->ToInteger()->Int32Value();

    if ( ! args[2]->IsInt32()) {
        return throwTypeError("argument 3 must be an integer (interfaceIndex)");
    }
    uint32_t interfaceIndex = args[2]->ToInteger()->Int32Value();

    if ( ! args[3]->IsString()) {
        return throwTypeError("argument 4 must be a string (name)");
    }
    String::Utf8Value name(args[3]->ToString());

    if ( ! args[4]->IsString()) {
        return throwTypeError("argument 5 must be a string (service type)");
    }
    String::Utf8Value serviceType(args[4]->ToString());

    if ( ! args[5]->IsString()) {
        return throwTypeError("argument 6 must be a string (domain)");
    }
    String::Utf8Value domain(args[5]->ToString());

    if ( ! args[6]->IsFunction()) {
        return throwTypeError("argument 7 must be a function (callBack)");
    }
    serviceRef->SetCallback(Local<Function>::Cast(args[6]));

    if ( ! args[7]->IsNull() && ! args[7]->IsUndefined()) {
        serviceRef->SetContext(args[7]);
    }

    DNSServiceErrorType error = DNSServiceResolve( & serviceRef->GetServiceRef(),
            flags, interfaceIndex, *name, *serviceType, *domain, OnResolve, serviceRef);

    if (error != kDNSServiceErr_NoError) {
        return throwMdnsError("DNSServiceResolve()", error);
    }
    if ( ! serviceRef->SetSocketFlags()) {
        return throwError("Failed to set socket flags (O_NONBLOCK, FD_CLOEXEC)");
    }

    return Undefined();
}
Esempio n. 25
0
 Handle<Value> MSUnloadScene(const Arguments& args)
 {
    dtEntity::MapSystem* ms = UnwrapMapSystem(args.This());
    ms->UnloadScene();
    return Undefined();
 }   
Handle<Value> TiProxy::createProxy(void*, TiObject*, const Arguments&)
{
	// for subclass;
	return Undefined();
}
Esempio n. 27
0
 Handle<Value> MSDeleteEntitiesByMap(const Arguments& args)
 {
    dtEntity::MapSystem* ms = UnwrapMapSystem(args.This());
    ms->DeleteEntitiesByMap(ToStdString(args[0]));
    return Undefined();
 }   
Esempio n. 28
0
static Handle<Value> load(const Arguments& args)
{
    const char* file = *String::Utf8Value(args[0]);
    Script::load(file);
    return Undefined();
}
Esempio n. 29
0
static JSVAL gc(const Arguments& args) {
	HandleScope scope;
	while (!V8::IdleNotification()) {}
	return Undefined();
}
Esempio n. 30
0
Local<Value> Arguments::operator[](int i) const {
    if ((0 <= i) && (i < Length())) {
        return Local<Value>::New(argv_[i]);
    }
    return Local<Value>::New(Undefined());
}