예제 #1
0
/* zipfile.replaceFile(nameInArchive, name, offset, len) */
Handle<Value> ZipFile::Replace_File(const Arguments& args)
{
    ZipFile* zf = ObjectWrap::Unwrap<ZipFile>(args.This());

    struct zip_source *source;

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

    if (!args[0]->IsString())
      return ThrowException(Exception::TypeError(
                 String::New("Argument must be a file name.")));
    std::string archive_file = TOSTR(args[0]);

    std::string name;
    if (args[1]->IsUndefined())
      name = archive_file;
    else
      if (!args[1]->IsString())
        return ThrowException(Exception::TypeError(
                   String::New("Argument must be a file name.")));
      name = TOSTR(args[1]);

    zip_int64_t off;
    if (args[2]->IsUndefined())
      off = 0;
    else
      off = args[2]->Int32Value();
    
    zip_int64_t len; 
    if (args[3]->IsUndefined()) 
      len = -1; 
    else 
      len = args[3]->Int32Value();

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

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

    source = zip_source_file(zf->archive, name.c_str(), off, len);
    if (source == NULL) {
      std::stringstream s;
      s << "Error while replacing file " << name << " in zip archive: " << zip_strerror(zf->archive) << "\n";
      return ThrowException(Exception::Error(String::New(s.str().c_str())));
    }

    int ret = zip_replace(zf->archive, idx, source);        
    if (ret < 0) {
      zip_source_free(source);
      std::stringstream s;
      s << "Error while replacing file " << name << " in zip archive: " << zip_strerror(zf->archive) << "\n";
      return ThrowException(Exception::Error(String::New(s.str().c_str())));
    }

    return Undefined();
}
예제 #2
0
Handle<Value> HoneydProfileBinding::Save(const Arguments& args)
{

    if(args.Length() != 2)
    {
      return ThrowException(Exception::TypeError(String::New("Must be invoked with at exactly two parameters")));
    }
    
	HandleScope scope;
	HoneydProfileBinding* obj = ObjectWrap::Unwrap<HoneydProfileBinding>(args.This());

	std::string oldName = cvv8::CastFromJS<std::string>(args[0]);
	
	bool addOrEdit = cvv8::CastFromJS<bool>(args[1]);

	HoneydConfiguration *conf = new HoneydConfiguration();

	conf->LoadAllTemplates();
	
	if(addOrEdit)
	{
		conf->AddProfile(obj->m_pfile);
	}
	else
	{
		conf->m_profiles[oldName].SetTcpAction(obj->m_pfile->m_tcpAction);
		conf->m_profiles[oldName].SetUdpAction(obj->m_pfile->m_udpAction);
		conf->m_profiles[oldName].SetIcmpAction(obj->m_pfile->m_icmpAction);
		conf->m_profiles[oldName].SetPersonality(obj->m_pfile->m_personality);
		
		conf->m_profiles[oldName].SetUptimeMin(obj->m_pfile->m_uptimeMin);
		conf->m_profiles[oldName].SetUptimeMax(obj->m_pfile->m_uptimeMax);
		
		conf->m_profiles[oldName].SetDropRate(obj->m_pfile->m_dropRate);
		conf->m_profiles[oldName].SetParentProfile(obj->m_pfile->m_parentProfile);
		
		conf->m_profiles[oldName].SetVendors(obj->m_pfile->m_ethernetVendors);
		
		conf->m_profiles[oldName].setTcpActionInherited(obj->m_pfile->isTcpActionInherited());
		conf->m_profiles[oldName].setUdpActionInherited(obj->m_pfile->isUdpActionInherited());
		conf->m_profiles[oldName].setIcmpActionInherited(obj->m_pfile->isIcmpActionInherited());
		conf->m_profiles[oldName].setPersonalityInherited(obj->m_pfile->isPersonalityInherited());
		conf->m_profiles[oldName].setEthernetInherited(obj->m_pfile->isEthernetInherited());
		conf->m_profiles[oldName].setUptimeInherited(obj->m_pfile->isUptimeInherited());
		conf->m_profiles[oldName].setDropRateInherited(obj->m_pfile->isDropRateInherited());
		
		conf->m_profiles[oldName].SetGenerated(obj->m_pfile->m_generated);
		conf->m_profiles[oldName].SetDistribution(obj->m_pfile->m_distribution);
	
		std::vector<std::string> portNames = conf->m_profiles[oldName].GetPortNames();
	
		for(uint i = 0; i < obj->m_pfile->m_ports.size(); i++)
		{
			bool push = true;
		
			for(uint j = 0; j < portNames.size(); j++)
			{
				if(!portNames[j].compare(obj->m_pfile->m_ports[i].first))
				{
					push = false;
				}
			}
			
			if(push)
			{
				conf->m_profiles[oldName].m_ports.push_back(obj->m_pfile->m_ports[i]);
				push = false;
			}
		}
		
		conf->UpdateProfile("default");
		
		if(!conf->RenameProfile(oldName, obj->m_pfile->m_name))
		{
			std::cout << "Couldn't rename profile " << oldName << " to " << obj->m_pfile->m_name << std::endl;
		}
	}
	
	conf->SaveAllTemplates();

	delete conf;
	
	return scope.Close(Boolean::New(true));
}
예제 #3
0
Handle<Value> ZipFile::readFileSync(const Arguments& args)
{
    HandleScope scope;

    if (args.Length() != 1 || !args[0]->IsString())
        return ThrowException(Exception::TypeError(
          String::New("first 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..")));

    struct zip_file *zf_ptr;

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

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

    struct zip_stat st;
    zip_stat_index(zf->archive, idx, 0, &st);
  
    std::vector<unsigned char> data;
    data.clear();
    data.resize( st.size );
    
    int result =  0;
    result = (int)zip_fread( zf_ptr, reinterpret_cast<void*> (&data[0]), data.size() );

    if (result < 0) {
        zip_fclose(zf_ptr);
        std::stringstream s;
        s << "error reading file #" << idx << " in " << name << ": archive error: " << zip_file_strerror(zf_ptr) << "\n";
        return ThrowException(Exception::Error(String::New(s.str().c_str())));
    }

    #if NODE_VERSION_AT_LEAST(0,3,0)
        node::Buffer *retbuf = Buffer::New((char *)&data[0],data.size());
    #else
        node::Buffer *retbuf = Buffer::New(data.size());
        std::memcpy(retbuf->data(), (char *)&data[0], data.size());
    #endif
    
    zip_fclose(zf_ptr);
    return scope.Close(retbuf->handle_);
}
예제 #4
0
Handle<Value>
NodeSandbox::node_spawn(const Arguments& args)
{
  HandleScope scope;
  char** argv;
  std::map<std::string, std::string> envp;
  SandboxWrapper* wrap;

  wrap = node::ObjectWrap::Unwrap<SandboxWrapper>(args.This());
  argv = static_cast<char**>(calloc (sizeof (char*), args.Length()+1));
  argv[args.Length()] = nullptr;

  for(int i = 0; i < args.Length(); i++) {
    if (args[i]->IsString()) {
      Local<String> v = args[i]->ToString();
      argv[i] = static_cast<char*>(calloc(sizeof(char), v->Utf8Length()+1));
      v->WriteUtf8(argv[i]);
    } else {
      if (i <= args.Length() - 2 ) {
        ThrowException(Exception::TypeError(String::New("Arguments must be strings.")));
        goto out;
      } else {
        // Last parameter is an options structure
        Local<Object> options = args[i]->ToObject();
        if (!options.IsEmpty()) {
          if (options->HasRealNamedProperty(String::NewSymbol("env"))) {
            Local<Object> envOptions = options->Get(String::NewSymbol("env"))->ToObject();
            if (!envOptions.IsEmpty()) {
              Local<Array> envArray = envOptions->GetOwnPropertyNames();
              for (uint32_t i = 0; i < envArray->Length(); i++) {
                std::vector<char> strName;
                std::vector<char> strValue;
                Local<String> envName;
                Local<String> envValue;

                if (!(envArray->Get(i)->IsString() && envArray->Get(i)->IsString()))
                  goto err_env;

                envName = envArray->Get(i)->ToString();
                envValue = envOptions->Get(envName)->ToString();

                strName.resize (envName->Utf8Length()+1);
                strValue.resize (envValue->Utf8Length()+1);
                envName->WriteUtf8 (strName.data());
                envValue->WriteUtf8 (strValue.data());
                envp.insert (std::make_pair(std::string (strName.data()), std::string(strValue.data())));
              }
            } else {
              goto err_env;
            }
          }
        } else {
          goto err_options;
        }
      }
    }
  }

  wrap->sbox->getVFS().setCWD ("/contract/");
  wrap->sbox->spawn(argv, envp);

  goto out;

err_env:
  ThrowException(Exception::TypeError(String::New("'env' option must be a map of string:string")));
  goto out;

err_options:
  ThrowException(Exception::TypeError(String::New("Last argument must be an options structure.")));
  goto out;

out:
  for (int i = 0; i < args.Length();i ++) {
    free (argv[i]);
  }
  free (argv);

  return Undefined();
}
예제 #5
0
Handle<Value> Grid::encode(const Arguments& args) // format, resolution
{
    HandleScope scope;

    Grid* g = ObjectWrap::Unwrap<Grid>(args.This());

    // defaults
    std::string format("utf");
    unsigned int resolution = 4;
    bool add_features = true;

    // accept custom format
    if (args.Length() >= 1){
        if (!args[0]->IsString())
            return ThrowException(Exception::TypeError(
                                      String::New("first arg, 'format' must be a string")));
        format = TOSTR(args[0]);
    }

    // options hash
    if (args.Length() >= 2) {
        if (!args[1]->IsObject())
            return ThrowException(Exception::TypeError(
                                      String::New("optional second arg must be an options object")));

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

        if (options->Has(String::New("resolution")))
        {
            Local<Value> bind_opt = options->Get(String::New("resolution"));
            if (!bind_opt->IsNumber())
                return ThrowException(Exception::TypeError(
                                          String::New("'resolution' must be an Integer")));

            resolution = bind_opt->IntegerValue();
        }

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

            add_features = bind_opt->BooleanValue();
        }
    }

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

    encode_grid_baton_t *closure = new encode_grid_baton_t();
    closure->request.data = closure;
    closure->g = g;
    closure->format = format;
    closure->error = false;
    closure->resolution = resolution;
    closure->add_features = add_features;
    closure->cb = Persistent<Function>::New(Handle<Function>::Cast(callback));
    // todo - reserve lines size?
    uv_queue_work(uv_default_loop(), &closure->request, EIO_Encode, EIO_AfterEncode);
    uv_ref(uv_default_loop());
    g->Ref();
    return Undefined();
}
예제 #6
0
Handle<Value> WKTWriter::SetRoundingPrecision(const Arguments& args) {
    WKTWriter *writer = ObjectWrap::Unwrap<WKTWriter>(args.This());
    writer->_writer->setRoundingPrecision(args[0]->Int32Value());
    return Undefined();
}
예제 #7
0
Handle<Value> Window::Drag(const Arguments& args) {
  HandleScope scope;
  NativeWindow *window = ObjectWrap::Unwrap<NativeWindow> (args.This());
  window->Drag();
  return scope.Close(args.This());
}
예제 #8
0
/* static  */
Handle<Value> MemoryObject::New(const Arguments& args)
{
    HandleScope scope;
    MemoryObject *cl = new MemoryObject(args.This());
    return args.This();
}
예제 #9
0
Handle<Value> Database::Query(const Arguments& args) {
  HandleScope scope;

  REQ_STR_ARG(0, sql);
  
  Local<Function> cb; 
  
  int paramCount = 0;
  Parameter* params;

  Database* dbo = ObjectWrap::Unwrap<Database>(args.This());

  struct query_request *prep_req = (struct query_request *)
    calloc(1, sizeof(struct query_request));

  if (!prep_req) {
    V8::LowMemoryNotification();
    return ThrowException(Exception::Error(String::New("Could not allocate enough memory")));
  }

  // populate prep_req->params if parameters were supplied
  //
  if (args.Length() > 2) 
  {
      if ( !args[1]->IsArray() )
      {
           return ThrowException(Exception::TypeError(
                      String::New("Argument 1 must be an Array"))
           );
      }
      else if ( !args[2]->IsFunction() )
      {
           return ThrowException(Exception::TypeError(
                      String::New("Argument 2 must be a Function"))
           );
      }
  

      Local<Array> values = Local<Array>::Cast(args[1]);
      cb = Local<Function>::Cast(args[2]);

      prep_req->paramCount = paramCount = values->Length();
      prep_req->params     = params     = new Parameter[paramCount];

      for (int i = 0; i < paramCount; i++)
      {
          Local<Value> value = values->Get(i);

          params[i].size          = 0;
          params[i].length        = NULL;
          params[i].buffer_length = 0;

          if (value->IsString()) 
          {
              String::Utf8Value string(value);
              
              params[i].c_type        = SQL_C_CHAR;
              params[i].type          = SQL_VARCHAR;
              params[i].length        = SQL_NTS;
              params[i].buffer        = malloc(string.length() + 1);
              params[i].buffer_length = string.length() + 1;
              params[i].size          = string.length() + 1;

              strcpy((char*)params[i].buffer, *string);
          }
          else if (value->IsNull()) 
          {
              params[i].c_type = SQL_C_DEFAULT;
              params[i].type   = SQL_NULL_DATA;
              params[i].length = SQL_NULL_DATA;
          }
          else if (value->IsInt32()) 
          {
              int64_t  *number = new int64_t(value->IntegerValue());
              params[i].c_type = SQL_C_LONG;
              params[i].type   = SQL_INTEGER;
              params[i].buffer = number; 
          }
          else if (value->IsNumber()) 
          {
              double   *number = new double(value->NumberValue());
              params[i].c_type = SQL_C_DOUBLE;
              params[i].type   = SQL_DECIMAL;
              params[i].buffer = number; 
          }
          else if (value->IsBoolean()) 
          {
              bool *boolean    = new bool(value->BooleanValue());
              params[i].c_type = SQL_C_BIT;
              params[i].type   = SQL_BIT;
              params[i].buffer = boolean;
          }
      }
  }
  else 
  {
      if ( !args[1]->IsFunction() )
      {
           return ThrowException(Exception::TypeError(
                      String::New("Argument 1 must be a Function"))
           );
      }

      cb = Local<Function>::Cast(args[1]);

      prep_req->paramCount = 0;
  }

  prep_req->sql = (char *) malloc(sql.length() +1);
  prep_req->catalog = NULL;
  prep_req->schema = NULL;
  prep_req->table = NULL;
  prep_req->type = NULL;
  prep_req->column = NULL;
  prep_req->cb = Persistent<Function>::New(cb);
  
  strcpy(prep_req->sql, *sql);
  
  prep_req->dbo = dbo;

  eio_custom(EIO_Query, EIO_PRI_DEFAULT, EIO_AfterQuery, prep_req);

  ev_ref(EV_DEFAULT_UC);
  dbo->Ref();
  scope.Close(Undefined());
  return Undefined();
}
예제 #10
0
// ([streams], cb(stream, frame))
Handle<Value> NAVFormat::Decode(const Arguments& args) {
  HandleScope scope;
  Local<Array> streams;
  Local<Function> callback;
  
  StreamFrame streamFrames[MAX_NUM_STREAMFRAMES];
  
  if(!(args[0]->IsArray())){
    return ThrowException(Exception::TypeError(String::New("First parameter must be an array")));
  }  
  if(!(args[1]->IsFunction())){
    return ThrowException(Exception::TypeError(String::New("Second parameter must be a funcion")));
  }
  
  Local<Object> self = args.This();
  
  NAVFormat* instance = UNWRAP_OBJECT(NAVFormat, args);
  
  streams = Local<Array>::Cast(args[0]);
  callback = Local<Function>::Cast(args[1]);
 
  //
  // Create the required frames and associate every frame to a stream.
  // And open codecs.
  //
  for(unsigned int i=0;i<streams->Length(); i++){
    AVStream *pStream;
  
    Handle<Object> stream = streams->Get(i)->ToObject();
    streamFrames[i].stream = Persistent<Object>::New(stream);
    
    pStream = node::ObjectWrap::Unwrap<NAVStream>(streamFrames[i].stream)->pContext;
    
    streamFrames[i].pStream = pStream;
    streamFrames[i].pFrame = avcodec_alloc_frame();

    Handle<Object> frame = NAVFrame::New(streamFrames[i].pFrame);
    
    streamFrames[i].frame = Persistent<Object>::New(frame);
    
    AVCodecContext *pCodecCtx = streamFrames[i].pStream->codec;
    
    AVCodec *pCodec=avcodec_find_decoder(pCodecCtx->codec_id);
    if(pCodec==NULL){
      return ThrowException(Exception::Error(String::New("Could not find decoder!")));
    }
    
    if(avcodec_open2(pCodecCtx, pCodec, NULL)<0){
      return ThrowException(Exception::Error(String::New("Could not open decoder!")));
    }
  }
  
  //
  // Start decoding
  //
  
  Baton* pBaton = new Baton();
  
  pBaton->navformat = Persistent<Object>::New(self);
  pBaton->pFormatCtx = instance->pFormatCtx;
  pBaton->numStreams = streams->Length();
  
  memcpy((void*)&(pBaton->streamFrames), (void*)&streamFrames, sizeof(streamFrames));
  
  pBaton->notifier = Persistent<Object>::New(DecoderNotifier::New(pBaton));
  
  pBaton->request.data = pBaton;
  
  pBaton->callback = Persistent<Function>::New(callback);
  
  uv_queue_work(uv_default_loop(), 
                &pBaton->request,
                AsyncWork, 
                (uv_after_work_cb)AsyncAfter);

  return Undefined();
}
예제 #11
0
파일: rot13.cpp 프로젝트: jedp/node-rot13
 static Handle<Value> New(const Arguments &args)
 {
     Rot13 *rot13 = new Rot13();
     rot13->Wrap(args.This());
     return args.This();
 }
