<commit_before>#include <iostream>

#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include <boost/lexical_cast.hpp>
#include "DataBase.h"

DataBase::DataBase() : db(NULL)
{
	const char *fileName = "test.db";
	bool isExistingDB;
	int rc;

	this->log = log4cplus::Logger::getInstance(LOG4CPLUS_TEXT("DataBase"));
	isExistingDB = boost::filesystem::exists(fileName);
	rc = sqlite3_open(fileName, &db);
	if (rc != 0)
		LOG4CPLUS_ERROR(log, LOG4CPLUS_TEXT("DataBase::DataBase - sqlite3_open() failed: " << sqlite3_errmsg(db)));
	else if (!isExistingDB)
	{
		this->createTables();
		this->insertDefaultData();
	}
	else
		LOG4CPLUS_DEBUG(log, LOG4CPLUS_TEXT("DataBase::DataBase - Opening existing database..."));
}

DataBase::~DataBase()
{
	if (db != NULL)
		sqlite3_close(db);
}

void DataBase::createTables()
{
	const char sqls[][256] =
	{
			"CREATE TABLE calendar(date INTEGER)",
			"CREATE TABLE condition(description TEXT, domoticz_device_type INTEGER, temperature_min REAL, temperature_max REAL, day INTEGER, calendar_id INTEGER REFERENCES calendar(rowid))",
			"CREATE TABLE graph(description TEXT, position INTEGER DEFAULT 99, condition_id INTEGER REFERENCES condition(rowid))",
			"CREATE TABLE graph_data(graph_id INTEGER REFERENCES graph(rowid), time INTEGER NOT NULL, value REAL)",
	};
	int nbElements = (sizeof(sqls) / sizeof(*sqls));

	for (int i = 0; i < nbElements; i++)
	{
		char *zErrMsg = NULL;
		int rc;

		rc = sqlite3_exec(db, sqls[i], NULL, NULL, &zErrMsg);
		if (rc != SQLITE_OK)
		{
			LOG4CPLUS_ERROR(log, LOG4CPLUS_TEXT("DataBase::createTables - SQL error: " << zErrMsg << " ### " << sqls[i]));
			sqlite3_free(zErrMsg);
		}
		else
			LOG4CPLUS_DEBUG(log, LOG4CPLUS_TEXT("DataBase::createTables - table created successfully"));
	}
}

void DataBase::insertDefaultData()
{
	const char sqls[][256] =
	{
			"INSERT INTO condition(description, domoticz_device_type, day) VALUES('Monday to friday', NULL, 124),('Saturday to sunday', NULL, 3)",
			"INSERT INTO graph(description, position, condition_id) VALUES('Default week', 0, 1)",
			"INSERT INTO graph_data(graph_id, time, value) VALUES(1, 0000, 19),(1, 0600, 19.5),(1, 1900, 20),(1, 2100, 19)",
			"INSERT INTO graph(description, position, condition_id) VALUES('Default week-end', 1, 2)",
			"INSERT INTO graph_data(graph_id, time, value) VALUES(2, 0000, 19),(2, 1000, 19.5),(2, 1900, 20),(2, 2100, 19)"
	};
	int nbElements = (sizeof(sqls) / sizeof(*sqls));

	for (int i = 0; i < nbElements; i++)
	{
		char *zErrMsg = NULL;
		int rc;

		rc = sqlite3_exec(db, sqls[i], NULL, NULL, &zErrMsg);
		if (rc != SQLITE_OK)
		{
			LOG4CPLUS_ERROR(log, LOG4CPLUS_TEXT("DataBase::insertDefaultData - SQL error: " << zErrMsg << " ### " << sqls[i]));
			sqlite3_free(zErrMsg);
		}
		else
			LOG4CPLUS_DEBUG(log, LOG4CPLUS_TEXT("DataBase::createTables - data inserted successfully"));
	}
}

bool DataBase::addCondition(std::string &description)
{
	sqlite3_stmt *stmt = NULL;
	const char *sql = "INSERT INTO condition(description) VALUES(?)";
	int rc;

	rc = sqlite3_prepare(db, sql, strlen(sql), &stmt, NULL);
	if (rc == SQLITE_OK)
	{
		sqlite3_bind_text(stmt, 1, description.c_str(), description.length(), NULL);
		rc = sqlite3_step(stmt);
		sqlite3_finalize(stmt);
		return (rc == SQLITE_DONE);
	}
	else
		LOG4CPLUS_ERROR(log, LOG4CPLUS_TEXT("DataBase::addCondition - sqlite3_prepare() failed: " << sqlite3_errmsg(db)));
	return false;
}

bool DataBase::addGraph(std::string &description)
{
	sqlite3_stmt *stmt = NULL;
	const char *sql = "INSERT INTO graph(description,condition_id) VALUES(?,NULL)";
	int rc;

	rc = sqlite3_prepare(db, sql, strlen(sql), &stmt, NULL);
	if (rc == SQLITE_OK)
	{
		sqlite3_bind_text(stmt, 1, description.c_str(), description.length(), NULL);
		rc = sqlite3_step(stmt);
		sqlite3_finalize(stmt);
		return (rc == SQLITE_DONE);
	}
	else
		LOG4CPLUS_ERROR(log, LOG4CPLUS_TEXT("DataBase::addGraph - sqlite3_prepare() failed: " << sqlite3_errmsg(db)));
	return false;
}

bool DataBase::updateCondition(sCondition &cond)
{
	sqlite3_stmt *stmt = NULL;
	const char *sql = "UPDATE condition SET description=?,domoticz_device_type=?,temperature_min=?,temperature_max=?,day=?,calendar_id=? WHERE rowid=?";
	int rc;

	rc = sqlite3_prepare(db, sql, strlen(sql), &stmt, NULL);
	if (rc == SQLITE_OK)
	{
		sqlite3_bind_text(stmt, 1, cond.description.c_str(), cond.description.length(), NULL);
		if (cond.domoticzDeviceType != -1)
			sqlite3_bind_int(stmt, 2, cond.domoticzDeviceType);
		else
			sqlite3_bind_null(stmt, 2);
		if (cond.temperatureMin != -1)
			sqlite3_bind_double(stmt, 3, cond.temperatureMin);
		else
			sqlite3_bind_null(stmt, 3);
		if (cond.temperatureMax != -1)
			sqlite3_bind_double(stmt, 4, cond.temperatureMax);
		else
			sqlite3_bind_null(stmt, 4);
		if (cond.day != -1)
			sqlite3_bind_int(stmt, 5, cond.day);
		else
			sqlite3_bind_null(stmt, 5);
		if (cond.calendarId != -1)
			sqlite3_bind_int(stmt, 6, cond.calendarId);
		else
			sqlite3_bind_null(stmt, 6);
		sqlite3_bind_int(stmt, 7, cond.id);
		rc = sqlite3_step(stmt);
		sqlite3_finalize(stmt);
		return (rc == SQLITE_DONE);
	}
	else
		LOG4CPLUS_ERROR(log, LOG4CPLUS_TEXT("DataBase::updateCondition - sqlite3_prepare() failed: " << sqlite3_errmsg(db)));
	return false;
}

bool DataBase::updateGraph(sGraph &graph)
{
	sqlite3_stmt *stmt = NULL;
	const char *sql = "UPDATE graph SET position=?,description=?,condition_id=? WHERE rowid=?";
	int rc;

	rc = sqlite3_prepare(db, sql, strlen(sql), &stmt, NULL);
	if (rc == SQLITE_OK)
	{
		sqlite3_bind_int(stmt, 1, graph.position);
		sqlite3_bind_text(stmt, 2, graph.description.c_str(), graph.description.length(), NULL);
		if (graph.conditionId != -1)
			sqlite3_bind_int(stmt, 3, graph.conditionId);
		else
			sqlite3_bind_null(stmt, 3);
		sqlite3_bind_int(stmt, 4, graph.id);
		rc = sqlite3_step(stmt);
		sqlite3_finalize(stmt);
		return (rc == SQLITE_DONE);
	}
	else
		LOG4CPLUS_ERROR(log, LOG4CPLUS_TEXT("DataBase::updateGraph - sqlite3_prepare() failed: " << sqlite3_errmsg(db)));
	return false;
}

bool DataBase::updateGraphData(sGraph &graph)
{
	sqlite3_stmt *stmt = NULL;
	const char *sqlDelete = "DELETE FROM graph_data WHERE graph_id=?";
	const char *sql = "INSERT INTO graph_data(graph_id, time, value) VALUES(?,?,?)";
	int rc;

	rc = sqlite3_prepare(db, sqlDelete, strlen(sqlDelete), &stmt, NULL);
	if (rc == SQLITE_OK)
	{
		sqlite3_bind_int(stmt, 1, graph.id);
		rc = sqlite3_step(stmt);
		sqlite3_finalize(stmt);
		if (rc == SQLITE_DONE)
		{
			rc = sqlite3_prepare(db, sql, strlen(sql), &stmt, NULL);
			if (rc == SQLITE_OK)
			{
				BOOST_FOREACH(sGraphData data, graph.data)
				{
					sqlite3_bind_int(stmt, 1, graph.id);
					sqlite3_bind_int(stmt, 2, data.time);
					sqlite3_bind_double(stmt, 3, data.value);
					rc = sqlite3_step(stmt);
					sqlite3_reset(stmt);
				}
				sqlite3_finalize(stmt);
			}
		}
	}
	if (rc != SQLITE_OK && rc != SQLITE_DONE)
		LOG4CPLUS_ERROR(log, LOG4CPLUS_TEXT("DataBase::updateGraphData - sqlite3_prepare() failed: " << sqlite3_errmsg(db)));
	return (rc == SQLITE_OK || rc == SQLITE_DONE);
}

static int selectCondition(void *param, int ac, char **av, char **column)
{
	std::vector<sCondition> *r = static_cast<std::vector<sCondition>*>(param);

	if (ac == 7)
	{
		sCondition cond;

		cond.id = boost::lexical_cast<int>(av[0]);
		cond.description = av[1];
		cond.domoticzDeviceType = static_cast<eDomoticzDeviceType>(av[2] == NULL ? none : boost::lexical_cast<int>(av[2]));
		cond.temperatureMin = (av[3] == NULL ? -1 : boost::lexical_cast<float>(av[3]));
		cond.temperatureMax = (av[4] == NULL ? -1 : boost::lexical_cast<float>(av[4]));
		cond.day = (av[5] == NULL ? -1 : boost::lexical_cast<int>(av[5]));
		cond.calendarId = (av[6] == NULL ? -1 : boost::lexical_cast<int>(av[6]));
		r->push_back(cond);
	}
	return 0;
}

std::vector<sCondition> DataBase::getConditions()
{
	std::vector<sCondition> ret;
	int rc;

	rc = sqlite3_exec(db, "SELECT rowid,description,domoticz_device_type,temperature_min,temperature_max,day,calendar_id FROM condition ORDER BY rowid", selectCondition, &ret, NULL);
	if (rc != SQLITE_OK)
		LOG4CPLUS_ERROR(log, LOG4CPLUS_TEXT("DataBase::getConditions - SQL error"));
	return ret;
}

static int selectGraph(void *param, int ac, char **av, char **column)
{
	std::vector<sGraph> *r = static_cast<std::vector<sGraph>*>(param);

	if (ac == 4)
	{
		sGraph graph;

		graph.id = boost::lexical_cast<int>(av[0]);
		graph.position = boost::lexical_cast<int>(av[1]);
		graph.description = av[2];
		graph.conditionId = (av[3] == NULL ? -1 : boost::lexical_cast<int>(av[3]));
		r->push_back(graph);
	}
	return 0;
}

std::vector<sGraph> DataBase::getGraphs()
{
	std::vector<sGraph> ret;
	int rc;

	rc = sqlite3_exec(db, "SELECT rowid,position,description,condition_id FROM graph ORDER BY position", selectGraph, &ret, NULL);
	if (rc != SQLITE_OK)
		LOG4CPLUS_ERROR(log, LOG4CPLUS_TEXT("DataBase::getGraphs - SQL error"));
	return ret;
}

static int selectGraphData(void *param, int ac, char **av, char **column)
{
	sGraph *r = static_cast<sGraph*>(param);

	if (ac == 2)
	{
		sGraphData data;

		data.time = boost::lexical_cast<int>(av[0]);
		data.value = boost::lexical_cast<float>(av[1]);
		r->data.push_back(data);
	}
	return 0;
}

