예제 #1
0
파일: raspi.cpp 프로젝트: hephaisto/heinz
EndpointRaspberry::EndpointRaspberry(ptree &pt)
:HardwareEndpoint(pt),
pinNumber(pt.get<int>("pin")),
invert(pt.get<bool>("invert",false))
{
	if(!initialized)
	{
		if(wiringPiSetup())
			throw HeinzException("unable to initialize wiringPi");
		initialized=true;
	}
	string pull_mode_s=pt.get<string>("pull","off");
	int pull_mode=PUD_OFF;
	if(pull_mode_s=="off")
		pull_mode=PUD_OFF;
	else if(pull_mode_s=="up")
		pull_mode=PUD_UP;
	else if(pull_mode_s=="down")
		pull_mode=PUD_DOWN;
	else
		BOOST_THROW_EXCEPTION(ConfigException()<<ExErrorMessage((boost::format("unknown pull mode: %1%")%pull_mode_s).str()));

	if(allocatedPins.find(pinNumber)!=allocatedPins.end())
		BOOST_THROW_EXCEPTION(ConfigException()<<ExErrorMessage((boost::format("pin %1% already in use")%pinNumber).str()));
	allocatedPins.insert(pinNumber);

	pinMode(pinNumber,getIsInput()?INPUT:OUTPUT);
	if(getIsInput())
		pullUpDnControl(pinNumber, pull_mode);
}
예제 #2
0
파일: kvstore.cpp 프로젝트: vyvy/vasum
char* KVStore::getInternal(const std::string& key, char**)
{
    Transaction transaction(*this);
    ScopedReset scopedReset(mGetValueStmt);

    ::sqlite3_bind_text(mGetValueStmt->get(), 1, key.c_str(), AUTO_DETERM_SIZE, SQLITE_TRANSIENT);

    int ret = ::sqlite3_step(mGetValueStmt->get());
    if (ret == SQLITE_DONE) {
        throw ConfigException("No value corresponding to the key: " + key + "@" + mPath);
    }
    if (ret != SQLITE_ROW) {
        throw ConfigException("Error during stepping: " + mConn.getErrorMessage());
    }

    const char* source = reinterpret_cast<const char*>(sqlite3_column_text(mGetValueStmt->get(), FIRST_COLUMN));

    size_t length = std::strlen(source);
    char* value = new char[length + 1];

    std::strncpy(value, source, length);
    value[length] = '\0';

    transaction.commit();
    return value;
}
예제 #3
0
AbsSyncAlgorithm* OptimisticTickSyncAlgo::Create(const Json::Value& param,AbsCommManager *comm){

	if(param["strategy"].isNull())
		throw ConfigException("Speculation strategy is not defined!");


	SpeculationTimeCalculationStrategy *st;
	string strategy=param["strategy"].asString();
	if(strategy.compare("constant")==0){
		time_metric met=FncsConfig::jsonToTimeMetric(param["metric"]);
		TIME specTime=(TIME)param["look_ahead_time"].asUInt64();
		st=new ConstantSpeculationTimeStrategy(met,specTime);
	}else
		if(strategy.compare("increasing")==0){
			time_metric met=FncsConfig::jsonToTimeMetric(param["metric"]);
			TIME specTime=(TIME)param["initial_look_ahead_time"].asUInt64();
			st=new IncreasingSpeculationTimeStrategy(met,specTime);
		}else
			if(strategy.compare("infinity")==0){
				st=new InfinitySpeculationTimeStrategy();
			}else
				if(strategy.compare("infinitywithkill")==0){
					st=new InfinitySpeculationTimeStrategyWithKillLast();
				}else{
					throw ConfigException("unknown speculation strategy!");
				}

	return new OptimisticTickSyncAlgo(comm,st);
}
예제 #4
0
파일: manager.hpp 프로젝트: vyvy/vasum
void loadFromJsonFile(const std::string& filename, Config& config)
{
    std::string content;
    if (!fsutils::readFileContent(filename, content)) {
        throw ConfigException("Could not load " + filename);
    }
    try {
        loadFromJsonString(content, config);
    } catch (ConfigException& e) {
        throw ConfigException("Error in " + filename + ": " + e.what());
    }
}
예제 #5
0
파일: Config.cpp 프로젝트: LeHack/hackttp
int Config::get_int_setting(std::string setting_name) {
    reload_on_usr1();
	int returnInt = -1;
    try {
        returnInt = std::stoi(configMap.at(setting_name));
    } catch (out_of_range){
        throw ConfigException("Unknown int option passed: " + setting_name);
	} catch (invalid_argument){
        throw ConfigException("Error parsing config to int, check config file syntax at " + setting_name);
    }
	return returnInt;
}
예제 #6
0
	void OnReload(Configuration::Conf *conf) override
	{
		const Anope::string &hsnick = conf->GetModule(this)->Get<Anope::string>("client");

		if (hsnick.empty())
			throw ConfigException(Module::name + ": <client> must be defined");

		ServiceBot *bi = ServiceBot::Find(hsnick, true);
		if (!bi)
			throw ConfigException(Module::name + ": no bot named " + hsnick);

		HostServ = bi;
	}