예제 #12
0
Handle<Value> LineStringPoints::add(const Arguments& args)
{
	HandleScope scope;

	Handle<Object> parent = args.This()->GetHiddenValue(String::NewSymbol("parent_"))->ToObject();
	LineString *geom = ObjectWrap::Unwrap<LineString>(parent);

	int n = args.Length();

	if(n == 0) {
		return NODE_THROW("Point must be given");
	} else if(n == 1) {
		if(!args[0]->IsObject()) {
			return NODE_THROW("Point, object, or array of points expected");
		}
		if(IS_WRAPPED(args[0], Point)){
			//set from Point object
			Point* pt = ObjectWrap::Unwrap<Point>(args[0]->ToObject());
			geom->get()->addPoint(pt->get());
		} else if (args[0]->IsArray()) {
			//set from array of points
			Handle<Array> array = Handle<Array>::Cast(args[0]);
			int length = array->Length();
			for (int i = 0; i < length; i++){
				Handle<Value> element = array->Get(i);
				if(!element->IsObject()) {
					return NODE_THROW("All points must be Point objects or objects");
				}
				Handle<Object> element_obj = element->ToObject();
				if(IS_WRAPPED(element_obj, Point)){
					//set from Point object
					Point* pt = ObjectWrap::Unwrap<Point>(element_obj);
					geom->get()->addPoint(pt->get());
				} else {
					//set from object {x: 0, y: 5}
					double x, y;
					NODE_DOUBLE_FROM_OBJ(element_obj, "x", x);
					NODE_DOUBLE_FROM_OBJ(element_obj, "y", y);

					Handle<String> z_prop_name = String::NewSymbol("z");
					if (element_obj->HasOwnProperty(z_prop_name)) {
						Handle<Value> z_val = element_obj->Get(z_prop_name);
						if (!z_val->IsNumber()) {
							return NODE_THROW("z property must be number");
						}
						geom->get()->addPoint(x, y, z_val->NumberValue());
					} else {
						geom->get()->addPoint(x, y);
					}
				}
			}
		} else {
			//set from object {x: 0, y: 5}
			Handle<Object> obj = args[0]->ToObject();
			double x, y;
			NODE_DOUBLE_FROM_OBJ(obj, "x", x);
			NODE_DOUBLE_FROM_OBJ(obj, "y", y);

			Handle<String> z_prop_name = String::NewSymbol("z");
			if (obj->HasOwnProperty(z_prop_name)) {
				Handle<Value> z_val = obj->Get(z_prop_name);
				if (!z_val->IsNumber()) {
					return NODE_THROW("z property must be number");
				}
				geom->get()->addPoint(x, y, z_val->NumberValue());
			} else {
				geom->get()->addPoint(x, y);
			}
		}
	} else {
		//set x, y, z from numeric arguments
		if(!args[0]->IsNumber()){
			return NODE_THROW("Number expected for first argument");
		}
		if(!args[1]->IsNumber()){
			return NODE_THROW("Number expected for second argument");
		}
		if(n == 2){
			geom->get()->addPoint(args[0]->NumberValue(), args[1]->NumberValue());
		} else {
			if(!args[2]->IsNumber()){
				return NODE_THROW("Number expected for third argument");
			}

			geom->get()->addPoint(args[0]->NumberValue(), args[1]->NumberValue(), args[2]->NumberValue());
		}
	}

	return Undefined();
}
예제 #13
0
Handle<Value> LineStringPoints::set(const Arguments& args)
{
	HandleScope scope;

	Handle<Object> parent = args.This()->GetHiddenValue(String::NewSymbol("parent_"))->ToObject();
	LineString *geom = ObjectWrap::Unwrap<LineString>(parent);

	int i;
	NODE_ARG_INT(0, "index", i);
	if(i < 0 || i >= geom->get()->getNumPoints()) {
		return NODE_THROW("Point index out of range");
	}

	int n = args.Length() - 1;

	if(n == 0) {
		return NODE_THROW("Point must be given");
	} else if(n == 1) {
		if(!args[1]->IsObject()) {
			return NODE_THROW("Point or object expected for second argument");
		}
		if(IS_WRAPPED(args[1], Point)){
			//set from Point object
			Point* pt = ObjectWrap::Unwrap<Point>(args[1]->ToObject());
			geom->get()->setPoint(i, pt->get());
		} else {
			Handle<Object> obj = args[1]->ToObject();
			//set from object {x: 0, y: 5}
			double x, y;
			NODE_DOUBLE_FROM_OBJ(obj, "x", x);
			NODE_DOUBLE_FROM_OBJ(obj, "y", y);

			Handle<String> z_prop_name = String::NewSymbol("z");
			if (obj->HasOwnProperty(z_prop_name)) {
				Handle<Value> z_val = obj->Get(z_prop_name);
				if (!z_val->IsNumber()) {
					return NODE_THROW("z property must be number");
				}
				geom->get()->setPoint(i, x, y, z_val->NumberValue());
			} else {
				geom->get()->setPoint(i, x, y);
			}
		}
	} else {
		//set x, y, z from numeric arguments
		if(!args[1]->IsNumber()){
			return NODE_THROW("Number expected for second argument");
		}
		if(!args[2]->IsNumber()){
			return NODE_THROW("Number expected for third argument");
		}
		if(n == 2){
			geom->get()->setPoint(i, args[1]->NumberValue(), args[2]->NumberValue());
		} else {
			if(!args[3]->IsNumber()){
				return NODE_THROW("Number expected for fourth argument");
			}

			geom->get()->setPoint(i, args[1]->NumberValue(), args[2]->NumberValue(), args[3]->NumberValue());
		}
	}

	return Undefined();
}
예제 #14
0
Handle<Value> Grid::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();
        Grid* g =  static_cast<Grid*>(ptr);
        g->Wrap(args.This());
        return args.This();
    }

    if (args.Length() >= 2)
    {
        if (!args[0]->IsNumber() || !args[1]->IsNumber())
            return ThrowException(Exception::TypeError(
                                      String::New("Grid 'width' and 'height' must be a integers")));

        // defaults
        std::string key("__id__");
        unsigned int resolution = 1;

        if (args.Length() >= 3) {

            if (!args[2]->IsObject())
                return ThrowException(Exception::TypeError(
                                          String::New("optional third arg must be an options object")));
            Local<Object> options = args[2]->ToObject();

            if (options->Has(String::New("key"))) {
                Local<Value> bind_opt = options->Get(String::New("key"));
                if (!bind_opt->IsString())
                    return ThrowException(Exception::TypeError(
                                              String::New("optional arg 'key' must be an string")));

                key = TOSTR(bind_opt);
            }
            // TODO - remove, deprecated
            if (options->Has(String::New("resolution"))) {
                Local<Value> bind_opt = options->Get(String::New("resolution"));
                if (!bind_opt->IsNumber())
                    return ThrowException(Exception::TypeError(
                                              String::New("optional arg 'resolution' must be an string")));

                resolution = bind_opt->IntegerValue();
            }
        }

        Grid* g = new Grid(args[0]->IntegerValue(),args[1]->IntegerValue(),key,resolution);
        g->Wrap(args.This());
        return args.This();
    }
    else
    {
        return ThrowException(Exception::Error(
                                  String::New("please provide Grid width and height")));
    }
    return Undefined();
}
예제 #15
0
Handle<Value> QuaternionToString(const Arguments& args) {
    Handle<Object> self = args.This();
    QuaternionCheckAndExtract(self_val, self);
    String self_val_str = self_val.toString();
    return v8::String::New( self_val_str.c_str(), self_val_str.size() );
}
예제 #16
0
Handle<Value> Connection::SetAutoCommit(const Arguments& args) {
  Connection* connection = ObjectWrap::Unwrap<Connection>(args.This());
  REQ_BOOL_ARG(0, autoCommit);
  connection->m_autoCommit = autoCommit;
  return Undefined();
}
예제 #17
0
Handle<Value> WKTWriter::New(const Arguments& args) {
    HandleScope scope;
    WKTWriter* writer = new WKTWriter();
    writer->Wrap(args.This());
    return args.This();
}
예제 #18
0
Handle<Value> App::New(const Arguments& args) {
  HandleScope scope;
  App* obj = new App();
  obj->Wrap(args.This());
  return scope.Close(args.This());
}
예제 #19
0
Handle<Value> WKTWriter::SetTrim(const Arguments& args) {
    WKTWriter *writer = ObjectWrap::Unwrap<WKTWriter>(args.This());
    writer->_writer->setTrim(args[0]->BooleanValue());
    return Undefined();
}
예제 #20
0
Handle<Value> Query::New(Arguments const& args)
{
    HandleScope scope;
    if (!args.IsConstructCall()) {
        return ThrowException(Exception::Error(String::New("Cannot call constructor as function, you need to use 'new' keyword")));
    }
    try {
        if (args.Length() != 1) {
            return ThrowException(Exception::TypeError(String::New("please provide an object of options for the first argument")));
        }
        if (!args[0]->IsObject()) {
            return ThrowException(Exception::TypeError(String::New("first argument must be an object")));
        }
        Local<Object> obj = args[0]->ToObject();
        if (obj->IsNull() || obj->IsUndefined()) {
            return ThrowException(Exception::TypeError(String::New("first arg must be an object")));
        }
        if (!obj->Has(String::New("coordinates"))) {
            return ThrowException(Exception::TypeError(String::New("must provide a coordinates property")));
        }
        Local<Value> coordinates = obj->Get(String::New("coordinates"));
        if (!coordinates->IsArray()) {
            return ThrowException(Exception::TypeError(String::New("coordinates must be an array of (lat/long) pairs")));
        }

        // Handle scenario in which caller explicitly specified service
        std::string service;
        if (obj->Has(String::New("service"))) {
            Local<Value> serviceValue = obj->Get(String::New("service"));
            v8::String::Utf8Value serviceUtf8Value(serviceValue->ToString());
            service = std::string(*serviceUtf8Value);
        }

        // Handle 'nearest', otherwise assume 'viaroute' service.
        if (service == "nearest" || service == "locate") {
            Local<Array> coordinates_array = Local<Array>::Cast(coordinates);
            if (coordinates_array->Length() != 1) {
                return ThrowException(Exception::TypeError(String::New("coordinates array should only have one lat/long pair for 'nearest' or 'locate' queries")));
            }
            Local<Value> coordinate = coordinates_array->Get(0);
            if (!coordinate->IsArray()) {
                return ThrowException(Exception::TypeError(String::New("coordinates must be an array of (lat/long) pairs")));
            }
            Local<Array> coordinate_array = Local<Array>::Cast(coordinate);
            if (coordinate_array->Length() != 2) {
                return ThrowException(Exception::TypeError(String::New("coordinates must be an array of (lat/long) pairs")));
            }

            Query* q = new Query();
            q->this_->service = service;
            q->this_->coordinates.push_back(
                FixedPointCoordinate(coordinate_array->Get(0)->NumberValue()*COORDINATE_PRECISION,
                                     coordinate_array->Get(1)->NumberValue()*COORDINATE_PRECISION));

            q->Wrap(args.This());
            return args.This();
        }


        Local<Array> coordinates_array = Local<Array>::Cast(coordinates);
        if (coordinates_array->Length() < 2) {
            return ThrowException(Exception::TypeError(String::New("at least two coordinates must be provided")));
        }

        Query* q = new Query();
        q->this_->zoomLevel = 18; //no generalization
        q->this_->printInstructions = false; //turn by turn instructions
        q->this_->alternateRoute = true; //get an alternate route, too
        q->this_->geometry = true; //retrieve geometry of route
        q->this_->compression = true; //polyline encoding
        q->this_->checkSum = UINT_MAX; //see wiki
        q->this_->service = "viaroute"; //that's routing
        q->this_->outputFormat = "json";
        q->this_->jsonpParameter = ""; //set for jsonp wrapping
        q->this_->language = ""; //unused atm

        if (obj->Has(String::New("alternateRoute"))) {
            q->this_->alternateRoute = obj->Get(String::New("alternateRoute"))->BooleanValue();
        }

        if (obj->Has(String::New("checksum"))) {
            q->this_->checkSum = static_cast<unsigned>(obj->Get(String::New("checksum"))->Uint32Value());
        }

        if (obj->Has(String::New("zoomLevel"))) {
            q->this_->zoomLevel = static_cast<short>(obj->Get(String::New("zoomLevel"))->Int32Value());
        }

        if (obj->Has(String::New("printInstructions"))) {
            q->this_->printInstructions = obj->Get(String::New("printInstructions"))->BooleanValue();
        }

        if (obj->Has(String::New("jsonpParameter"))) {
            q->this_->jsonpParameter = *v8::String::Utf8Value(obj->Get(String::New("jsonpParameter")));
        }

        if (obj->Has(String::New("hints"))) {
            Local<Value> hints = obj->Get(String::New("hints"));
            if (!hints->IsArray()) {
                return ThrowException(Exception::TypeError(String::New("hints must be an array of strings/null")));
            }
            Local<Array> hints_array = Local<Array>::Cast(hints);
            for (uint32_t i = 0; i < hints_array->Length(); ++i) {
                Local<Value> hint = hints_array->Get(i);
                if (hint->IsString()) {
                    q->this_->hints.push_back(*v8::String::Utf8Value(hint));
                } else if(hint->IsNull()){
                    q->this_->hints.push_back("");
                }else{
                    return ThrowException(Exception::TypeError(String::New("hint must be null or string")));
                }
            }
        }

        for (uint32_t i = 0; i < coordinates_array->Length(); ++i) {
            Local<Value> coordinate = coordinates_array->Get(i);
            if (!coordinate->IsArray()) {
                return ThrowException(Exception::TypeError(String::New("coordinates must be an array of (lat/long) pairs")));
            }
            Local<Array> coordinate_array = Local<Array>::Cast(coordinate);
            if (coordinate_array->Length() != 2) {
                return ThrowException(Exception::TypeError(String::New("coordinates must be an array of (lat/long) pairs")));
            }
            q->this_->coordinates.push_back(
                FixedPointCoordinate(coordinate_array->Get(0)->NumberValue()*COORDINATE_PRECISION,
                                     coordinate_array->Get(1)->NumberValue()*COORDINATE_PRECISION));
        }

        q->Wrap(args.This());
        return args.This();
    } catch (std::exception const& ex) {
        return ThrowException(Exception::TypeError(String::New(ex.what())));
    }
    return Undefined();
}
예제 #21
0
// --------------------------------------------------------
Handle<Value> NodeOpenALSource::Play(const Arguments& args) {
	HandleScope scope;
	NodeOpenALSource* obj = ObjectWrap::Unwrap<NodeOpenALSource>(args.This());
	obj->play();
	return scope.Close(v8::Undefined());
}
예제 #22
0
Handle<Value> DispObject::NodeToString(const Arguments& args)
{
	DispObject *me = DispObject::Unwrap<DispObject>(args.This());
	if (!me) return Undefined();
	return me->toString();
}
예제 #23
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();
	}

	int filename_offset = 1;
	if (context_flag == thisContext) {
		filename_offset = 0;
	}

	const int filename_index = sandbox_index + filename_offset;
	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 = WrappedContext::Unwrap(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);
			}
		}
	}

	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 == 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);
}
예제 #24
0
Handle<Value> Grid::encodeSync(const Arguments& args) // format, resolution
{
    HandleScope scope;

    Grid* g = ObjectWrap::Unwrap<Grid>(args.This());

    // defaults
    std::string format("utf");
    unsigned int resolution = 4;
    bool add_features = true;

    // accept custom format
    if (args.Length() >= 1){
        if (!args[0]->IsString())
            return ThrowException(Exception::TypeError(
                                      String::New("first arg, 'format' must be a string")));
        format = TOSTR(args[0]);
    }

    // options hash
    if (args.Length() >= 2) {
        if (!args[1]->IsObject())
            return ThrowException(Exception::TypeError(
                                      String::New("optional second arg must be an options object")));

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

        if (options->Has(String::New("resolution")))
        {
            Local<Value> bind_opt = options->Get(String::New("resolution"));
            if (!bind_opt->IsNumber())
                return ThrowException(Exception::TypeError(
                                          String::New("'resolution' must be an Integer")));

            resolution = bind_opt->IntegerValue();
        }

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

            add_features = bind_opt->BooleanValue();
        }
    }

    try {

        boost::ptr_vector<uint16_t> lines;
        std::vector<mapnik::grid::lookup_type> key_order;
        node_mapnik::grid2utf<mapnik::grid>(*g->get(),lines,key_order,resolution);

        // convert key order to proper javascript array
        Local<Array> keys_a = Array::New(key_order.size());
        std::vector<std::string>::iterator it;
        unsigned int i;
        for (it = key_order.begin(), i = 0; it < key_order.end(); ++it, ++i)
        {
            keys_a->Set(i, String::New((*it).c_str()));
        }

        mapnik::grid const& grid_type = *g->get();

        // gather feature data
        Local<Object> feature_data = Object::New();
        if (add_features) {
            node_mapnik::write_features<mapnik::grid>(*g->get(),
                                                      feature_data,
                                                      key_order);
        }

        // Create the return hash.
        Local<Object> json = Object::New();
        Local<Array> grid_array = Array::New();
        unsigned array_size = static_cast<unsigned int>(grid_type.width()/resolution);
        for (unsigned j=0;j<lines.size();++j)
        {
            grid_array->Set(j,String::New(&lines[j],array_size));
        }
        json->Set(String::NewSymbol("grid"), grid_array);
        json->Set(String::NewSymbol("keys"), keys_a);
        json->Set(String::NewSymbol("data"), feature_data);
        return json;

    }
    catch (std::exception & ex)
    {
        return ThrowException(Exception::Error(
                                  String::New(ex.what())));
    }
}