sCondition DataBase::getCondition(int id)
{
	std::stringstream ss;
	std::vector<sCondition> conds;
	sCondition ret;
	int rc;

	ss << "SELECT rowid,description,domoticz_device_type,temperature_min,temperature_max,day,calendar_id FROM condition WHERE rowid=" << id;
	rc = sqlite3_exec(db, ss.str().c_str(), selectCondition, &conds, NULL);
	if (rc != SQLITE_OK)
		LOG4CPLUS_ERROR(log, LOG4CPLUS_TEXT("DataBase::getCondition - SQL error graph"));
	else if (conds.size() == 1)
		ret = conds[0];
	return ret;
}

sGraph DataBase::getGraph(int id)
{
	std::stringstream ss;
	std::vector<sGraph> graphs;
	sGraph ret;
	int rc;

	ss << "SELECT rowid,position,description,condition_id FROM graph WHERE rowid=" << id;
	rc = sqlite3_exec(db, ss.str().c_str(), selectGraph, &graphs, NULL);
	if (rc != SQLITE_OK)
		LOG4CPLUS_ERROR(log, LOG4CPLUS_TEXT("DataBase::getGraph - SQL error graph"));
	else if (graphs.size() == 1)
	{
		ret = graphs[0];
		ss.str(std::string());
		ss << "SELECT time,value FROM graph_data WHERE graph_id=" << id;
		rc = sqlite3_exec(db, ss.str().c_str(), selectGraphData, &ret, NULL);
		if (rc != SQLITE_OK)
			LOG4CPLUS_ERROR(log, LOG4CPLUS_TEXT("DataBase::getGraph - SQL error graph_data"));
	}
	else
		LOG4CPLUS_ERROR(log, LOG4CPLUS_TEXT("DataBase::getGraph - no data"));
	return ret;
}

<commit_msg>Add graph and condition when it's hot<commit_after>#include <iostream>

#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include <boost/lexical_cast.hpp>
#include "DataBase.h"

DataBase::DataBase() : db(NULL)
{
	const char *fileName = "test.db";
	bool isExistingDB;
	int rc;

	this->log = log4cplus::Logger::getInstance(LOG4CPLUS_TEXT("DataBase"));
	isExistingDB = boost::filesystem::exists(fileName);
	rc = sqlite3_open(fileName, &db);
	if (rc != 0)
		LOG4CPLUS_ERROR(log, LOG4CPLUS_TEXT("DataBase::DataBase - sqlite3_open() failed: " << sqlite3_errmsg(db)));
	else if (!isExistingDB)
	{
		this->createTables();
		this->insertDefaultData();
	}
	else
		LOG4CPLUS_DEBUG(log, LOG4CPLUS_TEXT("DataBase::DataBase - Opening existing database..."));
}

DataBase::~DataBase()
{
	if (db != NULL)
		sqlite3_close(db);
}

void DataBase::createTables()
{
	const char sqls[][256] =
	{
			"CREATE TABLE calendar(date INTEGER)",
			"CREATE TABLE condition(description TEXT, domoticz_device_type INTEGER, temperature_min REAL, temperature_max REAL, day INTEGER, calendar_id INTEGER REFERENCES calendar(rowid))",
			"CREATE TABLE graph(description TEXT, position INTEGER DEFAULT 99, condition_id INTEGER REFERENCES condition(rowid))",
			"CREATE TABLE graph_data(graph_id INTEGER REFERENCES graph(rowid), time INTEGER NOT NULL, value REAL)",
	};
	int nbElements = (sizeof(sqls) / sizeof(*sqls));

	for (int i = 0; i < nbElements; i++)
	{
		char *zErrMsg = NULL;
		int rc;

		rc = sqlite3_exec(db, sqls[i], NULL, NULL, &zErrMsg);
		if (rc != SQLITE_OK)
		{
			LOG4CPLUS_ERROR(log, LOG4CPLUS_TEXT("DataBase::createTables - SQL error: " << zErrMsg << " ### " << sqls[i]));
			sqlite3_free(zErrMsg);
		}
		else
			LOG4CPLUS_DEBUG(log, LOG4CPLUS_TEXT("DataBase::createTables - table created successfully"));
	}
}

void DataBase::insertDefaultData()
{
	const char sqls[][256] =
	{
			"INSERT INTO condition(description, day) VALUES('Monday to friday', 124),('Saturday to sunday', 3)",
			"INSERT INTO graph(description, position, condition_id) VALUES('Default week', 0, 1)",
			"INSERT INTO graph_data(graph_id, time, value) VALUES(1, 0000, 19),(1, 0600, 19.5),(1, 1900, 20),(1, 2100, 19)",
			"INSERT INTO graph(description, position, condition_id) VALUES('Default week-end', 1, 2)",
			"INSERT INTO graph_data(graph_id, time, value) VALUES(2, 0000, 19),(2, 1000, 19.5),(2, 1900, 20),(2, 2100, 19)",

			"INSERT INTO condition(description, domoticz_device_type, temperature_min, day) VALUES('Monday to friday - hot', 1, 14, 124),('Saturday to sunday - hot', 1, 14, 3)",
			"INSERT INTO graph(description, position, condition_id) VALUES('Hot week', 2, 3)",
			"INSERT INTO graph_data(graph_id, time, value) VALUES(3, 0000, 18),(3, 0600, 18.5),(3, 1900, 19),(3, 2100, 18)",
			"INSERT INTO graph(description, position, condition_id) VALUES('Hot week-end', 3, 4)",
			"INSERT INTO graph_data(graph_id, time, value) VALUES(4, 0000, 18),(4, 1000, 18.5),(4, 1900, 19),(4, 2100, 18)"
	};
	int nbElements = (sizeof(sqls) / sizeof(*sqls));

	for (int i = 0; i < nbElements; i++)
	{
		char *zErrMsg = NULL;
		int rc;

		rc = sqlite3_exec(db, sqls[i], NULL, NULL, &zErrMsg);
		if (rc != SQLITE_OK)
		{
			LOG4CPLUS_ERROR(log, LOG4CPLUS_TEXT("DataBase::insertDefaultData - SQL error: " << zErrMsg << " ### " << sqls[i]));
			sqlite3_free(zErrMsg);
		}
		else
			LOG4CPLUS_DEBUG(log, LOG4CPLUS_TEXT("DataBase::createTables - data inserted successfully"));
	}
}

bool DataBase::addCondition(std::string &description)
{
	sqlite3_stmt *stmt = NULL;
	const char *sql = "INSERT INTO condition(description) VALUES(?)";
	int rc;

	rc = sqlite3_prepare(db, sql, strlen(sql), &stmt, NULL);
	if (rc == SQLITE_OK)
	{
		sqlite3_bind_text(stmt, 1, description.c_str(), description.length(), NULL);
		rc = sqlite3_step(stmt);
		sqlite3_finalize(stmt);
		return (rc == SQLITE_DONE);
	}
	else
		LOG4CPLUS_ERROR(log, LOG4CPLUS_TEXT("DataBase::addCondition - sqlite3_prepare() failed: " << sqlite3_errmsg(db)));
	return false;
}

bool DataBase::addGraph(std::string &description)
{
	sqlite3_stmt *stmt = NULL;
	const char *sql = "INSERT INTO graph(description,condition_id) VALUES(?,NULL)";
	int rc;

	rc = sqlite3_prepare(db, sql, strlen(sql), &stmt, NULL);
	if (rc == SQLITE_OK)
	{
		sqlite3_bind_text(stmt, 1, description.c_str(), description.length(), NULL);
		rc = sqlite3_step(stmt);
		sqlite3_finalize(stmt);
		return (rc == SQLITE_DONE);
	}
	else
		LOG4CPLUS_ERROR(log, LOG4CPLUS_TEXT("DataBase::addGraph - sqlite3_prepare() failed: " << sqlite3_errmsg(db)));
	return false;
}

bool DataBase::updateCondition(sCondition &cond)
{
	sqlite3_stmt *stmt = NULL;
	const char *sql = "UPDATE condition SET description=?,domoticz_device_type=?,temperature_min=?,temperature_max=?,day=?,calendar_id=? WHERE rowid=?";
	int rc;

	rc = sqlite3_prepare(db, sql, strlen(sql), &stmt, NULL);
	if (rc == SQLITE_OK)
	{
		sqlite3_bind_text(stmt, 1, cond.description.c_str(), cond.description.length(), NULL);
		if (cond.domoticzDeviceType != -1)
			sqlite3_bind_int(stmt, 2, cond.domoticzDeviceType);
		else
			sqlite3_bind_null(stmt, 2);
		if (cond.temperatureMin != -1)
			sqlite3_bind_double(stmt, 3, cond.temperatureMin);
		else
			sqlite3_bind_null(stmt, 3);
		if (cond.temperatureMax != -1)
			sqlite3_bind_double(stmt, 4, cond.temperatureMax);
		else
			sqlite3_bind_null(stmt, 4);
		if (cond.day != -1)
			sqlite3_bind_int(stmt, 5, cond.day);
		else
			sqlite3_bind_null(stmt, 5);
		if (cond.calendarId != -1)
			sqlite3_bind_int(stmt, 6, cond.calendarId);
		else
			sqlite3_bind_null(stmt, 6);
		sqlite3_bind_int(stmt, 7, cond.id);
		rc = sqlite3_step(stmt);
		sqlite3_finalize(stmt);
		return (rc == SQLITE_DONE);
	}
	else
		LOG4CPLUS_ERROR(log, LOG4CPLUS_TEXT("DataBase::updateCondition - sqlite3_prepare() failed: " << sqlite3_errmsg(db)));
	return false;
}

bool DataBase::updateGraph(sGraph &graph)
{
	sqlite3_stmt *stmt = NULL;
	const char *sql = "UPDATE graph SET position=?,description=?,condition_id=? WHERE rowid=?";
	int rc;

	rc = sqlite3_prepare(db, sql, strlen(sql), &stmt, NULL);
	if (rc == SQLITE_OK)
	{
		sqlite3_bind_int(stmt, 1, graph.position);
		sqlite3_bind_text(stmt, 2, graph.description.c_str(), graph.description.length(), NULL);
		if (graph.conditionId != -1)
			sqlite3_bind_int(stmt, 3, graph.conditionId);
		else
			sqlite3_bind_null(stmt, 3);
		sqlite3_bind_int(stmt, 4, graph.id);
		rc = sqlite3_step(stmt);
		sqlite3_finalize(stmt);
		return (rc == SQLITE_DONE);
	}
	else
		LOG4CPLUS_ERROR(log, LOG4CPLUS_TEXT("DataBase::updateGraph - sqlite3_prepare() failed: " << sqlite3_errmsg(db)));
	return false;
}

bool DataBase::updateGraphData(sGraph &graph)
{
	sqlite3_stmt *stmt = NULL;
	const char *sqlDelete = "DELETE FROM graph_data WHERE graph_id=?";
	const char *sql = "INSERT INTO graph_data(graph_id, time, value) VALUES(?,?,?)";
	int rc;

	rc = sqlite3_prepare(db, sqlDelete, strlen(sqlDelete), &stmt, NULL);
	if (rc == SQLITE_OK)
	{
		sqlite3_bind_int(stmt, 1, graph.id);
		rc = sqlite3_step(stmt);
		sqlite3_finalize(stmt);
		if (rc == SQLITE_DONE)
		{
			rc = sqlite3_prepare(db, sql, strlen(sql), &stmt, NULL);
			if (rc == SQLITE_OK)
			{
				BOOST_FOREACH(sGraphData data, graph.data)
				{
					sqlite3_bind_int(stmt, 1, graph.id);
					sqlite3_bind_int(stmt, 2, data.time);
					sqlite3_bind_double(stmt, 3, data.value);
					rc = sqlite3_step(stmt);
					sqlite3_reset(stmt);
				}
				sqlite3_finalize(stmt);
			}
		}
	}
	if (rc != SQLITE_OK && rc != SQLITE_DONE)
		LOG4CPLUS_ERROR(log, LOG4CPLUS_TEXT("DataBase::updateGraphData - sqlite3_prepare() failed: " << sqlite3_errmsg(db)));
	return (rc == SQLITE_OK || rc == SQLITE_DONE);
}