예제 #7
0
파일: manager.hpp 프로젝트: vyvy/vasum
void loadFromKVStoreWithJsonFile(const std::string& kvfile,
                                 const std::string& jsonfile,
                                 Config& config,
                                 const std::string& kvConfigName)
{
    std::string content;
    if (!fsutils::readFileContent(jsonfile, content)) {
        throw ConfigException("Could not load " + jsonfile);
    }
    try {
        loadFromKVStoreWithJson(kvfile, content, config, kvConfigName);
    } catch (ConfigException& e) {
        throw ConfigException("Error in " + jsonfile + ": " + e.what());
    }
}
예제 #8
0
void IRC2SQL::OnReload(Configuration::Conf *conf)
{
	Configuration::Block *block = Config->GetModule(this);
	prefix = block->Get<const Anope::string>("prefix", "anope_");
	GeoIPDB = block->Get<const Anope::string>("geoip_database");
	ctcpuser = block->Get<bool>("ctcpuser", "no");
	ctcpeob = block->Get<bool>("ctcpeob", "yes");
	Anope::string engine = block->Get<const Anope::string>("engine");
	this->sql = ServiceReference<SQL::Provider>("SQL::Provider", engine);
	if (sql)
		this->CheckTables();
	else
		Log() << "IRC2SQL: no database connection to " << engine;

	const Anope::string &snick = block->Get<const Anope::string>("client");
	if (snick.empty())
		throw ConfigException(Module::name + ": <client> must be defined");
	StatServ = BotInfo::Find(snick, true);
	if (!StatServ)
		throw ConfigException(Module::name + ": no bot named " + snick);

	if (firstrun)
	{
		firstrun = false;

		for (Anope::map<Server *>::const_iterator it = Servers::ByName.begin(); it != Servers::ByName.end(); ++it)
		{
			this->OnNewServer(it->second);
		}

		for (channel_map::const_iterator it = ChannelList.begin(), it_end = ChannelList.end(); it != it_end; ++it)
		{
			this->OnChannelCreate(it->second);
		}

		for (user_map::const_iterator it = UserListByNick.begin(); it != UserListByNick.end(); ++it)
		{
			User *u = it->second;
			bool exempt = false;
			this->OnUserConnect(u, exempt);
			for (User::ChanUserList::const_iterator cit = u->chans.begin(), cit_end = u->chans.end(); cit != cit_end; ++cit)
			{
				this->OnJoinChannel(u, cit->second->chan);
			}
		}
	}

}
예제 #9
0
  AbsCommManager* CommunicationComManager::Create(AbsNetworkInterface* given,bool simType){
	  if(simType){
		  throw ConfigException("SimType is not communication network simulator");
	  }

	  return new CommunicationComManager(given);
  }
