示例#1
0
std::string ArgsParser::selectStatement( const Args& selection ) const
{
  std::vector<bool> found( margs.size(), false );

  for ( Args::const_iterator o = selection.begin();
        o != selection.end(); ++o )
  {
    for ( uint i = 0; i < margs.size(); ++i )
    {
      if ( (*o)->inherits( margs[i].type ) && !found[i] )
      {
        // object o is of a type that we're looking for
        found[i] = true;
        break;
      }
    }
  }
  for ( uint i = 0; i < margs.size(); ++i )
  {
    if ( !found[i] )
      return margs[i].selectstat;
  }
  kdDebug() << k_funcinfo << "no proper select statement found :(" << endl;
  return 0;
}
        //A factory method that accept a string representation of a command with arguments and a stomp client pointer
        // and returns an appropriate Command object that represents the string command
        Command * CommandFactory::createFactory(std::string const &command_string, stomp::TwitterClient *client) {

            Args argumentList;
            boost::split(argumentList, command_string, boost::is_any_of(" "), boost::token_compress_on);
            
            std::string command_name = argumentList[0];
            
            //Remove the first element - that being the command_name, leaving only the actual arguments in the list
            argumentList.erase(argumentList.begin());

            Command *cmd = 0;

            //Ugly, we know, but C++ can't do a switch-case on strings and we didn't have enought time to find a more elegant solution
            if (command_name == "login") {
                cmd = new LoginCommand(client, argumentList);
            } else if (command_name == "follow") {
                cmd = new FollowCommand(client, argumentList);
            } else if (command_name == "unfollow") {
                cmd = new UnfollowCommand(client, argumentList);
            } else if (command_name == "tweet") {
                cmd = new TweetCommand(client, argumentList);
            } else if (command_name == "clients") {
                cmd = new ClientsCommand(client, argumentList);
            } else if (command_name == "stats") {
                cmd = new StatsCommand(client, argumentList);
            } else if (command_name == "logout") {
                cmd = new LogoutCommand(client, argumentList);
            } else if (command_name == "stop") {
                cmd = new StopCommand(client, argumentList);
            } else {
                std::cerr << "Unknown command type" << std::endl;
            }
            
            return cmd;
        }