static int selectCondition(void *param, int ac, char **av, char **column)
{
	std::vector<sCondition> *r = static_cast<std::vector<sCondition>*>(param);

	if (ac == 7)
	{
		sCondition cond;

		cond.id = boost::lexical_cast<int>(av[0]);
		cond.description = av[1];
		cond.domoticzDeviceType = static_cast<eDomoticzDeviceType>(av[2] == NULL ? none : boost::lexical_cast<int>(av[2]));
		cond.temperatureMin = (av[3] == NULL ? -1 : boost::lexical_cast<float>(av[3]));
		cond.temperatureMax = (av[4] == NULL ? -1 : boost::lexical_cast<float>(av[4]));
		cond.day = (av[5] == NULL ? -1 : boost::lexical_cast<int>(av[5]));
		cond.calendarId = (av[6] == NULL ? -1 : boost::lexical_cast<int>(av[6]));
		r->push_back(cond);
	}
	return 0;
}

std::vector<sCondition> DataBase::getConditions()
{
	std::vector<sCondition> ret;
	int rc;

	rc = sqlite3_exec(db, "SELECT rowid,description,domoticz_device_type,temperature_min,temperature_max,day,calendar_id FROM condition ORDER BY rowid", selectCondition, &ret, NULL);
	if (rc != SQLITE_OK)
		LOG4CPLUS_ERROR(log, LOG4CPLUS_TEXT("DataBase::getConditions - SQL error"));
	return ret;
}

static int selectGraph(void *param, int ac, char **av, char **column)
{
	std::vector<sGraph> *r = static_cast<std::vector<sGraph>*>(param);

	if (ac == 4)
	{
		sGraph graph;

		graph.id = boost::lexical_cast<int>(av[0]);
		graph.position = boost::lexical_cast<int>(av[1]);
		graph.description = av[2];
		graph.conditionId = (av[3] == NULL ? -1 : boost::lexical_cast<int>(av[3]));
		r->push_back(graph);
	}
	return 0;
}

std::vector<sGraph> DataBase::getGraphs()
{
	std::vector<sGraph> ret;
	int rc;

	rc = sqlite3_exec(db, "SELECT rowid,position,description,condition_id FROM graph ORDER BY position", selectGraph, &ret, NULL);
	if (rc != SQLITE_OK)
		LOG4CPLUS_ERROR(log, LOG4CPLUS_TEXT("DataBase::getGraphs - SQL error"));
	return ret;
}

static int selectGraphData(void *param, int ac, char **av, char **column)
{
	sGraph *r = static_cast<sGraph*>(param);

	if (ac == 2)
	{
		sGraphData data;

		data.time = boost::lexical_cast<int>(av[0]);
		data.value = boost::lexical_cast<float>(av[1]);
		r->data.push_back(data);
	}
	return 0;
}

sCondition DataBase::getCondition(int id)
{
	std::stringstream ss;
	std::vector<sCondition> conds;
	sCondition ret;
	int rc;

	ss << "SELECT rowid,description,domoticz_device_type,temperature_min,temperature_max,day,calendar_id FROM condition WHERE rowid=" << id;
	rc = sqlite3_exec(db, ss.str().c_str(), selectCondition, &conds, NULL);
	if (rc != SQLITE_OK)
		LOG4CPLUS_ERROR(log, LOG4CPLUS_TEXT("DataBase::getCondition - SQL error graph"));
	else if (conds.size() == 1)
		ret = conds[0];
	return ret;
}

sGraph DataBase::getGraph(int id)
{
	std::stringstream ss;
	std::vector<sGraph> graphs;
	sGraph ret;
	int rc;

	ss << "SELECT rowid,position,description,condition_id FROM graph WHERE rowid=" << id;
	rc = sqlite3_exec(db, ss.str().c_str(), selectGraph, &graphs, NULL);
	if (rc != SQLITE_OK)
		LOG4CPLUS_ERROR(log, LOG4CPLUS_TEXT("DataBase::getGraph - SQL error graph"));
	else if (graphs.size() == 1)
	{
		ret = graphs[0];
		ss.str(std::string());
		ss << "SELECT time,value FROM graph_data WHERE graph_id=" << id;
		rc = sqlite3_exec(db, ss.str().c_str(), selectGraphData, &ret, NULL);
		if (rc != SQLITE_OK)
			LOG4CPLUS_ERROR(log, LOG4CPLUS_TEXT("DataBase::getGraph - SQL error graph_data"));
	}
	else
		LOG4CPLUS_ERROR(log, LOG4CPLUS_TEXT("DataBase::getGraph - no data"));
	return ret;
}

<|endoftext|>


<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chromeos/dbus/mock_dbus_thread_manager.h"

#include "chromeos/dbus/dbus_thread_manager_observer.h"
#include "chromeos/dbus/mock_bluetooth_adapter_client.h"
#include "chromeos/dbus/mock_bluetooth_device_client.h"
#include "chromeos/dbus/mock_bluetooth_input_client.h"
#include "chromeos/dbus/mock_bluetooth_manager_client.h"
#include "chromeos/dbus/mock_bluetooth_node_client.h"
#include "chromeos/dbus/mock_bluetooth_out_of_band_client.h"
#include "chromeos/dbus/mock_cros_disks_client.h"
#include "chromeos/dbus/mock_cryptohome_client.h"
#include "chromeos/dbus/mock_debug_daemon_client.h"
#include "chromeos/dbus/mock_shill_device_client.h"
#include "chromeos/dbus/mock_shill_ipconfig_client.h"
#include "chromeos/dbus/mock_shill_manager_client.h"
#include "chromeos/dbus/mock_shill_profile_client.h"
#include "chromeos/dbus/mock_shill_service_client.h"
#include "chromeos/dbus/mock_gsm_sms_client.h"
#include "chromeos/dbus/mock_image_burner_client.h"
#include "chromeos/dbus/mock_introspectable_client.h"
#include "chromeos/dbus/mock_modem_messaging_client.h"
#include "chromeos/dbus/mock_permission_broker_client.h"
#include "chromeos/dbus/mock_power_manager_client.h"
#include "chromeos/dbus/mock_session_manager_client.h"
#include "chromeos/dbus/mock_sms_client.h"
#include "chromeos/dbus/mock_speech_synthesizer_client.h"
#include "chromeos/dbus/mock_update_engine_client.h"
#include "chromeos/dbus/power_policy_controller.h"

using ::testing::AnyNumber;
using ::testing::Return;
using ::testing::ReturnNull;
using ::testing::_;

namespace chromeos {

MockDBusThreadManager::MockDBusThreadManager()
    : mock_bluetooth_adapter_client_(new MockBluetoothAdapterClient),
      mock_bluetooth_device_client_(new MockBluetoothDeviceClient),
      mock_bluetooth_input_client_(new MockBluetoothInputClient),
      mock_bluetooth_manager_client_(new MockBluetoothManagerClient),
      mock_bluetooth_node_client_(new MockBluetoothNodeClient),
      mock_bluetooth_out_of_band_client_(new MockBluetoothOutOfBandClient),
      mock_cros_disks_client_(new MockCrosDisksClient),
      mock_cryptohome_client_(new MockCryptohomeClient),
      mock_debugdaemon_client_(new MockDebugDaemonClient),
      mock_shill_device_client_(new MockShillDeviceClient),
      mock_shill_ipconfig_client_(new MockShillIPConfigClient),
      mock_shill_manager_client_(new MockShillManagerClient),
      mock_shill_profile_client_(new MockShillProfileClient),
      mock_shill_service_client_(new MockShillServiceClient),
      mock_gsm_sms_client_(new MockGsmSMSClient),
      mock_image_burner_client_(new MockImageBurnerClient),
      mock_introspectable_client_(new MockIntrospectableClient),
      mock_modem_messaging_client_(new MockModemMessagingClient),
      mock_permission_broker_client_(new MockPermissionBrokerClient),
      mock_power_manager_client_(new MockPowerManagerClient),
      mock_session_manager_client_(new MockSessionManagerClient),
      mock_sms_client_(new MockSMSClient),
      mock_speech_synthesizer_client_(new MockSpeechSynthesizerClient),
      mock_update_engine_client_(new MockUpdateEngineClient),
      power_policy_controller_(ALLOW_THIS_IN_INITIALIZER_LIST(
          new PowerPolicyController(this, mock_power_manager_client_.get()))) {
  EXPECT_CALL(*this, GetBluetoothAdapterClient())
      .WillRepeatedly(Return(mock_bluetooth_adapter_client_.get()));
  EXPECT_CALL(*this, GetBluetoothDeviceClient())
      .WillRepeatedly(Return(mock_bluetooth_device_client_.get()));
  EXPECT_CALL(*this, GetBluetoothInputClient())
      .WillRepeatedly(Return(mock_bluetooth_input_client_.get()));
  EXPECT_CALL(*this, GetBluetoothManagerClient())
      .WillRepeatedly(Return(mock_bluetooth_manager_client()));
  EXPECT_CALL(*this, GetBluetoothNodeClient())
      .WillRepeatedly(Return(mock_bluetooth_node_client_.get()));
  EXPECT_CALL(*this, GetBluetoothOutOfBandClient())
      .WillRepeatedly(Return(mock_bluetooth_out_of_band_client_.get()));
  EXPECT_CALL(*this, GetCrosDisksClient())
      .WillRepeatedly(Return(mock_cros_disks_client()));
  EXPECT_CALL(*this, GetCryptohomeClient())
      .WillRepeatedly(Return(mock_cryptohome_client()));
  EXPECT_CALL(*this, GetDebugDaemonClient())
      .WillRepeatedly(Return(mock_debugdaemon_client()));
  EXPECT_CALL(*this, GetShillDeviceClient())
      .WillRepeatedly(Return(mock_shill_device_client()));
  EXPECT_CALL(*this, GetShillIPConfigClient())
      .WillRepeatedly(Return(mock_shill_ipconfig_client()));
  EXPECT_CALL(*this, GetShillManagerClient())
      .WillRepeatedly(Return(mock_shill_manager_client()));
  EXPECT_CALL(*this, GetShillProfileClient())
      .WillRepeatedly(Return(mock_shill_profile_client()));
  EXPECT_CALL(*this, GetShillServiceClient())
      .WillRepeatedly(Return(mock_shill_service_client()));
  EXPECT_CALL(*this, GetGsmSMSClient())
      .WillRepeatedly(Return(mock_gsm_sms_client()));
  EXPECT_CALL(*this, GetImageBurnerClient())
      .WillRepeatedly(Return(mock_image_burner_client()));
  EXPECT_CALL(*this, GetIntrospectableClient())
      .WillRepeatedly(Return(mock_introspectable_client()));
  EXPECT_CALL(*this, GetModemMessagingClient())
      .WillRepeatedly(Return(mock_modem_messaging_client()));
  EXPECT_CALL(*this, GetPowerManagerClient())
      .WillRepeatedly(Return(mock_power_manager_client_.get()));
  EXPECT_CALL(*this, GetPowerPolicyController())
      .WillRepeatedly(Return(power_policy_controller_.get()));
  EXPECT_CALL(*this, GetSessionManagerClient())
      .WillRepeatedly(Return(mock_session_manager_client_.get()));
  EXPECT_CALL(*this, GetSMSClient())
      .WillRepeatedly(Return(mock_sms_client_.get()));
  EXPECT_CALL(*this, GetSpeechSynthesizerClient())
      .WillRepeatedly(Return(mock_speech_synthesizer_client_.get()));
  EXPECT_CALL(*this, GetUpdateEngineClient())
      .WillRepeatedly(Return(mock_update_engine_client_.get()));
  EXPECT_CALL(*this, GetIBusInputContextClient())
      .WillRepeatedly(ReturnNull());

  EXPECT_CALL(*this, GetSystemBus())
      .WillRepeatedly(ReturnNull());
  EXPECT_CALL(*this, GetIBusBus())
      .WillRepeatedly(ReturnNull());

  // These observers calls are used in ChromeBrowserMainPartsChromeos.
  EXPECT_CALL(*mock_power_manager_client_.get(), AddObserver(_))
      .Times(AnyNumber());
  EXPECT_CALL(*mock_power_manager_client_.get(), RemoveObserver(_))
      .Times(AnyNumber());
  EXPECT_CALL(*mock_power_manager_client_.get(), NotifyUserActivity(_))
      .Times(AnyNumber());
  EXPECT_CALL(*mock_power_manager_client_.get(), NotifyVideoActivity(_, _))
      .Times(AnyNumber());
  EXPECT_CALL(*mock_session_manager_client_.get(), AddObserver(_))
      .Times(AnyNumber());
  EXPECT_CALL(*mock_session_manager_client_.get(), RemoveObserver(_))
      .Times(AnyNumber());
  EXPECT_CALL(*mock_session_manager_client_.get(), HasObserver(_))
      .Times(AnyNumber());
  EXPECT_CALL(*mock_update_engine_client_.get(), AddObserver(_))
      .Times(AnyNumber());
  EXPECT_CALL(*mock_update_engine_client_.get(), RemoveObserver(_))
      .Times(AnyNumber());
  EXPECT_CALL(*mock_bluetooth_manager_client_.get(), AddObserver(_))
      .Times(AnyNumber());
  EXPECT_CALL(*mock_bluetooth_manager_client_.get(), RemoveObserver(_))
      .Times(AnyNumber());
  EXPECT_CALL(*mock_bluetooth_adapter_client_.get(), AddObserver(_))
      .Times(AnyNumber());
  EXPECT_CALL(*mock_bluetooth_adapter_client_.get(), RemoveObserver(_))
      .Times(AnyNumber());
  EXPECT_CALL(*mock_bluetooth_device_client_.get(), AddObserver(_))
      .Times(AnyNumber());
  EXPECT_CALL(*mock_bluetooth_device_client_.get(), RemoveObserver(_))
      .Times(AnyNumber());
  EXPECT_CALL(*mock_bluetooth_input_client_.get(), AddObserver(_))
      .Times(AnyNumber());
  EXPECT_CALL(*mock_bluetooth_input_client_.get(), RemoveObserver(_))
      .Times(AnyNumber());
  EXPECT_CALL(*mock_bluetooth_node_client_.get(), AddObserver(_))
      .Times(AnyNumber());
  EXPECT_CALL(*mock_bluetooth_node_client_.get(), RemoveObserver(_))
      .Times(AnyNumber());

  // Called from PowerMenuButton ctor.
  EXPECT_CALL(*mock_power_manager_client_.get(), RequestStatusUpdate(_))
      .Times(AnyNumber());

  // Called from DiskMountManager::Initialize(), ChromeBrowserMainPartsChromeos.
  EXPECT_CALL(*mock_cros_disks_client_.get(), SetUpConnections(_, _))
      .Times(AnyNumber());
  EXPECT_CALL(*mock_cros_disks_client_.get(),
              EnumerateAutoMountableDevices(_, _))
      .Times(AnyNumber());

  // Called from BluetoothManagerImpl ctor.
  EXPECT_CALL(*mock_bluetooth_manager_client_.get(), DefaultAdapter(_))
      .Times(AnyNumber());

  // Called from AsyncMethodCaller ctor and dtor.
  EXPECT_CALL(*mock_cryptohome_client_.get(), SetAsyncCallStatusHandlers(_, _))
      .Times(AnyNumber());
  EXPECT_CALL(*mock_cryptohome_client_.get(), ResetAsyncCallStatusHandlers())
      .Times(AnyNumber());

  // Called from BrightnessController::GetBrightnessPercent as part of ash tray
  // initialization.
  EXPECT_CALL(*mock_power_manager_client_.get(), GetScreenBrightnessPercent(_))
      .Times(AnyNumber());

  // Called from GeolocationHandler::Init().
  EXPECT_CALL(*mock_shill_manager_client_.get(), GetProperties(_))
      .Times(AnyNumber());
  EXPECT_CALL(*mock_shill_manager_client_.get(), AddPropertyChangedObserver(_))
      .Times(AnyNumber());
  EXPECT_CALL(*mock_shill_manager_client_.get(),
              RemovePropertyChangedObserver(_))
      .Times(AnyNumber());
}

MockDBusThreadManager::~MockDBusThreadManager() {
  FOR_EACH_OBSERVER(DBusThreadManagerObserver, observers_,
                    OnDBusThreadManagerDestroying(this));
}

void MockDBusThreadManager::AddObserver(DBusThreadManagerObserver* observer) {
  DCHECK(observer);
  observers_.AddObserver(observer);
}

void MockDBusThreadManager::RemoveObserver(
    DBusThreadManagerObserver* observer) {
  DCHECK(observer);
  observers_.RemoveObserver(observer);
}

}  // namespace chromeos
<commit_msg>Added more default expectations to MockDBusThreadManager.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chromeos/dbus/mock_dbus_thread_manager.h"