예제 #10
0
void Config::onError(const std::string& msg, int code) {
	//std::cerr << "ConfigError:" << std::endl;
	//std::cerr << msg << std::endl;
	//std::cerr << "code: " << code << std::endl;
	exit(100);
	throw ConfigException(msg, code);
}
예제 #11
0
void MessageBroker::Server::start()
{
  if (_config_loaded == false)
    throw ConfigException("Message Broker server: Can't start server, config not loaded.");
  try
  {
    _ctx = std::make_unique<zmq::context_t>();

    _output = std::make_unique<zmq::socket_t>(*_ctx, zmq::socket_type::xpub);
    _output->bind("tcp://*:" + _server_pub_port);

    _input = std::make_unique<zmq::socket_t>(*_ctx, zmq::socket_type::xsub);
    _input->bind("tcp://*:" + _server_sub_port);

    _control = std::make_unique<zmq::socket_t>(*_ctx, zmq::socket_type::rep);
    _control->connect("tcp://127.0.0.1:6666");

    zmq::proxy_steerable(static_cast<void *>(*_input), static_cast<void *>(*_output), nullptr, static_cast<void *>(*_control));

    _control.reset();
    _input.reset();
    _output.reset();
    _ctx.reset();
  }
  catch (const std::exception& ex)
  {
    throw SystemException("Message broker server: Error. " + std::string(ex.what()));
  }
}
예제 #12
0
파일: kvstore.cpp 프로젝트: vyvy/vasum
void KVStore::createFunctions()
{
    int ret = sqlite3_create_function(mConn.get(), "escapeStr", 1, SQLITE_ANY, 0, &sqliteEscapeStr, 0, 0);
    if (ret != SQLITE_OK) {
        throw ConfigException("Error during creating functions: " + mConn.getErrorMessage());
    }
}
예제 #13
0
파일: manager.hpp 프로젝트: vyvy/vasum
void saveToJsonFile(const std::string& filename, const Config& config)
{
    const std::string content = saveToJsonString(config);
    if (!fsutils::saveFileContent(filename, content)) {
        throw ConfigException("Could not save " + filename);
    }
}
예제 #14
0
	void OnReload(Configuration::Conf *conf) override
	{
		Configuration::Block *config = conf->GetModule(this);

		this->certfile = config->Get<Anope::string>("cert", "data/anope.crt");
		this->keyfile = config->Get<Anope::string>("key", "data/anope.key");

		if (Anope::IsFile(this->certfile.c_str()))
		{
			if (!SSL_CTX_use_certificate_file(client_ctx, this->certfile.c_str(), SSL_FILETYPE_PEM) || !SSL_CTX_use_certificate_file(server_ctx, this->certfile.c_str(), SSL_FILETYPE_PEM))
				throw ConfigException("Error loading certificate");
			else
				Log(LOG_DEBUG) << "m_ssl_openssl: Successfully loaded certificate " << this->certfile;
		}
		else
			Log() << "Unable to open certificate " << this->certfile;

		if (Anope::IsFile(this->keyfile.c_str()))
		{
			if (!SSL_CTX_use_PrivateKey_file(client_ctx, this->keyfile.c_str(), SSL_FILETYPE_PEM) || !SSL_CTX_use_PrivateKey_file(server_ctx, this->keyfile.c_str(), SSL_FILETYPE_PEM))
				throw ConfigException("Error loading private key");
			else
				Log(LOG_DEBUG) << "m_ssl_openssl: Successfully loaded private key " << this->keyfile;
		}
		else
		{
			if (Anope::IsFile(this->certfile.c_str()))
				throw ConfigException("Error loading private key " + this->keyfile + " - file not found");
			else
				Log() << "Unable to open private key " << this->keyfile;
		}

		// Allow disabling SSLv3
		if (!config->Get<Anope::string>("sslv3").empty())
		{
			if (config->Get<bool>("sslv3"))
			{
				SSL_CTX_clear_options(client_ctx, SSL_OP_NO_SSLv3);
				SSL_CTX_clear_options(server_ctx, SSL_OP_NO_SSLv3);
			}
			else
			{
				SSL_CTX_set_options(client_ctx, SSL_OP_NO_SSLv3);
				SSL_CTX_set_options(server_ctx, SSL_OP_NO_SSLv3);
			}
		}
	}