示例#3
0
ArgsParser::spec ArgsParser::findSpec( const ObjectImp* obj, const Args& parents ) const
{
  spec ret;
  ret.type = 0;

  std::vector<bool> found( margs.size(), false );

  for ( Args::const_iterator o = parents.begin();
        o != parents.end(); ++o )
  {
    for ( uint i = 0; i < margs.size(); ++i )
    {
      if ( (*o)->inherits( margs[i].type ) && !found[i] )
      {
        // object o is of a type that we're looking for
        found[i] = true;
        if ( *o == obj ) return margs[i];
        // i know that "goto's are *evil*", but they're very useful
        // and completely harmless if you use them as better "break;"
        // statements.. trust me ;)
        goto matched;
      };
    };
  matched:
    ;
  };
  kdDebug() << k_funcinfo << "no proper spec found :(" << endl;
  return ret;
}
示例#4
0
LastfmService::Result LastfmService::fetch(Args &args)
{
	Result result;
	
	std::string url = baseURL;
	url += methodName();
	for (Args::const_iterator it = args.begin(); it != args.end(); ++it)
	{
		url += "&";
		url += it->first;
		url += "=";
		url += Curl::escape(it->second);
	}
	
	std::string data;
	CURLcode code = Curl::perform(data, url);
	
	if (code != CURLE_OK)
	{
		result.second = curl_easy_strerror(code);
		return result;
	}
	
	if (actionFailed(data))
	{
		StripHtmlTags(data);
		result.second = data;
		return result;
	}
	
	if (!parse(data))
	{
		// if relevant part of data was not found and one of arguments
		// was language, try to fetch it again without that parameter.
		// otherwise just report failure.
		Args::iterator lang = args.find("lang");
		if (lang != args.end())
		{
			args.erase(lang);
			return fetch(args);
		}
		else
		{
			// parse should change data to error msg, if it fails
			result.second = data;
			return result;
		}
	}
	
	result.first = true;
	result.second = data;
	return result;
}
示例#5
0
void ForkedBroker::init(const Args& userArgs) {
    using qpid::ErrnoException;
    port = 0;
    int pipeFds[2];
    if(::pipe(pipeFds) < 0) throw ErrnoException("Can't create pipe");

    // Ignore the SIGCHLD signal generated by an exitting child
    // We will clean up any exitting children in the waitpid above
    // This should really be neater (like only once not per fork)
    struct ::sigaction sa;
    sa.sa_handler = ignore_signal;
    ::sigemptyset(&sa.sa_mask);
    ::sigaddset(&sa.sa_mask, SIGCHLD);
    sa.sa_flags = SA_NOCLDSTOP | SA_RESTART;
    ::sigaction(SIGCHLD, &sa, 0);

    pid = ::fork();
    if (pid < 0) throw ErrnoException("Fork failed");
    if (pid) {              // parent
        ::close(pipeFds[1]);
        FILE* f = ::fdopen(pipeFds[0], "r");
        if (!f) throw ErrnoException("fopen failed");
        if (::fscanf(f, "%d", &port) != 1) {
            if (ferror(f)) throw ErrnoException("Error reading port number from child.");
            else throw qpid::Exception("EOF reading port number from child.");
        }
        ::fclose(f);
	running = true;
    }
    else {                  // child
        ::close(pipeFds[0]);
        int fd = ::dup2(pipeFds[1], 1); // pipe stdout to the parent.
        if (fd < 0) throw ErrnoException("dup2 failed");
        const char* prog = ::getenv("QPIDD_EXEC");
        if (!prog) prog = "../qpidd"; // This only works from within svn checkout
        Args args(userArgs);
        args.push_back("--port=0");
        // Keep quiet except for errors.
        if (!::getenv("QPID_TRACE") && !::getenv("QPID_LOG_ENABLE")
            && find_if(userArgs.begin(), userArgs.end(), isLogOption) == userArgs.end())
            args.push_back("--log-enable=error+");
        std::vector<const char*> argv(args.size());
        std::transform(args.begin(), args.end(), argv.begin(), boost::bind(&std::string::c_str, _1));
        argv.push_back(0);
        QPID_LOG(debug, "ForkedBroker exec " << prog << ": " << args);

        execv(prog, const_cast<char* const*>(&argv[0]));
        QPID_LOG(critical, "execv failed to start broker: prog=\"" << prog << "\"; args=\"" << args << "\"; errno=" << errno << " (" << std::strerror(errno) << ")");
        ::exit(1);
    }
}
示例#6
0
void FlagImpl<bool>::Parse( Args & args )
{
     for( Args::iterator arg = args.begin(); arg != args.end(); ++arg )
     {
          if( !arg->compare( GetFlag() ))
          {
               if( IsAlreadySet() ) // если флаг задан( уже встречалс¤ среди переданных аргументов )
                    throw exception::ErrBadArgs();
               // аргумент, ¤вл¤ющийс¤ булевым флагом, не предполагает следующей за ним опции
               SetVal( true ); 
               SetIsAlreadySet(); // выставл¤ем признак того, что данный флаг уже задан( защита от дублировани¤ )
               // удал¤ем из списка аргументов считанный флаг
               args.erase( arg ); 
               break;
          }
     }
}
示例#7
0
void FlagImpl<std::string>::Parse( Args & args )
{
     for( Args::iterator arg = args.begin(); arg != args.end(); ++arg )
     {
          if( !arg->compare( GetFlag() ))
          {
               if( IsAlreadySet() ) // если флаг задан( уже встречалс¤ среди переданных аргументов )
                    throw exception::ErrBadArgs();
               Args::iterator flag = arg; // первый аргумент - флаг
               Args::iterator opt = ++arg; // следущий за ним аргумент - опци¤ 
               if( opt == args.end() )
                    throw exception::ErrBadArgs();
               SetVal( *opt );
               SetIsAlreadySet(); // выставл¤ем признак того, что данный флаг уже задан( защита от дублировани¤ )
               // удал¤ем из списка аргументов считанные флаг и опцию
               args.erase( flag ); 
               args.erase( opt );
               break;
          }
     }
}
示例#8
0
void ForkedBroker::init(const Args& userArgs) {
    using qpid::ErrnoException;
    port = 0;
    int pipeFds[2];
    if(::pipe(pipeFds) < 0) throw ErrnoException("Can't create pipe");
    pid = ::fork();
    if (pid < 0) throw ErrnoException("Fork failed");
    if (pid) {              // parent
        ::close(pipeFds[1]);
        FILE* f = ::fdopen(pipeFds[0], "r");
        if (!f) throw ErrnoException("fopen failed");
        if (::fscanf(f, "%d", &port) != 1) {
            if (ferror(f)) throw ErrnoException("Error reading port number from child.");
            else throw qpid::Exception("EOF reading port number from child.");
        }
        ::close(pipeFds[0]);
    }
    else {                  // child
        ::close(pipeFds[0]);
        int fd = ::dup2(pipeFds[1], 1); // pipe stdout to the parent.
        if (fd < 0) throw ErrnoException("dup2 failed");
        const char* prog = ::getenv("QPIDD_EXEC");
        if (!prog) prog = "../qpidd"; // This only works from within svn checkout
        Args args(userArgs);
        args.push_back("--port=0");
        // Keep quiet except for errors.
        if (!::getenv("QPID_TRACE") && !::getenv("QPID_LOG_ENABLE")
            && find_if(userArgs.begin(), userArgs.end(), isLogOption) == userArgs.end())
            args.push_back("--log-enable=error+");
        std::vector<const char*> argv(args.size());
        std::transform(args.begin(), args.end(), argv.begin(), boost::bind(&std::string::c_str, _1));
        argv.push_back(0);
        QPID_LOG(debug, "ForkedBroker exec " << prog << ": " << args);
        execv(prog, const_cast<char* const*>(&argv[0]));
        QPID_LOG(critical, "execv failed to start broker: prog=\"" << prog << "\"; args=\"" << args << "\"; errno=" << errno << " (" << std::strerror(errno) << ")");
        ::exit(1);
    }
}
示例#9
0
//static 
ProcessHandlePtr Process::launch(const std::string& command, const Args& args,
                                 const EnvMap& envVariables,
                                 const std::string& sWorkDir)
{
    if (!sWorkDir.empty())
    {
        File f(sWorkDir);
        if (!f.createDirectories())
        {
            FIRTEX_THROW(SystemException, "Cannot create work "
                         "directory for: [%s]", command.c_str());
        }
    }

    int pid = fork();
    if (pid < 0)
    {
        FIRTEX_THROW(SystemException, "Cannot fork process for: [%s]", 
                     command.c_str());
    }

    //fill arguments
    char** argv = new char*[args.size() + 2];
    int i = 0;
    argv[i++] = const_cast<char*>(command.c_str());
    for (Args::const_iterator it = args.begin(); it != args.end(); ++it)
    {
        argv[i++] = const_cast<char*>(it->c_str());
    }
    argv[i] = NULL;

    if (pid == 0) //the child process
    {
        for (EnvMap::const_iterator it = envVariables.begin();
             it != envVariables.end(); ++it)
        {
            Environment::set(it->first, it->second);
        }
        if (!sWorkDir.empty())
        {
            if (chdir(sWorkDir.c_str()) == -1)
            {
                FIRTEX_THROW(RuntimeException, "chdir(%s) FAILED",
                        sWorkDir.c_str());
            }
        }

        // close all open file descriptors other than stdin, stdout, stderr
        for (int i = 3; i < getdtablesize(); ++i)
        {
            close(i);
        }
        
        stringstream ss;
        ss << "." << getpid();
        Path path(sWorkDir);
        path.makeDirectory();

        path.setFileName(STDOUT_FILE_NAME + ss.str());
        if (freopen(path.toString().c_str(), "w+", stdout) == NULL)
        {
            FX_LOG(ERROR, "Reopen [%s] FAILED", path.toString().c_str());
        }

        path.setFileName(STDERR_FILE_NAME + ss.str());
        if (freopen(path.toString().c_str(), "w+", stderr) == NULL)
        {
            FX_LOG(ERROR, "Reopen [%s] FAILED", path.toString().c_str());
        }
        execvp(command.c_str(), argv);

        fprintf(stderr, "command: [%s] execvp FAILED, error code: %d(%s)",
                command.c_str(), errno, strerror(errno));
        fflush(stderr);
        _exit(72);
    }
    else 
    {
        delete[] argv;
        //parent process
        return ProcessHandlePtr(new ProcessHandle(pid));
    }

    //never get here
    return ProcessHandlePtr();
}