#include "chromeos/dbus/dbus_thread_manager_observer.h"
#include "chromeos/dbus/mock_bluetooth_adapter_client.h"
#include "chromeos/dbus/mock_bluetooth_device_client.h"
#include "chromeos/dbus/mock_bluetooth_input_client.h"
#include "chromeos/dbus/mock_bluetooth_manager_client.h"
#include "chromeos/dbus/mock_bluetooth_node_client.h"
#include "chromeos/dbus/mock_bluetooth_out_of_band_client.h"
#include "chromeos/dbus/mock_cros_disks_client.h"
#include "chromeos/dbus/mock_cryptohome_client.h"
#include "chromeos/dbus/mock_debug_daemon_client.h"
#include "chromeos/dbus/mock_shill_device_client.h"
#include "chromeos/dbus/mock_shill_ipconfig_client.h"
#include "chromeos/dbus/mock_shill_manager_client.h"
#include "chromeos/dbus/mock_shill_profile_client.h"
#include "chromeos/dbus/mock_shill_service_client.h"
#include "chromeos/dbus/mock_gsm_sms_client.h"
#include "chromeos/dbus/mock_image_burner_client.h"
#include "chromeos/dbus/mock_introspectable_client.h"
#include "chromeos/dbus/mock_modem_messaging_client.h"
#include "chromeos/dbus/mock_permission_broker_client.h"
#include "chromeos/dbus/mock_power_manager_client.h"
#include "chromeos/dbus/mock_session_manager_client.h"
#include "chromeos/dbus/mock_sms_client.h"
#include "chromeos/dbus/mock_speech_synthesizer_client.h"
#include "chromeos/dbus/mock_update_engine_client.h"
#include "chromeos/dbus/power_policy_controller.h"

using ::testing::AnyNumber;
using ::testing::Return;
using ::testing::ReturnNull;
using ::testing::_;

namespace chromeos {

MockDBusThreadManager::MockDBusThreadManager()
    : mock_bluetooth_adapter_client_(new MockBluetoothAdapterClient),
      mock_bluetooth_device_client_(new MockBluetoothDeviceClient),
      mock_bluetooth_input_client_(new MockBluetoothInputClient),
      mock_bluetooth_manager_client_(new MockBluetoothManagerClient),
      mock_bluetooth_node_client_(new MockBluetoothNodeClient),
      mock_bluetooth_out_of_band_client_(new MockBluetoothOutOfBandClient),
      mock_cros_disks_client_(new MockCrosDisksClient),
      mock_cryptohome_client_(new MockCryptohomeClient),
      mock_debugdaemon_client_(new MockDebugDaemonClient),
      mock_shill_device_client_(new MockShillDeviceClient),
      mock_shill_ipconfig_client_(new MockShillIPConfigClient),
      mock_shill_manager_client_(new MockShillManagerClient),
      mock_shill_profile_client_(new MockShillProfileClient),
      mock_shill_service_client_(new MockShillServiceClient),
      mock_gsm_sms_client_(new MockGsmSMSClient),
      mock_image_burner_client_(new MockImageBurnerClient),
      mock_introspectable_client_(new MockIntrospectableClient),
      mock_modem_messaging_client_(new MockModemMessagingClient),
      mock_permission_broker_client_(new MockPermissionBrokerClient),
      mock_power_manager_client_(new MockPowerManagerClient),
      mock_session_manager_client_(new MockSessionManagerClient),
      mock_sms_client_(new MockSMSClient),
      mock_speech_synthesizer_client_(new MockSpeechSynthesizerClient),
      mock_update_engine_client_(new MockUpdateEngineClient) {
  EXPECT_CALL(*this, GetBluetoothAdapterClient())
      .WillRepeatedly(Return(mock_bluetooth_adapter_client_.get()));
  EXPECT_CALL(*this, GetBluetoothDeviceClient())
      .WillRepeatedly(Return(mock_bluetooth_device_client_.get()));
  EXPECT_CALL(*this, GetBluetoothInputClient())
      .WillRepeatedly(Return(mock_bluetooth_input_client_.get()));
  EXPECT_CALL(*this, GetBluetoothManagerClient())
      .WillRepeatedly(Return(mock_bluetooth_manager_client()));
  EXPECT_CALL(*this, GetBluetoothNodeClient())
      .WillRepeatedly(Return(mock_bluetooth_node_client_.get()));
  EXPECT_CALL(*this, GetBluetoothOutOfBandClient())
      .WillRepeatedly(Return(mock_bluetooth_out_of_band_client_.get()));
  EXPECT_CALL(*this, GetCrosDisksClient())
      .WillRepeatedly(Return(mock_cros_disks_client()));
  EXPECT_CALL(*this, GetCryptohomeClient())
      .WillRepeatedly(Return(mock_cryptohome_client()));
  EXPECT_CALL(*this, GetDebugDaemonClient())
      .WillRepeatedly(Return(mock_debugdaemon_client()));
  EXPECT_CALL(*this, GetShillDeviceClient())
      .WillRepeatedly(Return(mock_shill_device_client()));
  EXPECT_CALL(*this, GetShillIPConfigClient())
      .WillRepeatedly(Return(mock_shill_ipconfig_client()));
  EXPECT_CALL(*this, GetShillManagerClient())
      .WillRepeatedly(Return(mock_shill_manager_client()));
  EXPECT_CALL(*this, GetShillProfileClient())
      .WillRepeatedly(Return(mock_shill_profile_client()));
  EXPECT_CALL(*this, GetShillServiceClient())
      .WillRepeatedly(Return(mock_shill_service_client()));
  EXPECT_CALL(*this, GetGsmSMSClient())
      .WillRepeatedly(Return(mock_gsm_sms_client()));
  EXPECT_CALL(*this, GetImageBurnerClient())
      .WillRepeatedly(Return(mock_image_burner_client()));
  EXPECT_CALL(*this, GetIntrospectableClient())
      .WillRepeatedly(Return(mock_introspectable_client()));
  EXPECT_CALL(*this, GetModemMessagingClient())
      .WillRepeatedly(Return(mock_modem_messaging_client()));
  EXPECT_CALL(*this, GetPowerManagerClient())
      .WillRepeatedly(Return(mock_power_manager_client_.get()));
  EXPECT_CALL(*this, GetSessionManagerClient())
      .WillRepeatedly(Return(mock_session_manager_client_.get()));
  EXPECT_CALL(*this, GetSMSClient())
      .WillRepeatedly(Return(mock_sms_client_.get()));
  EXPECT_CALL(*this, GetSpeechSynthesizerClient())
      .WillRepeatedly(Return(mock_speech_synthesizer_client_.get()));
  EXPECT_CALL(*this, GetUpdateEngineClient())
      .WillRepeatedly(Return(mock_update_engine_client_.get()));
  EXPECT_CALL(*this, GetIBusInputContextClient())
      .WillRepeatedly(ReturnNull());

  EXPECT_CALL(*this, GetSystemBus())
      .WillRepeatedly(ReturnNull());
  EXPECT_CALL(*this, GetIBusBus())
      .WillRepeatedly(ReturnNull());

  // |power_policy_controller_| calls some of these from the constructor, so
  // set these expectations before creating the controller.
  EXPECT_CALL(*mock_power_manager_client_.get(), AddObserver(_))
      .Times(AnyNumber());
  EXPECT_CALL(*mock_power_manager_client_.get(), RemoveObserver(_))
      .Times(AnyNumber());
  EXPECT_CALL(*mock_power_manager_client_.get(), NotifyUserActivity(_))
      .Times(AnyNumber());
  EXPECT_CALL(*mock_power_manager_client_.get(), NotifyVideoActivity(_, _))
      .Times(AnyNumber());
  EXPECT_CALL(*mock_power_manager_client_.get(), SetPolicy(_))
      .Times(AnyNumber());
  power_policy_controller_.reset(
      new PowerPolicyController(this, mock_power_manager_client_.get()));
  EXPECT_CALL(*this, GetPowerPolicyController())
      .WillRepeatedly(Return(power_policy_controller_.get()));

  // These observers calls are used in ChromeBrowserMainPartsChromeos.
  EXPECT_CALL(*mock_session_manager_client_.get(), AddObserver(_))
      .Times(AnyNumber());
  EXPECT_CALL(*mock_session_manager_client_.get(), RemoveObserver(_))
      .Times(AnyNumber());
  EXPECT_CALL(*mock_session_manager_client_.get(), HasObserver(_))
      .Times(AnyNumber());
  EXPECT_CALL(*mock_update_engine_client_.get(), AddObserver(_))
      .Times(AnyNumber());
  EXPECT_CALL(*mock_update_engine_client_.get(), RemoveObserver(_))
      .Times(AnyNumber());
  EXPECT_CALL(*mock_bluetooth_manager_client_.get(), AddObserver(_))
      .Times(AnyNumber());
  EXPECT_CALL(*mock_bluetooth_manager_client_.get(), RemoveObserver(_))
      .Times(AnyNumber());
  EXPECT_CALL(*mock_bluetooth_adapter_client_.get(), AddObserver(_))
      .Times(AnyNumber());
  EXPECT_CALL(*mock_bluetooth_adapter_client_.get(), RemoveObserver(_))
      .Times(AnyNumber());
  EXPECT_CALL(*mock_bluetooth_device_client_.get(), AddObserver(_))
      .Times(AnyNumber());
  EXPECT_CALL(*mock_bluetooth_device_client_.get(), RemoveObserver(_))
      .Times(AnyNumber());
  EXPECT_CALL(*mock_bluetooth_input_client_.get(), AddObserver(_))
      .Times(AnyNumber());
  EXPECT_CALL(*mock_bluetooth_input_client_.get(), RemoveObserver(_))
      .Times(AnyNumber());
  EXPECT_CALL(*mock_bluetooth_node_client_.get(), AddObserver(_))
      .Times(AnyNumber());
  EXPECT_CALL(*mock_bluetooth_node_client_.get(), RemoveObserver(_))
      .Times(AnyNumber());

  // Called from PowerMenuButton ctor.
  EXPECT_CALL(*mock_power_manager_client_.get(), RequestStatusUpdate(_))
      .Times(AnyNumber());

  // Called from DiskMountManager::Initialize(), ChromeBrowserMainPartsChromeos.
  EXPECT_CALL(*mock_cros_disks_client_.get(), SetUpConnections(_, _))
      .Times(AnyNumber());
  EXPECT_CALL(*mock_cros_disks_client_.get(),
              EnumerateAutoMountableDevices(_, _))
      .Times(AnyNumber());

  // Called from BluetoothManagerImpl ctor.
  EXPECT_CALL(*mock_bluetooth_manager_client_.get(), DefaultAdapter(_))
      .Times(AnyNumber());

  // Called from AsyncMethodCaller ctor and dtor.
  EXPECT_CALL(*mock_cryptohome_client_.get(), SetAsyncCallStatusHandlers(_, _))
      .Times(AnyNumber());
  EXPECT_CALL(*mock_cryptohome_client_.get(), ResetAsyncCallStatusHandlers())
      .Times(AnyNumber());

  // Called from BrightnessController::GetBrightnessPercent as part of ash tray
  // initialization.
  EXPECT_CALL(*mock_power_manager_client_.get(), GetScreenBrightnessPercent(_))
      .Times(AnyNumber());

  // Called from GeolocationHandler::Init().
  EXPECT_CALL(*mock_shill_manager_client_.get(), GetProperties(_))
      .Times(AnyNumber());
  EXPECT_CALL(*mock_shill_manager_client_.get(), AddPropertyChangedObserver(_))
      .Times(AnyNumber());
  EXPECT_CALL(*mock_shill_manager_client_.get(),
              RemovePropertyChangedObserver(_))
      .Times(AnyNumber());
}

MockDBusThreadManager::~MockDBusThreadManager() {
  FOR_EACH_OBSERVER(DBusThreadManagerObserver, observers_,
                    OnDBusThreadManagerDestroying(this));
}

void MockDBusThreadManager::AddObserver(DBusThreadManagerObserver* observer) {
  DCHECK(observer);
  observers_.AddObserver(observer);
}

void MockDBusThreadManager::RemoveObserver(
    DBusThreadManagerObserver* observer) {
  DCHECK(observer);
  observers_.RemoveObserver(observer);
}

}  // namespace chromeos
<|endoftext|>