예제 #15
0
파일: Config.cpp 프로젝트: LeHack/hackttp
void Config::loadConfigFileToMap(){
    configMap.clear();
    std::string configString;
    std::string delimiter;
    std::string configRelevantString;
    std::string configLine;
    std::string key;
    size_t position;

    int configFileDescriptor;
    // TODO: Should take name of config file from constructor param (passed from CmdLine or some default)
    if ((configFileDescriptor = open("./config", O_RDONLY, S_IRUSR)) == -1) {
        throw ConfigException("Cannot open config file!");
    }

    char configFileContents[CONFIG_SIZE];
    if (read(configFileDescriptor, &configFileContents, CONFIG_SIZE) == -1) {
        throw ConfigException("Cannot read config file!");
    }
    close(configFileDescriptor);

    //Removes everything after ; in config file
    configString = std::string(configFileContents);
    delimiter = ";";
    configRelevantString = configString.substr(0, configString.find(delimiter));

    //Splits the file into lines
    vector<string> vectorOfLines;
    delimiter = "\n";
    while ((position = configRelevantString.find(delimiter)) != std::string::npos) {
        configLine = configRelevantString.substr(0, position);
        vectorOfLines.push_back(configLine);
        configRelevantString.erase(0, position + delimiter.length());
    }

    //Splits the lines into key/value pairs
    delimiter = "=";
    for (std::vector<string>::const_iterator i = vectorOfLines.begin(); i != vectorOfLines.end(); ++i){
        configLine = *i;
        while ((position = configLine.find(delimiter)) != std::string::npos) {
            key = configLine.substr(0, position);
            configLine.erase(0, position + delimiter.length());
            configMap.insert(pair<string, string>(key, configLine));
        }
    }
}
예제 #16
0
// TODO - maybe something better
void GlobalManager::updateErrorFunction() throw(ConfigException) {
	if (settings->ERROR_FUNCTION == "ERROR_SQUARED") {
		errorFunction = ErrorFunction::ERROR_SQUARED;
	} else if (settings->ERROR_FUNCTION == "ABS_ERROR") {
		errorFunction = ErrorFunction::ABS_ERROR;
	} else {
		throw ConfigException("Unknown error function: " + settings->ERROR_FUNCTION);
	}
}
예제 #17
0
파일: kvstore.cpp 프로젝트: vyvy/vasum
void KVStore::Transaction::commit()
{
    if (mKVStore.mIsTransactionCommited) {
        throw ConfigException("Transaction already commited");
    }
    if (mIsOuter) {
        mKVStore.mConn.exec("COMMIT TRANSACTION");
        mKVStore.mIsTransactionCommited = true;
    }
}
예제 #18
0
파일: Config.cpp 프로젝트: LeHack/hackttp
std::string Config::get_str_setting(std::string setting_name) {
    reload_on_usr1();
    std::string returnString;
    try{
        returnString = configMap.at(setting_name);
    } catch (out_of_range) {
        throw ConfigException("Unknown string option passed: " + setting_name);
    }
    return returnString;
}
void MyriadEnumSet::initialize(const Path& path)
{
    if (!path.isFile())
    {
        throw ConfigException(format("Cannot find file at `%s`", path.toString()));
    }

    File file(path);

    if (!file.canRead())
    {
        throw ConfigException(format("Cannot read from file at `%s`", path.toString()));
    }

    ifstream in(file.path().c_str());

    if (!in.is_open())
    {
        throw ConfigException(format("Cannot open file at `%s`", path.toString()));
    }

    try
    {
        initialize(in);
        in.close();
    }
    catch(Poco::Exception& e)
    {
        in.close();
        throw e;
    }
    catch(exception& e)
    {
        in.close();
        throw e;
    }
    catch(...)
    {
        in.close();
        throw;
    }
}
예제 #20
0
파일: kvstore.cpp 프로젝트: vyvy/vasum
void KVStore::remove(const std::string& key)
{
    Transaction transaction(*this);
    ScopedReset scopedReset(mRemoveValuesStmt);

    ::sqlite3_bind_text(mRemoveValuesStmt->get(), 1, key.c_str(), AUTO_DETERM_SIZE, SQLITE_STATIC);

    if (::sqlite3_step(mRemoveValuesStmt->get()) != SQLITE_DONE) {
        throw ConfigException("Error during stepping: " + mConn.getErrorMessage());
    }
    transaction.commit();
}
예제 #21
0
파일: xmlrpc.cpp 프로젝트: gerrit-rws/anope
	void OnReload(Configuration::Conf *conf) override
	{
		if (httpref)
			httpref->UnregisterPage(&xmlrpcinterface);

		this->httpref = ServiceReference<HTTPProvider>(conf->GetModule(this)->Get<Anope::string>("server", "httpd/main"));

		if (!httpref)
			throw ConfigException("Unable to find http reference, is m_httpd loaded?");

		httpref->RegisterPage(&xmlrpcinterface);
	}
