example-service.cpp
#if !defined(EXAMPLE_SERVICE_H)
#define EXAMPLE_SERVICE_H
#include <dbus/qdbusconnection.h>
#include <dbus/qdbusobject.h>
class QStringList;
class ExampleService : public QDBusObjectBase
{
public:
ExampleService(const QDBusConnection& connection);
virtual ~ExampleService();
protected:
virtual bool handleMethodCall(const QDBusMessage& message);
private:
QDBusConnection m_connection;
private:
QStringList sortStrings(const QStringList& list);
};
#endif
#include <qapplication.h>
#include <qstringlist.h>
#include <dbus/qdbusdatalist.h>
#include <dbus/qdbuserror.h>
#include <dbus/qdbusmessage.h>
#include "example-service.h"
ExampleService::ExampleService(const QDBusConnection& connection) : m_connection(connection)
{
m_connection.registerObject("/ListSorter", this);
qDebug("Object registered for path /ListSorter on unique name %s",
m_connection.uniqueName().local8Bit().data());
}
ExampleService::~ExampleService()
{
m_connection.unregisterObject("/ListSorter");
}
bool ExampleService::handleMethodCall(const QDBusMessage& message)
{
qDebug("ExampleService::handleMethodCall: interface='%s', member='%s'",
message.interface().latin1(), message.member().latin1());
if (message.interface() != "org.example.Sort") return false;
if (message.member() == "Strings")
{
if (message.count() != 1 || message[0].type() != QDBusData::List)
{
QDBusError error = QDBusError::stdInvalidArgs(
"Expected one argument of type array of string");
QDBusMessage reply = QDBusMessage::methodError(message, error);
m_connection.send(reply);
return true;
}
bool ok = false;
QDBusDataList list = message[0].toList(&ok);
if (!ok || list.count() < 1 || list.type() != QDBusData::String)
{
QDBusError error = QDBusError::stdInvalidArgs(
"Expected one argument of type array of string");
QDBusMessage reply = QDBusMessage::methodError(message, error);
m_connection.send(reply);
return true;
}
QStringList result = sortStrings(list.toQStringList());
QDBusMessage reply = QDBusMessage::methodReply(message);
list = result;
reply << QDBusData::fromList(list);
m_connection.send(reply);
return true;
}
return false;
}
QStringList ExampleService::sortStrings(const QStringList& list)
{
QStringList result = list;
result.sort();
return result;
}
int main(int argc, char** argv)
{
QApplication app(argc, argv, false);
QDBusConnection connection = QDBusConnection::sessionBus();
if (!connection.isConnected())
qFatal("Cannot connect to session bus");
if (!connection.requestName("org.example.SortService"))
{
qWarning("Requesting name 'org.example.SortService' failed. "
"Will only be addressable through unique name '%s'",
connection.uniqueName().local8Bit().data());
}
else
{
qDebug("Requesting name 'org.example.SortService' successfull");
}
ExampleService service(connection);
return app.exec();
}