<commit_before>#include <stdlib.h>

#include "util/jsmn.h"

/**
 * Allocates a fresh unused token from the token pull.
 */
static jsmntok_t *jsmn_alloc_token(jsmn_parser *parser,
		jsmntok_t *tokens, size_t num_tokens) {
	jsmntok_t *tok;
	if (parser->toknext >= num_tokens) {
		return NULL;
	}
	tok = &tokens[parser->toknext++];
	tok->start = tok->end = -1;
	tok->size = 0;
#ifdef JSMN_PARENT_LINKS
	tok->parent = -1;
#endif
	return tok;
}

/**
 * Fills token type and boundaries.
 */
static void jsmn_fill_token(jsmntok_t *token, jsmntype_t type,
                            int start, int end) {
	token->type = type;
	token->start = start;
	token->end = end;
	token->size = 0;
}

/**
 * Fills next available token with JSON primitive.
 */
static jsmnerr_t jsmn_parse_primitive(jsmn_parser *parser, const char *js,
		size_t len, jsmntok_t *tokens, size_t num_tokens) {
	jsmntok_t *token;
	int start;

	start = parser->pos;

	for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++) {
		switch (js[parser->pos]) {
#ifndef JSMN_STRICT
			/* In strict mode primitive must be followed by "," or "}" or "]" */
			case ':':
#endif
			case '\t' : case '\r' : case '\n' : case ' ' :
			case ','  : case ']'  : case '}' :
				goto found;
		}
		if (js[parser->pos] < 32 || js[parser->pos] >= 127) {
			parser->pos = start;
			return JSMN_ERROR_INVAL;
		}
	}
#ifdef JSMN_STRICT
	/* In strict mode primitive must be followed by a comma/object/array */
	parser->pos = start;
	return JSMN_ERROR_PART;
#endif

found:
	if (tokens == NULL) {
		parser->pos--;
		return static_cast<jsmnerr_t>(0);
	}
	token = jsmn_alloc_token(parser, tokens, num_tokens);
	if (token == NULL) {
		parser->pos = start;
		return JSMN_ERROR_NOMEM;
	}
	jsmn_fill_token(token, JSMN_PRIMITIVE, start, parser->pos);
#ifdef JSMN_PARENT_LINKS
	token->parent = parser->toksuper;
#endif
	parser->pos--;
	return static_cast<jsmnerr_t>(0);
}

/**
 * Filsl next token with JSON string.
 */
static jsmnerr_t jsmn_parse_string(jsmn_parser *parser, const char *js,
		size_t len, jsmntok_t *tokens, size_t num_tokens) {
	jsmntok_t *token;

	int start = parser->pos;

	parser->pos++;

	/* Skip starting quote */
	for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++) {
		char c = js[parser->pos];

		/* Quote: end of string */
		if (c == '\"') {
			if (tokens == NULL) {
				return static_cast<jsmnerr_t>(0);
			}
			token = jsmn_alloc_token(parser, tokens, num_tokens);
			if (token == NULL) {
				parser->pos = start;
				return JSMN_ERROR_NOMEM;
			}
			jsmn_fill_token(token, JSMN_STRING, start+1, parser->pos);
#ifdef JSMN_PARENT_LINKS
			token->parent = parser->toksuper;
#endif
			return static_cast<jsmnerr_t>(0);
		}

		/* Backslash: Quoted symbol expected */
		if (c == '\\') {
			parser->pos++;
			switch (js[parser->pos]) {
				/* Allowed escaped symbols */
				case '\"': case '/' : case '\\' : case 'b' :
				case 'f' : case 'r' : case 'n'  : case 't' :
					break;
				/* Allows escaped symbol \uXXXX */
				case 'u': {
						parser->pos++;
						int i = 0;
						for(; i < 4 && js[parser->pos] != '\0'; i++) {
							/* If it isn't a hex character we have an error */
							if(!((js[parser->pos] >= 48 && js[parser->pos] <= 57) || /* 0-9 */
										(js[parser->pos] >= 65 && js[parser->pos] <= 70) || /* A-F */
										(js[parser->pos] >= 97 && js[parser->pos] <= 102))) { /* a-f */
								parser->pos = start;
								return JSMN_ERROR_INVAL;
							}
							parser->pos++;
						}
						parser->pos--;

						break;
					}
				/* Unexpected symbol */
				default:
					{
						parser->pos = start;
						return JSMN_ERROR_INVAL;
					}
			}
		}
	}
	parser->pos = start;
	return JSMN_ERROR_PART;
}

/**
 * Parse JSON string and fill tokens.
 */
jsmnerr_t jsmn_parse(jsmn_parser *parser, const char *js, size_t len,
		jsmntok_t *tokens, unsigned int num_tokens) {
	jsmnerr_t r;
	int i;
	jsmntok_t *token;
	int count = 0;

	for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++) {
		char c;
		jsmntype_t type;

		c = js[parser->pos];
		switch (c) {
			case '{': case '[':
				count++;
				if (tokens == NULL) {
					break;
				}
				token = jsmn_alloc_token(parser, tokens, num_tokens);
				if (token == NULL)
					return JSMN_ERROR_NOMEM;
				if (parser->toksuper != -1) {
					tokens[parser->toksuper].size++;
#ifdef JSMN_PARENT_LINKS
					token->parent = parser->toksuper;
#endif
				}
				token->type = (c == '{' ? JSMN_OBJECT : JSMN_ARRAY);
				token->start = parser->pos;
				parser->toksuper = parser->toknext - 1;
				break;
			case '}': case ']':
				if (tokens == NULL)
					break;
				type = (c == '}' ? JSMN_OBJECT : JSMN_ARRAY);
#ifdef JSMN_PARENT_LINKS
				if (parser->toknext < 1) {
					return JSMN_ERROR_INVAL;
				}
				token = &tokens[parser->toknext - 1];
				for (;;) {
					if (token->start != -1 && token->end == -1) {
						if (token->type != type) {
							return JSMN_ERROR_INVAL;
						}
						token->end = parser->pos + 1;
						parser->toksuper = token->parent;
						break;
					}
					if (token->parent == -1) {
						break;
					}
					token = &tokens[token->parent];
				}
#else
				for (i = parser->toknext - 1; i >= 0; i--) {
					token = &tokens[i];
					if (token->start != -1 && token->end == -1) {
						if (token->type != type) {
							return JSMN_ERROR_INVAL;
						}
						parser->toksuper = -1;
						token->end = parser->pos + 1;
						break;
					}
				}
				/* Error if unmatched closing bracket */
				if (i == -1) return JSMN_ERROR_INVAL;
				for (; i >= 0; i--) {
					token = &tokens[i];
					if (token->start != -1 && token->end == -1) {
						parser->toksuper = i;
						break;
					}
				}
#endif
				break;
			case '\"':
				r = jsmn_parse_string(parser, js, len, tokens, num_tokens);
				if (r < 0) return r;
				count++;
				if (parser->toksuper != -1 && tokens != NULL)
					tokens[parser->toksuper].size++;
				break;
			case '\t' : case '\r' : case '\n' : case ':' : case ',': case ' ':
				break;
#ifdef JSMN_STRICT
			/* In strict mode primitives are: numbers and booleans */
			case '-': case '0': case '1' : case '2': case '3' : case '4':
			case '5': case '6': case '7' : case '8': case '9':
			case 't': case 'f': case 'n' :
#else
			/* In non-strict mode every unquoted value is a primitive */
			default:
#endif
				r = jsmn_parse_primitive(parser, js, len, tokens, num_tokens);
				if (r < 0) return r;
				count++;
				if (parser->toksuper != -1 && tokens != NULL)
					tokens[parser->toksuper].size++;
				break;

#ifdef JSMN_STRICT
			/* Unexpected char in strict mode */
			default:
				return JSMN_ERROR_INVAL;
#endif
		}
	}

	for (i = parser->toknext - 1; i >= 0; i--) {
		/* Unmatched opened object or array */
		if (tokens[i].start != -1 && tokens[i].end == -1) {
			return JSMN_ERROR_PART;
		}
	}

	return static_cast<jsmnerr_t>(count);
}

/**
 * Creates a new parser based over a given  buffer with an array of tokens
 * available.
 */