예제 #22
0
파일: kvstore.cpp 프로젝트: vyvy/vasum
KVStore::Transaction::Transaction(KVStore& kvStore)
    : mLock(kvStore.mMutex)
    , mKVStore(kvStore)
    , mIsOuter(kvStore.mTransactionDepth == 0)
{
    if (mKVStore.mIsTransactionCommited) {
        throw ConfigException("Previous transaction is not closed");
    }
    if (mIsOuter) {
        mKVStore.mConn.exec("BEGIN EXCLUSIVE TRANSACTION");
    }
    ++mKVStore.mTransactionDepth;
}
예제 #23
0
파일: kvstore.cpp 프로젝트: vyvy/vasum
bool KVStore::isEmpty()
{
    Transaction transaction(*this);
    ScopedReset scopedReset(mGetIsEmptyStmt);

    int ret = ::sqlite3_step(mGetIsEmptyStmt->get());
    if (ret != SQLITE_DONE && ret != SQLITE_ROW) {
        throw ConfigException("Error during stepping: " + mConn.getErrorMessage());
    }

    transaction.commit();
    return ret == SQLITE_DONE;
}
예제 #24
0
void MessageBroker::Server::load_config(const ConfigManager& mng)
{
  try
  {
    auto& section = mng.get_section("message_broker_settings");
    _server_pub_port = mng.get_value<std::string>(section, "server_pub_port");
    _server_sub_port = mng.get_value<std::string>(section, "server_sub_port");
    _config_loaded = true;
  }
  catch (const std::exception& ex)
  {
    throw ConfigException("Message Broker server : " + std::string(ex.what()));
  }
}
예제 #25
0
파일: kvstore.cpp 프로젝트: vyvy/vasum
bool KVStore::exists(const std::string& key)
{
    Transaction transaction(*this);
    ScopedReset scopedReset(mGetKeyExistsStmt);

    ::sqlite3_bind_text(mGetKeyExistsStmt->get(), 1, key.c_str(), AUTO_DETERM_SIZE, SQLITE_TRANSIENT);

    int ret = ::sqlite3_step(mGetKeyExistsStmt->get());
    if (ret != SQLITE_DONE && ret != SQLITE_ROW) {
        throw ConfigException("Error during stepping: " + mConn.getErrorMessage());
    }

    transaction.commit();
    return ret == SQLITE_ROW;
}
예제 #26
0
파일: kvstore.cpp 프로젝트: vyvy/vasum
void KVStore::setInternal(const std::string& key, const std::vector<std::string>& values)
{
    if (values.size() > std::numeric_limits<unsigned int>::max()) {
        throw ConfigException("Too many values to insert");
    }

    Transaction transaction(*this);

    remove(key);

    // Save vector's capacity
    setInternal(key, values.size());

    // Save vector's elements
    for (unsigned int i = 0; i < values.size(); ++i) {
        setInternal(config::key(key, std::to_string(i)),
                    values[i]);
    }
    transaction.commit();
}
예제 #27
0
파일: kvstore.cpp 프로젝트: vyvy/vasum
std::vector<std::string> KVStore::getKeys()
{
    Transaction transaction(*this);
    ScopedReset scopedReset(mGetKeysStmt);

    std::vector<std::string> result;

    for (;;) {
        int ret = ::sqlite3_step(mGetKeysStmt->get());
        if (ret == SQLITE_DONE) {
            break;
        }
        if (ret != SQLITE_ROW) {
            throw ConfigException("Error during stepping: " + mConn.getErrorMessage());
        }
        const char* key = reinterpret_cast<const char*>(sqlite3_column_text(mGetKeysStmt->get(),
                                                                            FIRST_COLUMN));
        result.push_back(key);
    }

    transaction.commit();
    return result;
}
예제 #28
0
	std::vector<std::string> Configuration::getNames(const char *path, ...)
	{
		CONSUME_PARAMS(path);

		// Get relevant nodes
		std::vector<ConfigNode *> nodes;
		collect(this->configRoot.get(), params.get(), 0, &nodes);

		// If there are no nodes, exit
		if (nodes.size() == 0) {
			throw ConfigException(pathNotFound(params.get()));
		}

		// Copy only the keys
		std::vector<std::string> result;
		for (size_t i = 0; i < nodes.size(); i++) {
			if (nodes[i]->getType() == ConfigNode::Leaf) {
				result.push_back(nodes[i]->getName());
			}
		}

		return result;
	}