void jsmn_init(jsmn_parser *parser) {
	parser->pos = 0;
	parser->toknext = 0;
	parser->toksuper = -1;
}

<commit_msg>[jsnm] added license;<commit_after>/*
Copyright (c) 2010 Serge A. Zaitsev

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#include <stdlib.h>
#include "util/jsmn.h"

/**
 * Allocates a fresh unused token from the token pull.
 */
static jsmntok_t *jsmn_alloc_token(jsmn_parser *parser,
		jsmntok_t *tokens, size_t num_tokens) {
	jsmntok_t *tok;
	if (parser->toknext >= num_tokens) {
		return NULL;
	}
	tok = &tokens[parser->toknext++];
	tok->start = tok->end = -1;
	tok->size = 0;
#ifdef JSMN_PARENT_LINKS
	tok->parent = -1;
#endif
	return tok;
}

/**
 * Fills token type and boundaries.
 */
static void jsmn_fill_token(jsmntok_t *token, jsmntype_t type,
                            int start, int end) {
	token->type = type;
	token->start = start;
	token->end = end;
	token->size = 0;
}

/**
 * Fills next available token with JSON primitive.
 */
static jsmnerr_t jsmn_parse_primitive(jsmn_parser *parser, const char *js,
		size_t len, jsmntok_t *tokens, size_t num_tokens) {
	jsmntok_t *token;
	int start;

	start = parser->pos;

	for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++) {
		switch (js[parser->pos]) {
#ifndef JSMN_STRICT
			/* In strict mode primitive must be followed by "," or "}" or "]" */
			case ':':
#endif
			case '\t' : case '\r' : case '\n' : case ' ' :
			case ','  : case ']'  : case '}' :
				goto found;
		}
		if (js[parser->pos] < 32 || js[parser->pos] >= 127) {
			parser->pos = start;
			return JSMN_ERROR_INVAL;
		}
	}
#ifdef JSMN_STRICT
	/* In strict mode primitive must be followed by a comma/object/array */
	parser->pos = start;
	return JSMN_ERROR_PART;
#endif

found:
	if (tokens == NULL) {
		parser->pos--;
		return static_cast<jsmnerr_t>(0);
	}
	token = jsmn_alloc_token(parser, tokens, num_tokens);
	if (token == NULL) {
		parser->pos = start;
		return JSMN_ERROR_NOMEM;
	}
	jsmn_fill_token(token, JSMN_PRIMITIVE, start, parser->pos);
#ifdef JSMN_PARENT_LINKS
	token->parent = parser->toksuper;
#endif
	parser->pos--;
	return static_cast<jsmnerr_t>(0);
}

/**
 * Filsl next token with JSON string.
 */
static jsmnerr_t jsmn_parse_string(jsmn_parser *parser, const char *js,
		size_t len, jsmntok_t *tokens, size_t num_tokens) {
	jsmntok_t *token;

	int start = parser->pos;

	parser->pos++;

	/* Skip starting quote */
	for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++) {
		char c = js[parser->pos];

		/* Quote: end of string */
		if (c == '\"') {
			if (tokens == NULL) {
				return static_cast<jsmnerr_t>(0);
			}
			token = jsmn_alloc_token(parser, tokens, num_tokens);
			if (token == NULL) {
				parser->pos = start;
				return JSMN_ERROR_NOMEM;
			}
			jsmn_fill_token(token, JSMN_STRING, start+1, parser->pos);
#ifdef JSMN_PARENT_LINKS
			token->parent = parser->toksuper;
#endif
			return static_cast<jsmnerr_t>(0);
		}

		/* Backslash: Quoted symbol expected */
		if (c == '\\') {
			parser->pos++;
			switch (js[parser->pos]) {
				/* Allowed escaped symbols */
				case '\"': case '/' : case '\\' : case 'b' :
				case 'f' : case 'r' : case 'n'  : case 't' :
					break;
				/* Allows escaped symbol \uXXXX */
				case 'u': {
						parser->pos++;
						int i = 0;
						for(; i < 4 && js[parser->pos] != '\0'; i++) {
							/* If it isn't a hex character we have an error */
							if(!((js[parser->pos] >= 48 && js[parser->pos] <= 57) || /* 0-9 */
										(js[parser->pos] >= 65 && js[parser->pos] <= 70) || /* A-F */
										(js[parser->pos] >= 97 && js[parser->pos] <= 102))) { /* a-f */
								parser->pos = start;
								return JSMN_ERROR_INVAL;
							}
							parser->pos++;
						}
						parser->pos--;

						break;
					}
				/* Unexpected symbol */
				default:
					{
						parser->pos = start;
						return JSMN_ERROR_INVAL;
					}
			}
		}
	}
	parser->pos = start;
	return JSMN_ERROR_PART;
}

/**
 * Parse JSON string and fill tokens.
 */
jsmnerr_t jsmn_parse(jsmn_parser *parser, const char *js, size_t len,
		jsmntok_t *tokens, unsigned int num_tokens) {
	jsmnerr_t r;
	int i;
	jsmntok_t *token;
	int count = 0;

	for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++) {
		char c;
		jsmntype_t type;

		c = js[parser->pos];
		switch (c) {
			case '{': case '[':
				count++;
				if (tokens == NULL) {
					break;
				}
				token = jsmn_alloc_token(parser, tokens, num_tokens);
				if (token == NULL)
					return JSMN_ERROR_NOMEM;
				if (parser->toksuper != -1) {
					tokens[parser->toksuper].size++;
#ifdef JSMN_PARENT_LINKS
					token->parent = parser->toksuper;
#endif
				}
				token->type = (c == '{' ? JSMN_OBJECT : JSMN_ARRAY);
				token->start = parser->pos;
				parser->toksuper = parser->toknext - 1;
				break;
			case '}': case ']':
				if (tokens == NULL)
					break;
				type = (c == '}' ? JSMN_OBJECT : JSMN_ARRAY);
#ifdef JSMN_PARENT_LINKS
				if (parser->toknext < 1) {
					return JSMN_ERROR_INVAL;
				}
				token = &tokens[parser->toknext - 1];
				for (;;) {
					if (token->start != -1 && token->end == -1) {
						if (token->type != type) {
							return JSMN_ERROR_INVAL;
						}
						token->end = parser->pos + 1;
						parser->toksuper = token->parent;
						break;
					}
					if (token->parent == -1) {
						break;
					}
					token = &tokens[token->parent];
				}
#else
				for (i = parser->toknext - 1; i >= 0; i--) {
					token = &tokens[i];
					if (token->start != -1 && token->end == -1) {
						if (token->type != type) {
							return JSMN_ERROR_INVAL;
						}
						parser->toksuper = -1;
						token->end = parser->pos + 1;
						break;
					}
				}
				/* Error if unmatched closing bracket */
				if (i == -1) return JSMN_ERROR_INVAL;
				for (; i >= 0; i--) {
					token = &tokens[i];
					if (token->start != -1 && token->end == -1) {
						parser->toksuper = i;
						break;
					}
				}
#endif
				break;
			case '\"':
				r = jsmn_parse_string(parser, js, len, tokens, num_tokens);
				if (r < 0) return r;
				count++;
				if (parser->toksuper != -1 && tokens != NULL)
					tokens[parser->toksuper].size++;
				break;
			case '\t' : case '\r' : case '\n' : case ':' : case ',': case ' ':
				break;
#ifdef JSMN_STRICT
			/* In strict mode primitives are: numbers and booleans */
			case '-': case '0': case '1' : case '2': case '3' : case '4':
			case '5': case '6': case '7' : case '8': case '9':
			case 't': case 'f': case 'n' :
#else
			/* In non-strict mode every unquoted value is a primitive */
			default:
#endif
				r = jsmn_parse_primitive(parser, js, len, tokens, num_tokens);
				if (r < 0) return r;
				count++;
				if (parser->toksuper != -1 && tokens != NULL)
					tokens[parser->toksuper].size++;
				break;

#ifdef JSMN_STRICT
			/* Unexpected char in strict mode */
			default:
				return JSMN_ERROR_INVAL;
#endif
		}
	}

	for (i = parser->toknext - 1; i >= 0; i--) {
		/* Unmatched opened object or array */
		if (tokens[i].start != -1 && tokens[i].end == -1) {
			return JSMN_ERROR_PART;
		}
	}

	return static_cast<jsmnerr_t>(count);
}

/**
 * Creates a new parser based over a given  buffer with an array of tokens
 * available.
 */
void jsmn_init(jsmn_parser *parser) {
	parser->pos = 0;
	parser->toknext = 0;
	parser->toksuper = -1;
}

<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2006 - 2015, Paul Beckingham, Federico Hernandez.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////

#include <cmake.h>
#include <iostream>
#include <stdlib.h>
#include <main.h>
#include <util.h>
#include <test.h>

Context context;

////////////////////////////////////////////////////////////////////////////////
int main (int argc, char** argv)
{
  UnitTest t (23);

  // Ensure environment has no influence.
  unsetenv ("TASKDATA");
  unsetenv ("TASKRC");

  // TODO bool confirm (const std::string&);
  // TODO int confirm4 (const std::string&);

  // std::string formatBytes (size_t);
  t.is (formatBytes (0), "0 B", "0 -> 0 B");

  t.is (formatBytes (994),  "994 B", "994 -> 994 B");
  t.is (formatBytes (995),  "1.0 KiB", "995 -> 1.0 KiB");
  t.is (formatBytes (999),  "1.0 KiB", "999 -> 1.0 KiB");
  t.is (formatBytes (1000), "1.0 KiB", "1000 -> 1.0 KiB");
  t.is (formatBytes (1001), "1.0 KiB", "1001 -> 1.0 KiB");

  t.is (formatBytes (999999),  "1.0 MiB", "999999 -> 1.0 MiB");
  t.is (formatBytes (1000000), "1.0 MiB", "1000000 -> 1.0 MiB");
  t.is (formatBytes (1000001), "1.0 MiB", "1000001 -> 1.0 MiB");

  t.is (formatBytes (999999999),  "1.0 GiB", "999999999 -> 1.0 GiB");
  t.is (formatBytes (1000000000), "1.0 GiB", "1000000000 -> 1.0 GiB");
  t.is (formatBytes (1000000001), "1.0 GiB", "1000000001 -> 1.0 GiB");

  // TODO const std::string uuid ();

  // TODO These are in feedback.cpp, not util.cpp.
  // std::string taskDiff (const Task&, const Task&);
  Task left;
  left.set ("zero", "0");
  left.set ("one",  1);
  left.set ("two",  2);

  Task right;
  right.set ("zero",  "00");
  right.set ("two",   2);
  right.set ("three", 3);

  Task rightAgain (right);

  std::string output = taskDifferences (left, right);
  t.ok (taskDiff (left, right),                                                     "Detected changes");
  t.ok (output.find ("Zero will be changed from '0' to '00'") != std::string::npos, "Detected change zero:0 -> zero:00");
  t.ok (output.find ("One will be deleted")                   != std::string::npos, "Detected deletion one:1 ->");
  t.ok (output.find ("Two")                                   == std::string::npos, "Detected no change two:2 -> two:2");
  t.ok (output.find ("Three will be set to '3'")              != std::string::npos, "Detected addition -> three:3");

  t.notok (taskDiff (right, rightAgain),                                            "No changes detected");
  output = taskDifferences (right, rightAgain);
  t.ok (output.find ("No changes will be made")               != std::string::npos, "No changes detected");

  // std::vector<std::string> indentProject (const std::string&, const std::string whitespace="  ", char delimiter='.');
  t.is (indentProject (""),              "",                  "indentProject '' -> ''");
  t.is (indentProject ("one"),           "one",               "indentProject 'one' -> 'one'");
  t.is (indentProject ("one.two"),       "  two",         "indentProject 'one.two' -> '  two'");
  t.is (indentProject ("one.two.three"), "    three", "indentProject 'one.two.three' -> '    three'");

  return 0;
}

////////////////////////////////////////////////////////////////////////////////

<commit_msg>Tests: Fixed test that will no longer compile<commit_after>////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2006 - 2015, Paul Beckingham, Federico Hernandez.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////

#include <cmake.h>
#include <iostream>
#include <stdlib.h>
#include <main.h>
#include <util.h>
#include <test.h>

Context context;

////////////////////////////////////////////////////////////////////////////////
int main (int argc, char** argv)
{
  UnitTest t (22);

  // Ensure environment has no influence.
  unsetenv ("TASKDATA");
  unsetenv ("TASKRC");

  // TODO bool confirm (const std::string&);
  // TODO int confirm4 (const std::string&);

  // std::string formatBytes (size_t);
  t.is (formatBytes (0), "0 B", "0 -> 0 B");

  t.is (formatBytes (994),  "994 B", "994 -> 994 B");
  t.is (formatBytes (995),  "1.0 KiB", "995 -> 1.0 KiB");
  t.is (formatBytes (999),  "1.0 KiB", "999 -> 1.0 KiB");
  t.is (formatBytes (1000), "1.0 KiB", "1000 -> 1.0 KiB");
  t.is (formatBytes (1001), "1.0 KiB", "1001 -> 1.0 KiB");

  t.is (formatBytes (999999),  "1.0 MiB", "999999 -> 1.0 MiB");
  t.is (formatBytes (1000000), "1.0 MiB", "1000000 -> 1.0 MiB");
  t.is (formatBytes (1000001), "1.0 MiB", "1000001 -> 1.0 MiB");

  t.is (formatBytes (999999999),  "1.0 GiB", "999999999 -> 1.0 GiB");
  t.is (formatBytes (1000000000), "1.0 GiB", "1000000000 -> 1.0 GiB");
  t.is (formatBytes (1000000001), "1.0 GiB", "1000000001 -> 1.0 GiB");

  // TODO const std::string uuid ();

  // TODO These are in feedback.cpp, not util.cpp.
  Task left;
  left.set ("zero", "0");
  left.set ("one",  1);
  left.set ("two",  2);

  Task right;
  right.set ("zero",  "00");
  right.set ("two",   2);
  right.set ("three", 3);

  Task rightAgain (right);

  std::string output = taskDifferences (left, right);
  t.ok (left != right,                                                              "Detected changes");
  t.ok (output.find ("Zero will be changed from '0' to '00'") != std::string::npos, "Detected change zero:0 -> zero:00");
  t.ok (output.find ("One will be deleted")                   != std::string::npos, "Detected deletion one:1 ->");
  t.ok (output.find ("Two")                                   == std::string::npos, "Detected no change two:2 -> two:2");
  t.ok (output.find ("Three will be set to '3'")              != std::string::npos, "Detected addition -> three:3");

  output = taskDifferences (right, rightAgain);
  t.ok (output.find ("No changes will be made")               != std::string::npos, "No changes detected");

  // std::vector<std::string> indentProject (const std::string&, const std::string whitespace="  ", char delimiter='.');
  t.is (indentProject (""),              "",                  "indentProject '' -> ''");
  t.is (indentProject ("one"),           "one",               "indentProject 'one' -> 'one'");
  t.is (indentProject ("one.two"),       "  two",         "indentProject 'one.two' -> '  two'");
  t.is (indentProject ("one.two.three"), "    three", "indentProject 'one.two.three' -> '    three'");

  return 0;
}

////////////////////////////////////////////////////////////////////////////////

<|endoftext|>


<commit_before>/*
 * Copyright 2006-2008 The FLWOR Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "zorbautils/fatal.h"
#include "zorbautils/mutex.h"
#include "zorbautils/condition.h"
#include <cassert>
#include <time.h>

namespace zorba {

#ifdef ZORBA_HAVE_PTHREAD_H

Condition::Condition(Mutex& m) : theMutex(m)
{
  int ret = pthread_cond_init(&theCondition, NULL);

  ZORBA_FATAL(!ret, "Failed to create condition variable. Error code = " << ret);
}

Condition::~Condition()
{
  int ret = pthread_cond_destroy(&theCondition);

  ZORBA_FATAL(!ret, "Failed to destroy condition variable. Error code = " << ret);
}

void Condition::wait()
{
  int ret = pthread_cond_wait(&theCondition, theMutex.getMutex());

  ZORBA_FATAL(!ret, "Failed to wait on condition variable. Error code = " << ret);
}

void Condition::timedWait(unsigned long aTimeInsMs)
{
  struct timespec lTimespec;
  clock_gettime(CLOCK_REALTIME, &lTimespec);
  lTimespec.tv_sec += aTimeInsMs/1000;
  int ret = pthread_cond_timedwait(&theCondition, theMutex.getMutex(), &lTimespec);

  // error other than ETIMEDOUT
  ZORBA_FATAL(!ret || ret == 110, "Failed to wait on condition variable. Error code = " << ret);
}

void Condition::signal()
{
  int ret = pthread_cond_signal(&theCondition);

  ZORBA_FATAL(!ret, "Failed to signal condition variable. Error code = " << ret);
}

void Condition::broadcast()
{
  int ret = pthread_cond_broadcast(&theCondition);

  ZORBA_FATAL(!ret, "Failed to brodcast condition variable. Error code = " << ret);
}

#elif WIN32

Condition::Condition(Mutex& m) : theMutex(m)
{
//  int ret = pthread_cond_init(&theCondition, NULL);
	cond_event[0] = CreateEvent(NULL, FALSE, FALSE, NULL);//auto-reset, for signal
  assert(cond_event[0] != NULL);
	cond_event[1] = CreateEvent(NULL, TRUE, FALSE, NULL);//manual-reset, for broadcast
  assert(cond_event[1] != NULL);

  cond_door = CreateEvent(NULL, FALSE, TRUE, NULL);//auto-reset, initial ON
  assert(cond_door != NULL);
  cond_broadcast = CreateEvent(NULL, FALSE, FALSE, NULL);//auto-reset, initial OFF
  assert(cond_broadcast != NULL);

  InitializeCriticalSection(&cond_cs);
  waiters = 0;

  ZORBA_FATAL(cond_event[0]!=INVALID_HANDLE_VALUE && cond_event[1]!=INVALID_HANDLE_VALUE && cond_door!=INVALID_HANDLE_VALUE && cond_broadcast!=INVALID_HANDLE_VALUE,
            "Failed to create condition variable. Error code = " << GetLastError());
}

Condition::~Condition()
{
//  int ret = pthread_cond_destroy(&theCondition);
  BOOL ret = CloseHandle(cond_event[0]);
  ret &= CloseHandle(cond_event[1]);
  ret &= CloseHandle(cond_door);
  ret &= CloseHandle(cond_broadcast);

  DeleteCriticalSection(&cond_cs);

  ZORBA_FATAL(ret, "Failed to destroy condition variable. Error code = " << GetLastError());
}

void Condition::wait()
{
  //int ret = pthread_cond_wait(&theCondition, theMutex.getMutex());

  WaitForSingleObject(cond_door, INFINITE);

  EnterCriticalSection(&cond_cs);
  waiters++;
  LeaveCriticalSection(&cond_cs);

  SetEvent(cond_door);//let other waits/signal/broadcast to enter

  theMutex.unlock();
	int result = WaitForMultipleObjects(2,cond_event, FALSE, INFINITE);//wait any of them

  EnterCriticalSection(&cond_cs);
  waiters--;
  if((result == WAIT_OBJECT_0 + 1) && !waiters || (result == WAIT_OBJECT_0))
  {
    SetEvent(cond_broadcast);
  }
  LeaveCriticalSection(&cond_cs);

	theMutex.lock();
}

void Condition::signal()
{
  //int ret = pthread_cond_signal(&theCondition);
  WaitForSingleObject(cond_door, INFINITE);//allow one broadcast/signal at a time

  EnterCriticalSection(&cond_cs);
  bool have_waiters = waiters > 0;
  LeaveCriticalSection(&cond_cs);

  if(!have_waiters)
  {
    SetEvent(cond_door);//no reason to bother
    return;
  }

  SetEvent(cond_event[0]);

  WaitForSingleObject(cond_broadcast, INFINITE);//wait for one waiting thread to wake up

  SetEvent(cond_door);

  //ZORBA_FATAL(!ret, "Failed to signal condition variable. Error code = " << GetLastError());
}

void Condition::broadcast()
{
  //int ret = pthread_cond_broadcast(&theCondition);
  WaitForSingleObject(cond_door, INFINITE);//allow one broadcast/signal at a time

  EnterCriticalSection(&cond_cs);
  bool have_waiters = waiters > 0;
  LeaveCriticalSection(&cond_cs);

  if(!have_waiters)
  {
    SetEvent(cond_door);//no reason to bother
    return;
  }

  SetEvent(cond_event[1]);//signal broadcast

  WaitForSingleObject(cond_broadcast, INFINITE);//wait for all waiting threads to wake up
  ResetEvent(cond_event[1]);//stop the broadcast
  SetEvent(cond_door);//open the door for waits/signal/broadcast

  //ZORBA_FATAL(!ret, "Failed to brodcast condition variable. Error code = " << GetLastError());
}

#else

Condition::Condition(Mutex& m) : theMutex(m) {}
Condition::~Condition() {}

#endif // ZORBA_HAVE_PTHREAD_H

}
<commit_msg>fix for the build on apple<commit_after>/*
 * Copyright 2006-2008 The FLWOR Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "zorbautils/fatal.h"
#include "zorbautils/mutex.h"
#include "zorbautils/condition.h"
#include <cassert>
#include <time.h>
#ifdef APPLE
#  include <sys/time.h>
#endif

namespace zorba {

#ifdef ZORBA_HAVE_PTHREAD_H

Condition::Condition(Mutex& m) : theMutex(m)
{
  int ret = pthread_cond_init(&theCondition, NULL);

  ZORBA_FATAL(!ret, "Failed to create condition variable. Error code = " << ret);
}

Condition::~Condition()
{
  int ret = pthread_cond_destroy(&theCondition);

  ZORBA_FATAL(!ret, "Failed to destroy condition variable. Error code = " << ret);
}

void Condition::wait()
{
  int ret = pthread_cond_wait(&theCondition, theMutex.getMutex());

  ZORBA_FATAL(!ret, "Failed to wait on condition variable. Error code = " << ret);
}

void Condition::timedWait(unsigned long aTimeInsMs)
{
  struct timespec lTimespec;
#ifdef APPLE
  struct timeval tv;
  gettimeofday(&tv, NULL);
  lTimespec.tv_sec = tv.tv_sec + aTimeInsMs/1000;
#else
  clock_gettime(CLOCK_REALTIME, &lTimespec);
  lTimespec.tv_sec += aTimeInsMs/1000;
#endif
  pthread_cond_timedwait(&theCondition, theMutex.getMutex(), &lTimespec);
}

void Condition::signal()
{
  int ret = pthread_cond_signal(&theCondition);

  ZORBA_FATAL(!ret, "Failed to signal condition variable. Error code = " << ret);
}

void Condition::broadcast()
{
  int ret = pthread_cond_broadcast(&theCondition);

  ZORBA_FATAL(!ret, "Failed to brodcast condition variable. Error code = " << ret);
}

#elif WIN32

Condition::Condition(Mutex& m) : theMutex(m)
{
//  int ret = pthread_cond_init(&theCondition, NULL);
	cond_event[0] = CreateEvent(NULL, FALSE, FALSE, NULL);//auto-reset, for signal
  assert(cond_event[0] != NULL);
	cond_event[1] = CreateEvent(NULL, TRUE, FALSE, NULL);//manual-reset, for broadcast
  assert(cond_event[1] != NULL);

  cond_door = CreateEvent(NULL, FALSE, TRUE, NULL);//auto-reset, initial ON
  assert(cond_door != NULL);
  cond_broadcast = CreateEvent(NULL, FALSE, FALSE, NULL);//auto-reset, initial OFF
  assert(cond_broadcast != NULL);

  InitializeCriticalSection(&cond_cs);
  waiters = 0;

  ZORBA_FATAL(cond_event[0]!=INVALID_HANDLE_VALUE && cond_event[1]!=INVALID_HANDLE_VALUE && cond_door!=INVALID_HANDLE_VALUE && cond_broadcast!=INVALID_HANDLE_VALUE,
            "Failed to create condition variable. Error code = " << GetLastError());
}

Condition::~Condition()
{
//  int ret = pthread_cond_destroy(&theCondition);
  BOOL ret = CloseHandle(cond_event[0]);
  ret &= CloseHandle(cond_event[1]);
  ret &= CloseHandle(cond_door);
  ret &= CloseHandle(cond_broadcast);

  DeleteCriticalSection(&cond_cs);

  ZORBA_FATAL(ret, "Failed to destroy condition variable. Error code = " << GetLastError());
}

void Condition::wait()
{
  //int ret = pthread_cond_wait(&theCondition, theMutex.getMutex());

  WaitForSingleObject(cond_door, INFINITE);

  EnterCriticalSection(&cond_cs);
  waiters++;
  LeaveCriticalSection(&cond_cs);

  SetEvent(cond_door);//let other waits/signal/broadcast to enter

  theMutex.unlock();
	int result = WaitForMultipleObjects(2,cond_event, FALSE, INFINITE);//wait any of them

  EnterCriticalSection(&cond_cs);
  waiters--;
  if((result == WAIT_OBJECT_0 + 1) && !waiters || (result == WAIT_OBJECT_0))
  {
    SetEvent(cond_broadcast);
  }
  LeaveCriticalSection(&cond_cs);

	theMutex.lock();
}

void Condition::signal()
{
  //int ret = pthread_cond_signal(&theCondition);
  WaitForSingleObject(cond_door, INFINITE);//allow one broadcast/signal at a time

  EnterCriticalSection(&cond_cs);
  bool have_waiters = waiters > 0;
  LeaveCriticalSection(&cond_cs);

  if(!have_waiters)
  {
    SetEvent(cond_door);//no reason to bother
    return;
  }

  SetEvent(cond_event[0]);

  WaitForSingleObject(cond_broadcast, INFINITE);//wait for one waiting thread to wake up

  SetEvent(cond_door);

  //ZORBA_FATAL(!ret, "Failed to signal condition variable. Error code = " << GetLastError());
}

void Condition::broadcast()
{
  //int ret = pthread_cond_broadcast(&theCondition);
  WaitForSingleObject(cond_door, INFINITE);//allow one broadcast/signal at a time

  EnterCriticalSection(&cond_cs);
  bool have_waiters = waiters > 0;
  LeaveCriticalSection(&cond_cs);

  if(!have_waiters)
  {
    SetEvent(cond_door);//no reason to bother
    return;
  }

  SetEvent(cond_event[1]);//signal broadcast

  WaitForSingleObject(cond_broadcast, INFINITE);//wait for all waiting threads to wake up
  ResetEvent(cond_event[1]);//stop the broadcast
  SetEvent(cond_door);//open the door for waits/signal/broadcast

  //ZORBA_FATAL(!ret, "Failed to brodcast condition variable. Error code = " << GetLastError());
}

#else

Condition::Condition(Mutex& m) : theMutex(m) {}
Condition::~Condition() {}

#endif // ZORBA_HAVE_PTHREAD_H

}
<|endoftext|>


<commit_before>#include "clockUtils/argparser/Parser.h"

#include <iostream>

#include "clockUtils/errors.h"
#include "clockUtils/argparser/BasicVariable.h"

namespace clockUtils {
namespace argparser {

	std::vector<BasicVariable *> Parser::variableList = std::vector<BasicVariable *>();

	ClockError Parser::parseArguments(char ** argv, int argc) {
		ClockError result = ClockError::SUCCESS;
		while (argc > 0) {
			if (argv[0][0] == '-' && argv[0][1] != '\0') {
				std::string name(&argv[0][1]);

				bool found = false;

				for (BasicVariable * bv : Parser::variableList) {
					if (name.find(bv->getName()) == 0) {
						found = true;
						if (bv->isBool()) {
							bv->setValue("1");
						} else {
							if (name.length() > bv->getName().length()) {
								size_t startIndex = bv->getName().length();
								if (name.at(startIndex) == '=') {
									startIndex++;
								}
								if (!bv->setValue(name.substr(startIndex, name.length()))) {
									std::cerr << argv[1] << " is not a valid value for variable " << name << std::endl;
									result = ClockError::INVALID_USAGE;
									argc--;
									argv++;
								}
							} else if (argc == 1) {
								std::cerr << name << " requires a value: -" << name << " <value> or -" << name << "<value> or -" << name << "=<value>" << std::endl;
								result = ClockError::INVALID_USAGE;
							} else {
								if (!bv->setValue(argv[1])) {
									std::cerr << argv[1] << " is not a valid value for variable " << name << std::endl;
									result = ClockError::INVALID_USAGE;
									argc--;
									argv++;
								}
							}
						}
						break;
					}
				}

				if (!found) {
					std::cerr << "argument -" << name << " not registered!" << std::endl;
					result = ClockError::INVALID_ARGUMENT;
				}
			} else {
				// TODO: (Daniel) found a single value, but no argument before
			}

			argv++;
			argc--;
		}

		return result;
	}

} /* namespace argparser */
} /* namespace clockUtils */
<commit_msg>CU-16 (argparser) fixed bug in parser if two boolean variables match each other in the beginning (-b and -bar, always -b was detected)<commit_after>#include "clockUtils/argparser/Parser.h"