예제 #29
0
	void Configuration::load(std::string filename, boost::shared_ptr<std::istream> content, bool, bool) {

		this->filename = filename;

		int linePos = 0;
		int chrPos = 0;

		std::string line;

		ConfigNode *currentNode = this->configRoot.get();

		while (content->good()) {

			std::getline(*content, line);
			boost::algorithm::trim_left(line);

			int lineLen = line.size();

			chrPos = 1;

			linePos++;

			while (chrPos < lineLen - 1) {

				if (line.size() == 0) break;

				switch (line[0]) {

					case '#':
						{
							std::string comment = line.substr(1, line.size() - 1);

							boost::trim(comment);
							currentNode->create(ConfigNode::Comment, comment);

							chrPos += line.size() - 1;
						}
						continue;

					case '<':
					case '[':
						{
							size_t end = line.find(']');

							if (end == std::string::npos) {
								end = line.find('>');
							}

							if ((line.size() < 2) || (end == std::string::npos)) {
								std::ostringstream ss;
								ss << "Parse error in " << filename << ", line " << linePos << " character " << chrPos << ": malformed tag!";
								throw ConfigException(ss.str());
							}

							if (end - 1 == 0) {
								std::ostringstream ss;
								ss << "Parse error in " << filename << ", line " << linePos << " character " << chrPos << ": malformed tag, tag name empty!";
								throw ConfigException(ss.str());
							}

							std::string name = line.substr(1, end - 1);

							if ((name[0] == '/') || (name[0] == '!')) {

								if (currentNode == NULL) {
									std::ostringstream ss;
									ss << "Parse error in " << filename << ", line " << linePos << " character " << chrPos << ": no opening tag found!";
									throw ConfigException(ss.str());
								}

								if (name.compare(1, name.size() - 1, currentNode->getName()) != 0) {
									std::ostringstream ss;
									ss << "Parse error in " << filename << ", line " << linePos << " character " << chrPos << ": closing tag does not match opening tag!";
									throw ConfigException(ss.str());
								}

								currentNode = currentNode->getParent();
							} else {
								currentNode = currentNode->create(name);
							}

							if (end <= line.size() - 1) {
								line = line.substr(end + 1, line.size() - end - 1);
							}

							chrPos += (end + 1);
						}
						break;

					default:
						chrPos++;

						if ((line[0] != ' ') && (line[0] != '\t')) {

							size_t curPos = 0;
							bool inString = false;

							std::ostringstream ss;

							while (curPos < line.size()) {

								// TODO: This was commented out; why? phb
								if ((!inString) &&
									((line[curPos] == '[') || (line[curPos] == '<')))
								{
									curPos--;
									break;
								}

								if (line[curPos] == '"') {
									inString = !inString;
									curPos++;
								}

								if (curPos < line.size()) {

									ss << line[curPos];
									curPos++;
								}
							}

							line = (curPos >= line.size() - 1 ? "" : line.substr(curPos + 1, line.size() - curPos - 1));

							chrPos += (curPos - 1);

							std::string element = ss.str();
							std::string key;
							std::string value;

							size_t eq = element.find('=');

							if (eq != std::string::npos) {
								key = element.substr(0, eq - 1);
								value = element.substr(eq + 1, element.size() - eq - 1);

								boost::algorithm::trim(key);
								boost::algorithm::trim(value);
							}

							boost::any a(value);

							currentNode->create(key, a);

						} else {
							line = line.substr(1, line.size() - 1);
						}

						break;
				}
			}
		}


		if (this->configRoot.get() != currentNode) {
			std::ostringstream ss;
			ss << "Parse error in " << filename << ", line " << linePos << " character " << line.size() << ": no closing tag found!";
			throw ConfigException(ss.str());
		}
	}
예제 #30
0
void Config::onError(const std::string& msg) {
	//std::cerr << "ConfigError:" << std::endl;
	//std::cerr << msg << std::endl;
	//exit(100);
	throw ConfigException(msg);
}