#include <iostream>

#include "clockUtils/errors.h"
#include "clockUtils/argparser/BasicVariable.h"

namespace clockUtils {
namespace argparser {

	std::vector<BasicVariable *> Parser::variableList = std::vector<BasicVariable *>();

	ClockError Parser::parseArguments(char ** argv, int argc) {
		ClockError result = ClockError::SUCCESS;
		while (argc > 0) {
			if (argv[0][0] == '-' && argv[0][1] != '\0') {
				std::string name(&argv[0][1]);

				bool found = false;

				for (BasicVariable * bv : Parser::variableList) {
					if (name.find(bv->getName()) == 0) {
						found = true;
						if (bv->isBool()) {
							if (bv->getName().length() == name.length()) {
								bv->setValue("1");
							} else {
								found = false;
								continue;
							}
						} else {
							if (name.length() > bv->getName().length()) {
								size_t startIndex = bv->getName().length();
								if (name.at(startIndex) == '=') {
									startIndex++;
								}
								if (!bv->setValue(name.substr(startIndex, name.length()))) {
									std::cerr << argv[1] << " is not a valid value for variable " << name << std::endl;
									result = ClockError::INVALID_USAGE;
									argc--;
									argv++;
								}
							} else if (argc == 1) {
								std::cerr << name << " requires a value: -" << name << " <value> or -" << name << "<value> or -" << name << "=<value>" << std::endl;
								result = ClockError::INVALID_USAGE;
							} else {
								if (!bv->setValue(argv[1])) {
									std::cerr << argv[1] << " is not a valid value for variable " << name << std::endl;
									result = ClockError::INVALID_USAGE;
									argc--;
									argv++;
								}
							}
						}
						break;
					}
				}

				if (!found) {
					std::cerr << "argument -" << name << " not registered!" << std::endl;
					result = ClockError::INVALID_ARGUMENT;
				}
			} else {
				// TODO: (Daniel) found a single value, but no argument before
			}

			argv++;
			argc--;
		}

		return result;
	}

} /* namespace argparser */
} /* namespace clockUtils */
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: hlmarkwn.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: hr $ $Date: 2004-02-03 19:19:28 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _SVX_BKWND_HYPERLINK_HXX
#define _SVX_BKWND_HYPERLINK_HXX

#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif

#ifndef _SV_DIALOG_HXX
#include <vcl/dialog.hxx>
#endif
#ifndef _SV_BUTTON_HXX
#include <vcl/button.hxx>
#endif
#ifndef _SVTREEBOX_HXX
#include <svtools/svtreebx.hxx>
#endif

#ifndef _RTL_USTRING_
#include <rtl/ustring>
#endif

#include "hlmarkwn_def.hxx" //ADD CHINA001
class SvxHyperlinkTabPageBase;

//CHINA001 #define LERR_NOERROR     0
//CHINA001 #define LERR_NOENTRIES       1
//CHINA001 #define LERR_DOCNOTOPEN      2

//########################################################################
//#                                                                      #
//# Tree-Window                                                          #
//#                                                                      #
//########################################################################

class SvxHlinkDlgMarkWnd;

class SvxHlmarkTreeLBox : public SvTreeListBox
{
private:
    SvxHlinkDlgMarkWnd* mpParentWnd;

public:
    SvxHlmarkTreeLBox( Window* pParent, const ResId& rResId );

    virtual void Paint( const Rectangle& rRect );
};

//########################################################################
//#                                                                      #
//# Window-Class                                                         #
//#                                                                      #
//########################################################################

class SvxHlinkDlgMarkWnd : public ModalDialog //FloatingWindow
{
private:
    friend class SvxHlmarkTreeLBox;

    PushButton      maBtApply;
    PushButton      maBtClose;
    //SvTreeListBox maLbTree;
    SvxHlmarkTreeLBox maLbTree;

    BOOL            mbUserMoved;
    BOOL            mbFirst;

    SvxHyperlinkTabPageBase* mpParent;

    String          maStrLastURL;

    USHORT          mnError;

protected:
    BOOL RefreshFromDoc( ::rtl::OUString aURL );

    SvLBoxEntry* FindEntry ( String aStrName );
    void ClearTree();
    int FillTree( ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > xLinks, SvLBoxEntry* pParentEntry =NULL );

    virtual void Move ();

    DECL_LINK (ClickApplyHdl_Impl, void * );
    DECL_LINK (ClickCloseHdl_Impl, void * );

public:
    SvxHlinkDlgMarkWnd (SvxHyperlinkTabPageBase *pParent);
    ~SvxHlinkDlgMarkWnd();

    const BOOL MoveTo ( Point aNewPos );
    void RefreshTree ( String aStrURL );
    void SelectEntry ( String aStrMark );

    const BOOL ConnectToDialog( BOOL bDoit = TRUE );

    USHORT SetError( USHORT nError);
};

#endif  // _SVX_BKWND_HYPERLINK_HXX
<commit_msg>INTEGRATION: CWS ooo19126 (1.4.1044); FILE MERGED 2005/09/05 14:25:16 rt 1.4.1044.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: hlmarkwn.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 23:24:29 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _SVX_BKWND_HYPERLINK_HXX
#define _SVX_BKWND_HYPERLINK_HXX

#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif

#ifndef _SV_DIALOG_HXX
#include <vcl/dialog.hxx>
#endif
#ifndef _SV_BUTTON_HXX
#include <vcl/button.hxx>
#endif
#ifndef _SVTREEBOX_HXX
#include <svtools/svtreebx.hxx>
#endif

#ifndef _RTL_USTRING_
#include <rtl/ustring>
#endif

#include "hlmarkwn_def.hxx" //ADD CHINA001
class SvxHyperlinkTabPageBase;

//CHINA001 #define LERR_NOERROR     0
//CHINA001 #define LERR_NOENTRIES       1
//CHINA001 #define LERR_DOCNOTOPEN      2

//########################################################################
//#                                                                      #
//# Tree-Window                                                          #
//#                                                                      #
//########################################################################

class SvxHlinkDlgMarkWnd;

class SvxHlmarkTreeLBox : public SvTreeListBox
{
private:
    SvxHlinkDlgMarkWnd* mpParentWnd;

public:
    SvxHlmarkTreeLBox( Window* pParent, const ResId& rResId );

    virtual void Paint( const Rectangle& rRect );
};

//########################################################################
//#                                                                      #
//# Window-Class                                                         #
//#                                                                      #
//########################################################################

class SvxHlinkDlgMarkWnd : public ModalDialog //FloatingWindow
{
private:
    friend class SvxHlmarkTreeLBox;

    PushButton      maBtApply;
    PushButton      maBtClose;
    //SvTreeListBox maLbTree;
    SvxHlmarkTreeLBox maLbTree;

    BOOL            mbUserMoved;
    BOOL            mbFirst;

    SvxHyperlinkTabPageBase* mpParent;

    String          maStrLastURL;

    USHORT          mnError;

protected:
    BOOL RefreshFromDoc( ::rtl::OUString aURL );

    SvLBoxEntry* FindEntry ( String aStrName );
    void ClearTree();
    int FillTree( ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > xLinks, SvLBoxEntry* pParentEntry =NULL );

    virtual void Move ();

    DECL_LINK (ClickApplyHdl_Impl, void * );
    DECL_LINK (ClickCloseHdl_Impl, void * );

public:
    SvxHlinkDlgMarkWnd (SvxHyperlinkTabPageBase *pParent);
    ~SvxHlinkDlgMarkWnd();

    const BOOL MoveTo ( Point aNewPos );
    void RefreshTree ( String aStrURL );
    void SelectEntry ( String aStrMark );

    const BOOL ConnectToDialog( BOOL bDoit = TRUE );

    USHORT SetError( USHORT nError);
};

#endif  // _SVX_BKWND_HYPERLINK_HXX
<|endoftext|>