<commit_before>/*
 * This file is part of TelepathyQt4
 *
 * Copyright (C) 2008-2010 Collabora Ltd. <http://www.collabora.co.uk/>
 * Copyright (C) 2008-2010 Nokia Corporation
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include <TelepathyQt4/ManagerFile>

#include <QtCore/QDir>
#include <QtCore/QHash>
#include <QtCore/QString>
#include <QtCore/QStringList>
#include <QtDBus/QDBusVariant>

#include <TelepathyQt4/KeyFile>
#include <TelepathyQt4/Constants>

#include "TelepathyQt4/debug-internal.h"

namespace Tp
{

struct TELEPATHY_QT4_NO_EXPORT ManagerFile::Private
{
    Private(const QString &cnName);

    void init();
    bool parse(const QString &fileName);
    bool isValid() const;

    bool hasParameter(const QString &protocol, const QString &paramName) const;
    ParamSpec *getParameter(const QString &protocol, const QString &paramName);
    QStringList protocols() const;
    ParamSpecList parameters(const QString &protocol) const;

    QVariant valueForKey(const QString &param, const QString &signature);

    struct ProtocolInfo
    {
        ProtocolInfo() {}
        ProtocolInfo(const ParamSpecList &params)
            : params(params)
        {
        }

        ParamSpecList params;
        QString vcardField;
        QString englishName;
        QString iconName;
        RequestableChannelClassList rccs;
    };

    QString cmName;
    KeyFile keyFile;
    QHash<QString, ProtocolInfo> protocolsMap;
    bool valid;
};

ManagerFile::Private::Private(const QString &cmName)
    : cmName(cmName),
      valid(false)
{
    init();
}

void ManagerFile::Private::init()
{
    // TODO: should we cache the configDirs anywhere?
    QStringList configDirs;

    QString xdgDataHome = QString::fromLocal8Bit(qgetenv("XDG_DATA_HOME"));
    if (xdgDataHome.isEmpty()) {
        configDirs << QDir::homePath() + QLatin1String("/.local/share/data/telepathy/managers/");
    }
    else {
        configDirs << xdgDataHome + QLatin1String("/telepathy/managers/");
    }

    QString xdgDataDirsEnv = QString::fromLocal8Bit(qgetenv("XDG_DATA_DIRS"));
    if (xdgDataDirsEnv.isEmpty()) {
        configDirs << QLatin1String("/usr/local/share/telepathy/managers/");
        configDirs << QLatin1String("/usr/share/telepathy/managers/");
    }
    else {
        QStringList xdgDataDirs = xdgDataDirsEnv.split(QLatin1Char(':'));
        foreach (const QString xdgDataDir, xdgDataDirs) {
            configDirs << xdgDataDir + QLatin1String("/telepathy/managers/");
        }
    }

    foreach (const QString configDir, configDirs) {
        QString fileName = configDir + cmName + QLatin1String(".manager");
        if (QFile::exists(fileName)) {
            debug() << "parsing manager file" << fileName;
            protocolsMap.clear();
            if (!parse(fileName)) {
                warning() << "error parsing manager file" << fileName;
                continue;
            }
            valid = true;
            return;
        }
    }
}

bool ManagerFile::Private::parse(const QString &fileName)
{
    keyFile.setFileName(fileName);
    if (keyFile.status() != KeyFile::NoError) {
        return false;
    }

    /* read supported protocols and parameters */
    QString protocol;
    QStringList groups = keyFile.allGroups();
    foreach (const QString group, groups) {
        if (group.startsWith(QLatin1String("Protocol "))) {
            protocol = group.right(group.length() - 9);
            keyFile.setGroup(group);

            ParamSpecList paramSpecList;
            QString param;
            QStringList params = keyFile.keys();
            foreach (param, params) {
                ParamSpec spec;
                spec.flags = 0;
                if (param.startsWith(QLatin1String("param-"))) {
                    spec.name = param.right(param.length() - 6);

                    if (spec.name.endsWith(QLatin1String("password"))) {
                        spec.flags |= ConnMgrParamFlagSecret;
                    }

                    QStringList values = keyFile.value(param).split(QLatin1String(" "));

                    spec.signature = values[0];
                    if (values.contains(QLatin1String("secret"))) {
                        spec.flags |= ConnMgrParamFlagSecret;
                    }
                    if (values.contains(QLatin1String("dbus-property"))) {
                        spec.flags |= ConnMgrParamFlagDBusProperty;
                    }
                    if (values.contains(QLatin1String("required"))) {
                        spec.flags |= ConnMgrParamFlagRequired;
                    }
                    if (values.contains(QLatin1String("register"))) {
                        spec.flags |= ConnMgrParamFlagRegister;
                    }

                    paramSpecList.append(spec);
                }
            }

            protocolsMap.insert(protocol, ProtocolInfo(paramSpecList));

            /* now that we have all param-* created, let's find their default values */
            foreach (param, params) {
                if (param.startsWith(QLatin1String("default-"))) {
                    QString paramName = param.right(param.length() - 8);

                    if (!hasParameter(protocol, paramName)) {
                        warning() << "param" << paramName
                                  << "has default value set, but not a definition";
                        continue;
                    }

                    ParamSpec *spec = getParameter(protocol, paramName);

                    spec->flags |= ConnMgrParamFlagHasDefault;

                    /* map based on the param dbus signature, otherwise use
                     * QString */
                    QVariant value = valueForKey(param, spec->signature);
                    if (value.type() == QVariant::Invalid) {
                        warning() << "param" << paramName
                                  << "has invalid signature";
                        protocolsMap.clear();
                        return false;
                    }
                    spec->defaultValue = QDBusVariant(value);
                }
            }

            ProtocolInfo &info = protocolsMap[protocol];
            info.vcardField = keyFile.value(QLatin1String("VCardField"));
            info.englishName = keyFile.value(QLatin1String("EnglishName"));
            info.iconName = keyFile.value(QLatin1String("Icon"));

            QStringList rccGroups = keyFile.valueAsStringList(
                    QLatin1String("RequestableChannelClasses"));
            RequestableChannelClass rcc;
            foreach (const QString &rccGroup, rccGroups) {
                keyFile.setGroup(rccGroup);

                foreach (const QString &key, keyFile.keys()) {
                    int spaceIdx = key.indexOf(QLatin1String(" "));
                    if (spaceIdx == -1) {
                        continue;
                    }

                    QString propertyName = key.mid(0, spaceIdx);
                    QString signature = key.mid(spaceIdx + 1);
                    QString param = keyFile.value(key);
                    QVariant value = valueForKey(key, signature);
                    rcc.fixedProperties.insert(propertyName, value);
                }

                rcc.allowedProperties = keyFile.valueAsStringList(
                        QLatin1String("allowed"));

                info.rccs.append(rcc);
            }
        }
    }

    return true;
}

bool ManagerFile::Private::isValid() const
{
    return ((keyFile.status() == KeyFile::NoError) && (valid));
}

bool ManagerFile::Private::hasParameter(const QString &protocol,
                                        const QString &paramName) const
{
    ParamSpecList paramSpecList = protocolsMap[protocol].params;
    foreach (const ParamSpec &paramSpec, paramSpecList) {
        if (paramSpec.name == paramName) {
            return true;
        }
    }
    return false;
}

ParamSpec *ManagerFile::Private::getParameter(const QString &protocol,
                                              const QString &paramName)
{
    ParamSpecList &paramSpecList = protocolsMap[protocol].params;
    for (int i = 0; i < paramSpecList.size(); ++i) {
        ParamSpec &paramSpec = paramSpecList[i];
        if (paramSpec.name == paramName) {
            return &paramSpec;
        }
    }
    return NULL;
}

QStringList ManagerFile::Private::protocols() const
{
    return protocolsMap.keys();
}

ParamSpecList ManagerFile::Private::parameters(const QString &protocol) const
{
    return protocolsMap.value(protocol).params;
}

QVariant ManagerFile::Private::valueForKey(const QString &param,
                                           const QString &signature)
{
    QVariant::Type type = ManagerFile::variantTypeFromDBusSignature(signature);

    if (type == QVariant::Invalid) {
        return QVariant(type);
    }

    switch (type) {
        case QVariant::Bool:
            {
                QString value = keyFile.value(param);
                if (value.toLower() == QLatin1String("true") ||
                    value == QLatin1String("1")) {
                    return QVariant(true);
                }
                else {
                    return QVariant(false);
                }
                break;
            }
        case QVariant::Int:
            {
                QString value = keyFile.value(param);
                return QVariant(value.toInt());
            }
        case QVariant::UInt:
            {
                QString value = keyFile.value(param);
                return QVariant(value.toUInt());
            }
        case QVariant::LongLong:
            {
                QString value = keyFile.value(param);
                return QVariant(value.toLongLong());
            }
        case QVariant::ULongLong:
            {
                QString value = keyFile.value(param);
                return QVariant(value.toULongLong());
            }
        case QVariant::Double:
            {
                QString value = keyFile.value(param);
                return QVariant(value.toDouble());
            }
        case QVariant::StringList:
            {
                QStringList value = keyFile.valueAsStringList(param);
                return QVariant(value);
            }
        default:
            break;
    }
    QString value = keyFile.value(param);
    return QVariant(value);
}

/**
 * \class ManagerFile
 * \headerfile TelepathyQt4/manager-file.h <TelepathyQt4/ManagerFile>
 *
 * \brief The ManagerFile class provides an easy way to read telepathy manager
 * files according to http://telepathy.freedesktop.org/spec.html.
 */

/**
 * Create a ManagerFile object used to read .manager compliant files.
 *
 * \param cmName Name of the connection manager to read the file for.
 */
ManagerFile::ManagerFile(const QString &cmName)
    : mPriv(new Private(cmName))
{
}

/**
 * Class destructor.
 */
ManagerFile::~ManagerFile()
{
    delete mPriv;
}

/**
 * Check whether or not a ManagerFile object is valid. If the file for the
 * specified connection manager cannot be found it will be considered invalid.
 *
 * \return true if valid, false otherwise.
 */
bool ManagerFile::isValid() const
{
    return mPriv->isValid();
}

/**
 * Return a list of all protocols defined in the manager file.
 *
 * \return List of all protocols defined in the file.
 */
QStringList ManagerFile::protocols() const
{
    return mPriv->protocols();
}

/**
 * Return a list of parameters for the given \a protocol.
 *
 * \param protocol Name of the protocol to look for.
 * \return List of ParamSpec of a specific protocol defined in the file, or an
 *         empty list if the protocol is not defined.
 */
ParamSpecList ManagerFile::parameters(const QString &protocol) const
{
    return mPriv->parameters(protocol);
}

/**
 * Return the name of the most common vCard field used for the given \a protocol's
 * contact identifiers, normalized to lower case.
 *
 * \param protocol Name of the protocol to look for.
 * \return The most common vCard field used for the given protocol's contact
 *         identifiers, or an empty string if there is no such field or the
 *         protocol is not defined.
 */
QString ManagerFile::vcardField(const QString &protocol) const
{
    return mPriv->protocolsMap[protocol].vcardField;
}

/**
 * Return the name of the given \a protocol in a form suitable for display to
 * users, such as "AIM" or "Yahoo!".
 *
 * \param protocol Name of the protocol to look for.
 * \return The name of the given \a protocol in a form suitable for display to
 *         users or an empty string if none is available or the protocol is not
 *         defined.
 */
QString ManagerFile::englishName(const QString &protocol) const
{
    return mPriv->protocolsMap[protocol].englishName;
}

/**
 * Return the name of an icon for the given \a protocol in the system's icon
 * theme, such as "im-msn".
 *
 * \param protocol Name of the protocol to look for.
 * \return The name of an icon for the given \a protocol in the system's icon
 *         theme or an empty string if none is available or the protocol is not
 *         defined.
 */
QString ManagerFile::iconName(const QString &protocol) const
{
    return mPriv->protocolsMap[protocol].iconName;
}

/**
 * Return a list of channel classes which might be requestable from a connection
 * to the given \a protocol.
 *
 * \param protocol Name of the protocol to look for.
 * \return A list of channel classes which might be requestable from a
 *         connection to the given \a protocol or a default constructed
 *         RequestableChannelClassList instance if the protocol is not defined.
 */
RequestableChannelClassList ManagerFile::requestableChannelClasses(
        const QString &protocol) const
{
    return mPriv->protocolsMap[protocol].rccs;
}

QVariant::Type ManagerFile::variantTypeFromDBusSignature(const QString &signature)
{
    QVariant::Type type;
    if (signature == QLatin1String("b"))
        type = QVariant::Bool;
    else if (signature == QLatin1String("n") || signature == QLatin1String("i"))
        type = QVariant::Int;
    else if (signature == QLatin1String("q") || signature == QLatin1String("u"))
        type = QVariant::UInt;
    else if (signature == QLatin1String("x"))
        type = QVariant::LongLong;
    else if (signature == QLatin1String("t"))
        type = QVariant::ULongLong;
    else if (signature == QLatin1String("d"))
        type = QVariant::Double;
    else if (signature == QLatin1String("as"))
        type = QVariant::StringList;
    else if (signature == QLatin1String("s") || signature == QLatin1String("o"))
        type = QVariant::String;
    else
        type = QVariant::Invalid;

    return type;
}

} // Tp
<commit_msg>ManagerFile: Always return non-empty englishName and iconName strings.<commit_after>/*
 * This file is part of TelepathyQt4
 *
 * Copyright (C) 2008-2010 Collabora Ltd. <http://www.collabora.co.uk/>
 * Copyright (C) 2008-2010 Nokia Corporation
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include <TelepathyQt4/ManagerFile>

#include <QtCore/QDir>
#include <QtCore/QHash>
#include <QtCore/QString>
#include <QtCore/QStringList>
#include <QtDBus/QDBusVariant>

#include <TelepathyQt4/KeyFile>
#include <TelepathyQt4/Constants>

#include "TelepathyQt4/debug-internal.h"

namespace Tp
{

struct TELEPATHY_QT4_NO_EXPORT ManagerFile::Private
{
    Private(const QString &cnName);

    void init();
    bool parse(const QString &fileName);
    bool isValid() const;

    bool hasParameter(const QString &protocol, const QString &paramName) const;
    ParamSpec *getParameter(const QString &protocol, const QString &paramName);
    QStringList protocols() const;
    ParamSpecList parameters(const QString &protocol) const;

    QVariant valueForKey(const QString &param, const QString &signature);

    struct ProtocolInfo
    {
        ProtocolInfo() {}
        ProtocolInfo(const ParamSpecList &params)
            : params(params)
        {
        }

        ParamSpecList params;
        QString vcardField;
        QString englishName;
        QString iconName;
        RequestableChannelClassList rccs;
    };

    QString cmName;
    KeyFile keyFile;
    QHash<QString, ProtocolInfo> protocolsMap;
    bool valid;
};

ManagerFile::Private::Private(const QString &cmName)
    : cmName(cmName),
      valid(false)
{
    init();
}

void ManagerFile::Private::init()
{
    // TODO: should we cache the configDirs anywhere?
    QStringList configDirs;

    QString xdgDataHome = QString::fromLocal8Bit(qgetenv("XDG_DATA_HOME"));
    if (xdgDataHome.isEmpty()) {
        configDirs << QDir::homePath() + QLatin1String("/.local/share/data/telepathy/managers/");
    }
    else {
        configDirs << xdgDataHome + QLatin1String("/telepathy/managers/");
    }

    QString xdgDataDirsEnv = QString::fromLocal8Bit(qgetenv("XDG_DATA_DIRS"));
    if (xdgDataDirsEnv.isEmpty()) {
        configDirs << QLatin1String("/usr/local/share/telepathy/managers/");
        configDirs << QLatin1String("/usr/share/telepathy/managers/");
    }
    else {
        QStringList xdgDataDirs = xdgDataDirsEnv.split(QLatin1Char(':'));
        foreach (const QString xdgDataDir, xdgDataDirs) {
            configDirs << xdgDataDir + QLatin1String("/telepathy/managers/");
        }
    }

    foreach (const QString configDir, configDirs) {
        QString fileName = configDir + cmName + QLatin1String(".manager");
        if (QFile::exists(fileName)) {
            debug() << "parsing manager file" << fileName;
            protocolsMap.clear();
            if (!parse(fileName)) {
                warning() << "error parsing manager file" << fileName;
                continue;
            }
            valid = true;
            return;
        }
    }
}

bool ManagerFile::Private::parse(const QString &fileName)
{
    keyFile.setFileName(fileName);
    if (keyFile.status() != KeyFile::NoError) {
        return false;
    }

    /* read supported protocols and parameters */
    QString protocol;
    QStringList groups = keyFile.allGroups();
    foreach (const QString group, groups) {
        if (group.startsWith(QLatin1String("Protocol "))) {
            protocol = group.right(group.length() - 9);
            keyFile.setGroup(group);

            ParamSpecList paramSpecList;
            QString param;
            QStringList params = keyFile.keys();
            foreach (param, params) {
                ParamSpec spec;
                spec.flags = 0;
                if (param.startsWith(QLatin1String("param-"))) {
                    spec.name = param.right(param.length() - 6);

                    if (spec.name.endsWith(QLatin1String("password"))) {
                        spec.flags |= ConnMgrParamFlagSecret;
                    }

                    QStringList values = keyFile.value(param).split(QLatin1String(" "));

                    spec.signature = values[0];
                    if (values.contains(QLatin1String("secret"))) {
                        spec.flags |= ConnMgrParamFlagSecret;
                    }
                    if (values.contains(QLatin1String("dbus-property"))) {
                        spec.flags |= ConnMgrParamFlagDBusProperty;
                    }
                    if (values.contains(QLatin1String("required"))) {
                        spec.flags |= ConnMgrParamFlagRequired;
                    }
                    if (values.contains(QLatin1String("register"))) {
                        spec.flags |= ConnMgrParamFlagRegister;
                    }

                    paramSpecList.append(spec);
                }
            }

            protocolsMap.insert(protocol, ProtocolInfo(paramSpecList));

            /* now that we have all param-* created, let's find their default values */
            foreach (param, params) {
                if (param.startsWith(QLatin1String("default-"))) {
                    QString paramName = param.right(param.length() - 8);

                    if (!hasParameter(protocol, paramName)) {
                        warning() << "param" << paramName
                                  << "has default value set, but not a definition";
                        continue;
                    }

                    ParamSpec *spec = getParameter(protocol, paramName);

                    spec->flags |= ConnMgrParamFlagHasDefault;

                    /* map based on the param dbus signature, otherwise use
                     * QString */
                    QVariant value = valueForKey(param, spec->signature);
                    if (value.type() == QVariant::Invalid) {
                        warning() << "param" << paramName
                                  << "has invalid signature";
                        protocolsMap.clear();
                        return false;
                    }
                    spec->defaultValue = QDBusVariant(value);
                }
            }

            ProtocolInfo &info = protocolsMap[protocol];
            info.vcardField = keyFile.value(QLatin1String("VCardField"));
            info.englishName = keyFile.value(QLatin1String("EnglishName"));
            if (info.englishName.isEmpty()) {
                info.englishName = QString("%1").arg(protocol);
            }
            info.iconName = keyFile.value(QLatin1String("Icon"));
            if (info.iconName.isEmpty()) {
                info.iconName = QString("im-%1").arg(protocol);
            }

            QStringList rccGroups = keyFile.valueAsStringList(
                    QLatin1String("RequestableChannelClasses"));
            RequestableChannelClass rcc;
            foreach (const QString &rccGroup, rccGroups) {
                keyFile.setGroup(rccGroup);

                foreach (const QString &key, keyFile.keys()) {
                    int spaceIdx = key.indexOf(QLatin1String(" "));
                    if (spaceIdx == -1) {
                        continue;
                    }

                    QString propertyName = key.mid(0, spaceIdx);
                    QString signature = key.mid(spaceIdx + 1);
                    QString param = keyFile.value(key);
                    QVariant value = valueForKey(key, signature);
                    rcc.fixedProperties.insert(propertyName, value);
                }

                rcc.allowedProperties = keyFile.valueAsStringList(
                        QLatin1String("allowed"));

                info.rccs.append(rcc);
            }
        }
    }

    return true;
}

bool ManagerFile::Private::isValid() const
{
    return ((keyFile.status() == KeyFile::NoError) && (valid));
}

bool ManagerFile::Private::hasParameter(const QString &protocol,
                                        const QString &paramName) const
{
    ParamSpecList paramSpecList = protocolsMap[protocol].params;
    foreach (const ParamSpec &paramSpec, paramSpecList) {
        if (paramSpec.name == paramName) {
            return true;
        }
    }
    return false;
}

ParamSpec *ManagerFile::Private::getParameter(const QString &protocol,
                                              const QString &paramName)
{
    ParamSpecList &paramSpecList = protocolsMap[protocol].params;
    for (int i = 0; i < paramSpecList.size(); ++i) {
        ParamSpec &paramSpec = paramSpecList[i];
        if (paramSpec.name == paramName) {
            return &paramSpec;
        }
    }
    return NULL;
}

QStringList ManagerFile::Private::protocols() const
{
    return protocolsMap.keys();
}

ParamSpecList ManagerFile::Private::parameters(const QString &protocol) const
{
    return protocolsMap.value(protocol).params;
}

QVariant ManagerFile::Private::valueForKey(const QString &param,
                                           const QString &signature)
{
    QVariant::Type type = ManagerFile::variantTypeFromDBusSignature(signature);

    if (type == QVariant::Invalid) {
        return QVariant(type);
    }

    switch (type) {
        case QVariant::Bool:
            {
                QString value = keyFile.value(param);
                if (value.toLower() == QLatin1String("true") ||
                    value == QLatin1String("1")) {
                    return QVariant(true);
                }
                else {
                    return QVariant(false);
                }
                break;
            }
        case QVariant::Int:
            {
                QString value = keyFile.value(param);
                return QVariant(value.toInt());
            }
        case QVariant::UInt:
            {
                QString value = keyFile.value(param);
                return QVariant(value.toUInt());
            }
        case QVariant::LongLong:
            {
                QString value = keyFile.value(param);
                return QVariant(value.toLongLong());
            }
        case QVariant::ULongLong:
            {
                QString value = keyFile.value(param);
                return QVariant(value.toULongLong());
            }
        case QVariant::Double:
            {
                QString value = keyFile.value(param);
                return QVariant(value.toDouble());
            }
        case QVariant::StringList:
            {
                QStringList value = keyFile.valueAsStringList(param);
                return QVariant(value);
            }
        default:
            break;
    }
    QString value = keyFile.value(param);
    return QVariant(value);
}

/**
 * \class ManagerFile
 * \headerfile TelepathyQt4/manager-file.h <TelepathyQt4/ManagerFile>
 *
 * \brief The ManagerFile class provides an easy way to read telepathy manager
 * files according to http://telepathy.freedesktop.org/spec.html.
 */

/**
 * Create a ManagerFile object used to read .manager compliant files.
 *
 * \param cmName Name of the connection manager to read the file for.
 */
ManagerFile::ManagerFile(const QString &cmName)
    : mPriv(new Private(cmName))
{
}

/**
 * Class destructor.
 */
ManagerFile::~ManagerFile()
{
    delete mPriv;
}

/**
 * Check whether or not a ManagerFile object is valid. If the file for the
 * specified connection manager cannot be found it will be considered invalid.
 *
 * \return true if valid, false otherwise.
 */
bool ManagerFile::isValid() const
{
    return mPriv->isValid();
}

/**
 * Return a list of all protocols defined in the manager file.
 *
 * \return List of all protocols defined in the file.
 */
QStringList ManagerFile::protocols() const
{
    return mPriv->protocols();
}

/**
 * Return a list of parameters for the given \a protocol.
 *
 * \param protocol Name of the protocol to look for.
 * \return List of ParamSpec of a specific protocol defined in the file, or an
 *         empty list if the protocol is not defined.
 */
ParamSpecList ManagerFile::parameters(const QString &protocol) const
{
    return mPriv->parameters(protocol);
}

/**
 * Return the name of the most common vCard field used for the given \a protocol's
 * contact identifiers, normalized to lower case.
 *
 * \param protocol Name of the protocol to look for.
 * \return The most common vCard field used for the given protocol's contact
 *         identifiers, or an empty string if there is no such field or the
 *         protocol is not defined.
 */
QString ManagerFile::vcardField(const QString &protocol) const
{
    return mPriv->protocolsMap[protocol].vcardField;
}

/**
 * Return the name of the given \a protocol in a form suitable for display to
 * users, such as "AIM" or "Yahoo!".
 *
 * \param protocol Name of the protocol to look for.
 * \return The name of the given \a protocol in a form suitable for display to
 *         users or the \a protocol if the protocol is defined and englishName
 *         is absent.
 */
QString ManagerFile::englishName(const QString &protocol) const
{
    return mPriv->protocolsMap[protocol].englishName;
}

/**
 * Return the name of an icon for the given \a protocol in the system's icon
 * theme, such as "im-msn".
 *
 * \param protocol Name of the protocol to look for.
 * \return The name of an icon for the given \a protocol in the system's icon
 *         theme or the string im-\a protocol if the protocol is defined and
 *         Icon is absent.
 */
QString ManagerFile::iconName(const QString &protocol) const
{
    return mPriv->protocolsMap[protocol].iconName;
}

/**
 * Return a list of channel classes which might be requestable from a connection
 * to the given \a protocol.
 *
 * \param protocol Name of the protocol to look for.
 * \return A list of channel classes which might be requestable from a
 *         connection to the given \a protocol or a default constructed
 *         RequestableChannelClassList instance if the protocol is not defined.
 */
RequestableChannelClassList ManagerFile::requestableChannelClasses(
        const QString &protocol) const
{
    return mPriv->protocolsMap[protocol].rccs;
}

QVariant::Type ManagerFile::variantTypeFromDBusSignature(const QString &signature)
{
    QVariant::Type type;
    if (signature == QLatin1String("b"))
        type = QVariant::Bool;
    else if (signature == QLatin1String("n") || signature == QLatin1String("i"))
        type = QVariant::Int;
    else if (signature == QLatin1String("q") || signature == QLatin1String("u"))
        type = QVariant::UInt;
    else if (signature == QLatin1String("x"))
        type = QVariant::LongLong;
    else if (signature == QLatin1String("t"))
        type = QVariant::ULongLong;
    else if (signature == QLatin1String("d"))
        type = QVariant::Double;
    else if (signature == QLatin1String("as"))
        type = QVariant::StringList;
    else if (signature == QLatin1String("s") || signature == QLatin1String("o"))
        type = QVariant::String;
    else
        type = QVariant::Invalid;

    return type;
}

} // Tp
<|endoftext|>


<commit_before>#include "callback_engine.hpp"
#include "callback_object.hpp"
#include "code/ylikuutio/common/any_value.hpp"
#include "code/ylikuutio/hierarchy/hierarchy_templates.hpp"

// Include standard headers
#include <iostream> // std::cout, std::cin, std::cerr
#include <queue>    // std::queue
#include <stdint.h> // uint32_t etc.
#include <string>   // std::string
#include <vector>   // std::vector

namespace callback_system
{
    CallbackEngine::CallbackEngine()
    {
        // constructor.
        this->number_of_callback_objects = 0;
    }

    CallbackEngine::~CallbackEngine()
    {
        // destructor.
        std::cout << "This callback engine will be destroyed.\n";

        // destroy all callback objects of this callback engine.
        std::cout << "All callback objects of this callback engine will be destroyed.\n";
        hierarchy::delete_children<callback_system::CallbackObject*>(this->callback_object_pointer_vector, &this->number_of_callback_objects);
    }

    void CallbackEngine::set_callback_object_pointer(const uint32_t childID, callback_system::CallbackObject* const child_pointer)
    {
        hierarchy::set_child_pointer(childID, child_pointer, this->callback_object_pointer_vector, this->free_callback_objectID_queue, &this->number_of_callback_objects);
    }

    datatypes::AnyValue* CallbackEngine::execute()
    {
        datatypes::AnyValue* any_value = new datatypes::AnyValue();

        // execute all callbacks.
        for (uint32_t child_i = 0; child_i < this->callback_object_pointer_vector.size(); child_i++)
        {
            callback_system::CallbackObject* callback_object_pointer = static_cast<callback_system::CallbackObject*>(this->callback_object_pointer_vector[child_i]);
            any_value = callback_object_pointer->execute();

            this->return_values.push_back(any_value);
        }

        this->return_values.clear();
        return any_value;
    }

    uint32_t CallbackEngine::get_n_of_return_values()
    {
        return this->return_values.size();
    }

    datatypes::AnyValue* CallbackEngine::get_nth_return_value(uint32_t n)
    {
        // note: indexing of `n` begins from 0.

        uint32_t n_of_return_values = this->get_n_of_return_values();

        if (n_of_return_values <= n)
        {
            return nullptr;
        }

        return this->return_values.at(n_of_return_values - 1);
    }

    datatypes::AnyValue* CallbackEngine::get_previous_return_value()
    {
        uint32_t n_of_return_values = this->get_n_of_return_values();

        if (n_of_return_values == 0)
        {
            return nullptr;
        }

        return this->return_values.at(this->return_values.size() - 1);
    }
}
<commit_msg>`CallbackEngine::execute()` without `CallbackObject`s returns `nullptr`.<commit_after>#include "callback_engine.hpp"
#include "callback_object.hpp"
#include "code/ylikuutio/common/any_value.hpp"
#include "code/ylikuutio/hierarchy/hierarchy_templates.hpp"

// Include standard headers
#include <iostream> // std::cout, std::cin, std::cerr
#include <queue>    // std::queue
#include <stdint.h> // uint32_t etc.
#include <string>   // std::string
#include <vector>   // std::vector

namespace callback_system
{
    CallbackEngine::CallbackEngine()
    {
        // constructor.
        this->number_of_callback_objects = 0;
    }

    CallbackEngine::~CallbackEngine()
    {
        // destructor.
        std::cout << "This callback engine will be destroyed.\n";

        // destroy all callback objects of this callback engine.
        std::cout << "All callback objects of this callback engine will be destroyed.\n";
        hierarchy::delete_children<callback_system::CallbackObject*>(this->callback_object_pointer_vector, &this->number_of_callback_objects);
    }

    void CallbackEngine::set_callback_object_pointer(const uint32_t childID, callback_system::CallbackObject* const child_pointer)
    {
        hierarchy::set_child_pointer(childID, child_pointer, this->callback_object_pointer_vector, this->free_callback_objectID_queue, &this->number_of_callback_objects);
    }

    datatypes::AnyValue* CallbackEngine::execute()
    {
        datatypes::AnyValue* any_value = nullptr;

        // execute all callbacks.
        for (uint32_t child_i = 0; child_i < this->callback_object_pointer_vector.size(); child_i++)
        {
            callback_system::CallbackObject* callback_object_pointer = static_cast<callback_system::CallbackObject*>(this->callback_object_pointer_vector[child_i]);
            any_value = callback_object_pointer->execute();

            this->return_values.push_back(any_value);
        }

        this->return_values.clear();
        return any_value;
    }

    uint32_t CallbackEngine::get_n_of_return_values()
    {
        return this->return_values.size();
    }

    datatypes::AnyValue* CallbackEngine::get_nth_return_value(uint32_t n)
    {
        // note: indexing of `n` begins from 0.

        uint32_t n_of_return_values = this->get_n_of_return_values();

        if (n_of_return_values <= n)
        {
            return nullptr;
        }

        return this->return_values.at(n_of_return_values - 1);
    }

    datatypes::AnyValue* CallbackEngine::get_previous_return_value()
    {
        uint32_t n_of_return_values = this->get_n_of_return_values();

        if (n_of_return_values == 0)
        {
            return nullptr;
        }

        return this->return_values.at(this->return_values.size() - 1);
    }
}
<|endoftext|>


<commit_before>/*************************************************************************
*    UrBackup - Client/Server backup system
*    Copyright (C) 2011  Martin Raiber
*
*    This program is free software: you can redistribute it and/or modify
*    it under the terms of the GNU General Public License as published by
*    the Free Software Foundation, either version 3 of the License, or
*    (at your option) any later version.
*
*    This program 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 General Public License for more details.
*
*    You should have received a copy of the GNU General Public License
*    along with this program.  If not, see <http://www.gnu.org/licenses/>.
**************************************************************************/

#include "os_functions.h"
#include "../stringtools.h"
#include "../Interface/Server.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/statvfs.h>
#include <dirent.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <algorithm>
#include <memory.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <netdb.h>

void getMousePos(int &x, int &y)
{
	x=0;
	y=0;
}

std::vector<SFile> getFiles(const std::wstring &path)
{
	std::string upath=Server->ConvertToUTF8(path);
	std::vector<SFile> tmp;
	DIR *dp;
    struct dirent *dirp;
    if((dp  = opendir(upath.c_str())) == NULL)
	{
		Server->Log("No permission to access \""+upath+"\"", LL_ERROR);
        return tmp;
    }

	upath+=os_file_sepn();

    while ((dirp = readdir(dp)) != NULL)
	{
		SFile f;
		f.name=widen(dirp->d_name);
		if(f.name==L"." || f.name==L".." )
			continue;

		f.isdir=(dirp->d_type==DT_DIR);
		if(!f.isdir || dirp->d_type==DT_UNKNOWN)
		{
			struct stat64 f_info;
			int rc=stat64((upath+dirp->d_name).c_str(), &f_info);
			if(rc==0)
			{
				if(dirp->d_type==DT_UNKNOWN)
				{
					f.isdir=S_ISDIR(f_info.st_mode);
					if(!f.isdir)
					{
						f.last_modified=f_info.st_mtime;
						f.size=f_info.st_size;
					}
				}
				else
				{
					f.last_modified=f_info.st_mtime;
					f.size=f_info.st_size;
				}
			}
			else
			{
				Server->Log("No permission to stat \""+upath+dirp->d_name+"\"", LL_ERROR);
				f.last_modified=0;
				f.size=0;
			}
		}
		else
		{
			f.last_modified=0;
			f.size=0;
		}
		tmp.push_back(f);
    }
    closedir(dp);

	std::sort(tmp.begin(), tmp.end());

    return tmp;
}

void removeFile(const std::wstring &path)
{
	unlink(wnarrow(path).c_str());
}

void moveFile(const std::wstring &src, const std::wstring &dst)
{
	rename(wnarrow(src).c_str(), wnarrow(dst).c_str() );
}

bool isDirectory(const std::wstring &path)
{
        struct stat64 f_info;
		int rc=stat64(Server->ConvertToUTF8(path).c_str(), &f_info);
		if(rc!=0)
		{
			Server->Log(L"No permission to access \""+path+L"\"", LL_ERROR);
			return false;
		}

        if ( S_ISDIR(f_info.st_mode) )
        {
                return true;
        }
        else
        {
                return false;
        }
}

int64 os_atoi64(const std::string &str)
{
	return strtoll(str.c_str(), NULL, 10);
}

bool os_create_dir(const std::wstring &dir)
{
	int rc=mkdir(Server->ConvertToUTF8(dir).c_str(), S_IRWXU | S_IRWXG );
	return rc==0;
}

bool os_create_hardlink(const std::wstring &linkname, const std::wstring &fname)
{
	int rc=link(Server->ConvertToUTF8(fname).c_str(), Server->ConvertToUTF8(linkname).c_str());
	return rc==0;
}

int64 os_free_space(const std::wstring &path)
{
	std::wstring cp=path;
	if(path.size()==0)
		return -1;
	if(cp[cp.size()-1]=='/')
		cp.erase(cp.size()-1, 1);
	if(cp[cp.size()-1]!='/')
		cp+='/';

	struct statvfs64 buf;
	int rc=statvfs64(Server->ConvertToUTF8(path).c_str(), &buf);
	if(rc==0)
		return buf.f_bsize*buf.f_bavail;
	else
		return -1;
}

bool os_directory_exists(const std::wstring &path)
{
	//std::string upath=Server->ConvertToUTF8(path);
	//DIR *dp=opendir(upath.c_str());
	//closedir(dp);
	//return dp!=NULL;
	return isDirectory(path);
}

bool os_remove_nonempty_dir(const std::wstring &path)
{
	std::string upath=Server->ConvertToUTF8(path);
	std::vector<SFile> tmp;
	DIR *dp;
    struct dirent *dirp;
    if((dp  = opendir(upath.c_str())) == NULL)
	{
		Server->Log("No permission to access \""+upath+"\"", LL_ERROR);
        return false;
    }

	bool ok=true;
	std::vector<std::wstring> subdirs;
	while ((dirp = readdir(dp)) != NULL)
	{
		if( (std::string)dirp->d_name!="." && (std::string)dirp->d_name!=".." )
		{
			if(dirp->d_type==DT_UNKNOWN)
			{
				struct stat f_info;
				int rc=stat((upath+"/"+(std::string)dirp->d_name).c_str(), &f_info);
				if(rc==0)
				{
					if(S_ISDIR(f_info.st_mode) )
					{
						subdirs.push_back(Server->ConvertToUnicode(dirp->d_name));
					}
					else
					{
						if(unlink((upath+"/"+(std::string)dirp->d_name).c_str())!=0)
						{
							Server->Log("Error deleting file \""+upath+"/"+(std::string)dirp->d_name+"\"", LL_ERROR);
						}
					}
				}
				else
				{
					Server->Log("No permission to stat \""+upath+dirp->d_name+"\"", LL_ERROR);
				}
			}
			else if(dirp->d_type==DT_DIR )
			{
				subdirs.push_back(Server->ConvertToUnicode(dirp->d_name));
			}
			else
			{
				if(unlink((upath+"/"+(std::string)dirp->d_name).c_str())!=0)
				{
					Server->Log("Error deleting file \""+upath+"/"+(std::string)dirp->d_name+"\"", LL_ERROR);
				}
			}
		}
    }
    closedir(dp);
    for(size_t i=0;i<subdirs.size();++i)
    {
		bool b=os_remove_nonempty_dir(path+L"/"+subdirs[i]);
		if(!b)
		    ok=false;
    }
    if(rmdir(upath.c_str())!=0)
	{
		Server->Log("Error deleting directory \""+upath+"\"", LL_ERROR);
	}
	return ok;
}

std::wstring os_file_sep(void)
{
	return L"/";
}

std::string os_file_sepn(void)
{
	return "/";
}

bool os_link_symbolic(const std::wstring &target, const std::wstring &lname)
{
	return symlink(Server->ConvertToUTF8(target).c_str(), Server->ConvertToUTF8(lname).c_str())==0;
}

bool os_lookuphostname(std::string pServer, unsigned int *dest)
{
	const char* host=pServer.c_str();
    unsigned int addr = inet_addr(host);
    if (addr != INADDR_NONE)
	{
        *dest = addr;
    }
	else
	{
		hostent* hp = gethostbyname(host);
        if (hp != 0)
		{
			in_addr tmp;
			memcpy(&tmp, hp->h_addr,  hp->h_length );
			*dest=tmp.s_addr;
		}
		else
		{
			return false;
		}
	}
	return true;
}<commit_msg>Added Logging to directory removal<commit_after>/*************************************************************************
*    UrBackup - Client/Server backup system
*    Copyright (C) 2011  Martin Raiber
*
*    This program is free software: you can redistribute it and/or modify
*    it under the terms of the GNU General Public License as published by
*    the Free Software Foundation, either version 3 of the License, or
*    (at your option) any later version.
*
*    This program 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 General Public License for more details.
*
*    You should have received a copy of the GNU General Public License
*    along with this program.  If not, see <http://www.gnu.org/licenses/>.
**************************************************************************/

#include "os_functions.h"
#include "../stringtools.h"
#include "../Interface/Server.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/statvfs.h>
#include <dirent.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <algorithm>
#include <memory.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <errno.h>

void getMousePos(int &x, int &y)
{
	x=0;
	y=0;
}

std::vector<SFile> getFiles(const std::wstring &path)
{
	std::string upath=Server->ConvertToUTF8(path);
	std::vector<SFile> tmp;
	DIR *dp;
    struct dirent *dirp;
    if((dp  = opendir(upath.c_str())) == NULL)
	{
		Server->Log("No permission to access \""+upath+"\"", LL_ERROR);
        return tmp;
    }

	upath+=os_file_sepn();

    while ((dirp = readdir(dp)) != NULL)
	{
		SFile f;
		f.name=widen(dirp->d_name);
		if(f.name==L"." || f.name==L".." )
			continue;

		f.isdir=(dirp->d_type==DT_DIR);
		if(!f.isdir || dirp->d_type==DT_UNKNOWN)
		{
			struct stat64 f_info;
			int rc=stat64((upath+dirp->d_name).c_str(), &f_info);
			if(rc==0)
			{
				if(dirp->d_type==DT_UNKNOWN)
				{
					f.isdir=S_ISDIR(f_info.st_mode);
					if(!f.isdir)
					{
						f.last_modified=f_info.st_mtime;
						f.size=f_info.st_size;
					}
				}
				else
				{
					f.last_modified=f_info.st_mtime;
					f.size=f_info.st_size;
				}
			}
			else
			{
				Server->Log("No permission to stat \""+upath+dirp->d_name+"\"", LL_ERROR);
				f.last_modified=0;
				f.size=0;
			}
		}
		else
		{
			f.last_modified=0;
			f.size=0;
		}
		tmp.push_back(f);
    }
    closedir(dp);

	std::sort(tmp.begin(), tmp.end());

    return tmp;
}

void removeFile(const std::wstring &path)
{
	unlink(wnarrow(path).c_str());
}

void moveFile(const std::wstring &src, const std::wstring &dst)
{
	rename(wnarrow(src).c_str(), wnarrow(dst).c_str() );
}

bool isDirectory(const std::wstring &path)
{
        struct stat64 f_info;
		int rc=stat64(Server->ConvertToUTF8(path).c_str(), &f_info);
		if(rc!=0)
		{
			Server->Log(L"No permission to access \""+path+L"\" (isdir)", LL_DEBUG);
			return false;
		}

        if ( S_ISDIR(f_info.st_mode) )
        {
                return true;
        }
        else
        {
                return false;
        }
}

int64 os_atoi64(const std::string &str)
{
	return strtoll(str.c_str(), NULL, 10);
}

bool os_create_dir(const std::wstring &dir)
{
	int rc=mkdir(Server->ConvertToUTF8(dir).c_str(), S_IRWXU | S_IRWXG );
	return rc==0;
}

bool os_create_hardlink(const std::wstring &linkname, const std::wstring &fname)
{
	int rc=link(Server->ConvertToUTF8(fname).c_str(), Server->ConvertToUTF8(linkname).c_str());
	return rc==0;
}

int64 os_free_space(const std::wstring &path)
{
	std::wstring cp=path;
	if(path.size()==0)
		return -1;
	if(cp[cp.size()-1]=='/')
		cp.erase(cp.size()-1, 1);
	if(cp[cp.size()-1]!='/')
		cp+='/';

	struct statvfs64 buf;
	int rc=statvfs64(Server->ConvertToUTF8(path).c_str(), &buf);
	if(rc==0)
		return buf.f_bsize*buf.f_bavail;
	else
		return -1;
}

bool os_directory_exists(const std::wstring &path)
{
	//std::string upath=Server->ConvertToUTF8(path);
	//DIR *dp=opendir(upath.c_str());
	//closedir(dp);
	//return dp!=NULL;
	return isDirectory(path);
}

bool os_remove_nonempty_dir(const std::wstring &path)
{
	std::string upath=Server->ConvertToUTF8(path);
	std::vector<SFile> tmp;
	DIR *dp;
    struct dirent *dirp;
    if((dp  = opendir(upath.c_str())) == NULL)
	{
		Server->Log("No permission to access \""+upath+"\"", LL_ERROR);
        return false;
    }

	bool ok=true;
	std::vector<std::wstring> subdirs;
	while ((dirp = readdir(dp)) != NULL)
	{
		if( (std::string)dirp->d_name!="." && (std::string)dirp->d_name!=".." )
		{
			if(dirp->d_type==DT_UNKNOWN)
			{
				struct stat64 f_info;
				int rc=stat64((upath+"/"+(std::string)dirp->d_name).c_str(), &f_info);
				if(rc==0)
				{
					if(S_ISDIR(f_info.st_mode) )
					{
						subdirs.push_back(Server->ConvertToUnicode(dirp->d_name));
					}
					else
					{
						if(unlink((upath+"/"+(std::string)dirp->d_name).c_str())!=0)
						{
							Server->Log("Error deleting file \""+upath+"/"+(std::string)dirp->d_name+"\"", LL_ERROR);
						}
					}
				}
				else
				{
					std::string e=nconvert(errno);
					switch(errno)
					{
					    case EACCES: e="EACCES"; break;
					    case EBADF: e="EBADF"; break;
					    case EFAULT: e="EFAULT"; break;
					    case ELOOP: e="ELOOP"; break;
					    case ENAMETOOLONG: e="ENAMETOOLONG"; break;
					    case ENOENT: e="ENOENT"; break;
					    case ENOMEM: e="ENOMEM"; break;
					    case ENOTDIR: e="ENOTDIR"; break;
					}
					Server->Log("No permission to stat \""+upath+"/"+dirp->d_name+"\" error: "+e, LL_ERROR);
				}
			}
			else if(dirp->d_type==DT_DIR )
			{
				subdirs.push_back(Server->ConvertToUnicode(dirp->d_name));
			}
			else
			{
				if(unlink((upath+"/"+(std::string)dirp->d_name).c_str())!=0)
				{
					Server->Log("Error deleting file \""+upath+"/"+(std::string)dirp->d_name+"\"", LL_ERROR);
				}
			}
		}
    }
    closedir(dp);
    for(size_t i=0;i<subdirs.size();++i)
    {
		bool b=os_remove_nonempty_dir(path+L"/"+subdirs[i]);
		if(!b)
		    ok=false;
    }
    if(rmdir(upath.c_str())!=0)
	{
		Server->Log("Error deleting directory \""+upath+"\"", LL_ERROR);
	}
	return ok;
}

std::wstring os_file_sep(void)
{
	return L"/";
}

std::string os_file_sepn(void)
{
	return "/";
}

bool os_link_symbolic(const std::wstring &target, const std::wstring &lname)
{
	return symlink(Server->ConvertToUTF8(target).c_str(), Server->ConvertToUTF8(lname).c_str())==0;
}

bool os_lookuphostname(std::string pServer, unsigned int *dest)
{
	const char* host=pServer.c_str();
    unsigned int addr = inet_addr(host);
    if (addr != INADDR_NONE)
	{
        *dest = addr;
    }
	else
	{
		hostent* hp = gethostbyname(host);
        if (hp != 0)
		{
			in_addr tmp;
			memcpy(&tmp, hp->h_addr,  hp->h_length );
			*dest=tmp.s_addr;
		}
		else
		{
			return false;
		}
	}
	return true;
}<|endoftext|>


<commit_before><commit_msg>Removing second SetState from main, was just using it for testing.<commit_after><|endoftext|>


<commit_before>#include <iostream>

#include "Dominio.h"
#include "Entidades.h"
#include "TestesDominio.h"
#include "TestesEntidades.h"

using namespace std;

int main()
{

    cout << "Testes de Dominios" << endl;

    TUNome testeNome;

    switch(testeNome.run()){
        case TUNome::SUCESSO: cout << "Nome - SUCESSO" << endl;
                                break;
        case TUNome::FALHA  : cout << "Nome - FALHA" << endl;
                                break;
    }

    TUTelefone testeTelefone;

    switch(testeTelefone.run()){
        case TUTelefone::SUCESSO: cout << "Telefone - SUCESSO" << endl;
                                break;
        case TUTelefone::FALHA  : cout << "Telefone - FALHA" << endl;
                                break;
    }

    TUTitulo testeTitulo;

    switch(testeTitulo.run()){
        case TUTitulo::SUCESSO: cout << "Titulo - SUCESSO" << endl;
                                break;
        case TUTitulo::FALHA  : cout << "Titulo - FALHA" << endl;
                                break;
    }

    TUCodigo testeCodigo;

    switch(testeCodigo.run()){
        case TUCodigo::SUCESSO: cout << "Codigo - SUCESSO" << endl;
                                break;
        case TUCodigo::FALHA  : cout << "Codigo - FALHA" << endl;
                                break;
    }

    TUGeneroLiterario testeGeneroLiterario;

    switch(testeGeneroLiterario.run()){
        case TUGeneroLiterario::SUCESSO: cout << "Genero Literario - SUCESSO" << endl;
                                break;
        case TUGeneroLiterario::FALHA  : cout << "Genero Literario - FALHA" << endl;
                                break;
    }

        TUApelido testeApelido;

    switch(testeApelido.run()){
        case TUApelido::SUCESSO: cout << "Apelido - SUCESSO" << endl;
                                break;
        case TUApelido::FALHA  : cout << "Apelido - FALHA" << endl;
                                break;
    }

    TUSenha testeSenha;

    switch(testeSenha.run()){
        case TUSenha::SUCESSO: cout << "Senha - SUCESSO" << endl;
                                break;
        case TUSenha::FALHA  : cout << "Senha - FALHA" << endl;
                                break;
    }

    TUData testeData;

    switch(testeData.run()){
        case TUData::SUCESSO: cout << "Data - SUCESSO" << endl;
                                break;
        case TUData::FALHA  : cout << "Data - FALHA" << endl;
                                break;
    }

    TUTexto testeTexto;

    switch(testeTexto.run()){
        case TUTexto::SUCESSO: cout << "Texto - SUCESSO" << endl;
                                break;
        case TUTexto::FALHA  : cout << "Texto - FALHA" << endl;
                                break;
    }

    cout << "Testes de Entidades" << endl;

    TUUsuario testeUsuario;

    switch(testeUsuario.run()){
        case TUUsuario::SUCESSO: cout << "Usuario - SUCESSO" << endl;
                                break;
        case TUUsuario::FALHA  : cout << "Usuario - FALHA" << endl;
                                break;
    }

    TUResenha testeResenha;

    switch(testeResenha.run()){
        case TUResenha::SUCESSO: cout << "Resenha - SUCESSO" << endl;
                                break;
        case TUResenha::FALHA  : cout << "Resenha - FALHA" << endl;
                                break;
    }

    TULivro testeLivro;

    switch(testeLivro.run()){
        case TULivro::SUCESSO: cout << "Livro - SUCESSO" << endl;
                                break;
        case TULivro::FALHA  : cout << "Livro - FALHA" << endl;
                                break;
    }
    return 0;
}
<commit_msg>adicionada uma quebra de linha no print dos testes<commit_after>#include <iostream>

#include "Dominio.h"
#include "Entidades.h"
#include "TestesDominio.h"
#include "TestesEntidades.h"

using namespace std;

int main()
{

    cout << "Testes de Dominios" << endl;

    TUNome testeNome;

    switch(testeNome.run()){
        case TUNome::SUCESSO: cout << "Nome - SUCESSO" << endl;
                                break;
        case TUNome::FALHA  : cout << "Nome - FALHA" << endl;
                                break;
    }

    TUTelefone testeTelefone;

    switch(testeTelefone.run()){
        case TUTelefone::SUCESSO: cout << "Telefone - SUCESSO" << endl;
                                break;
        case TUTelefone::FALHA  : cout << "Telefone - FALHA" << endl;
                                break;
    }

    TUTitulo testeTitulo;

    switch(testeTitulo.run()){
        case TUTitulo::SUCESSO: cout << "Titulo - SUCESSO" << endl;
                                break;
        case TUTitulo::FALHA  : cout << "Titulo - FALHA" << endl;
                                break;
    }

    TUCodigo testeCodigo;

    switch(testeCodigo.run()){
        case TUCodigo::SUCESSO: cout << "Codigo - SUCESSO" << endl;
                                break;
        case TUCodigo::FALHA  : cout << "Codigo - FALHA" << endl;
                                break;
    }

    TUGeneroLiterario testeGeneroLiterario;

    switch(testeGeneroLiterario.run()){
        case TUGeneroLiterario::SUCESSO: cout << "Genero Literario - SUCESSO" << endl;
                                break;
        case TUGeneroLiterario::FALHA  : cout << "Genero Literario - FALHA" << endl;
                                break;
    }

        TUApelido testeApelido;

    switch(testeApelido.run()){
        case TUApelido::SUCESSO: cout << "Apelido - SUCESSO" << endl;
                                break;
        case TUApelido::FALHA  : cout << "Apelido - FALHA" << endl;
                                break;
    }

    TUSenha testeSenha;

    switch(testeSenha.run()){
        case TUSenha::SUCESSO: cout << "Senha - SUCESSO" << endl;
                                break;
        case TUSenha::FALHA  : cout << "Senha - FALHA" << endl;
                                break;
    }

    TUData testeData;

    switch(testeData.run()){
        case TUData::SUCESSO: cout << "Data - SUCESSO" << endl;
                                break;
        case TUData::FALHA  : cout << "Data - FALHA" << endl;
                                break;
    }

    TUTexto testeTexto;

    switch(testeTexto.run()){
        case TUTexto::SUCESSO: cout << "Texto - SUCESSO" << endl;
                                break;
        case TUTexto::FALHA  : cout << "Texto - FALHA" << endl;
                                break;
    }
    cout << endl;
    cout << "Testes de Entidades" << endl;

    TUUsuario testeUsuario;

    switch(testeUsuario.run()){
        case TUUsuario::SUCESSO: cout << "Usuario - SUCESSO" << endl;
                                break;
        case TUUsuario::FALHA  : cout << "Usuario - FALHA" << endl;
                                break;
    }

    TUResenha testeResenha;

    switch(testeResenha.run()){
        case TUResenha::SUCESSO: cout << "Resenha - SUCESSO" << endl;
                                break;
        case TUResenha::FALHA  : cout << "Resenha - FALHA" << endl;
                                break;
    }

    TULivro testeLivro;

    switch(testeLivro.run()){
        case TULivro::SUCESSO: cout << "Livro - SUCESSO" << endl;
                                break;
        case TULivro::FALHA  : cout << "Livro - FALHA" << endl;
                                break;
    }
    return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#include "sal/config.h"
#include "sal/macros.h"

#include <cstddef>
#include <functional>
#include <memory>
#include <new>
#include <boost/unordered_map.hpp>

#include "com/sun/star/lang/XMain.hpp"
#include "com/sun/star/lang/XMultiComponentFactory.hpp"
#include "com/sun/star/uno/Exception.hpp"
#include "com/sun/star/uno/Reference.hxx"
#include "com/sun/star/uno/RuntimeException.hpp"
#include "com/sun/star/uno/Sequence.hxx"
#include "com/sun/star/uno/XComponentContext.hpp"
#include "com/sun/star/uno/XInterface.hpp"
#include "cppuhelper/factory.hxx"
#include "cppuhelper/implbase1.hxx"
#include "cppuhelper/implementationentry.hxx"
#include "cppuhelper/interfacecontainer.hxx"
#include "cppuhelper/unourl.hxx"
#include "cppuhelper/weak.hxx"
#include "osl/mutex.hxx"
#include "osl/thread.h"
#include "rtl/malformeduriexception.hxx"
#include "rtl/string.h"
#include "rtl/ustrbuf.hxx"
#include "rtl/ustring.h"
#include "rtl/ustring.hxx"
#include "sal/types.h"
#include "salhelper/simplereferenceobject.hxx"
#include "uno/current_context.hxx"
#include "uno/environment.h"
#include "uno/lbnames.h"

#include "test/types/CppTest.hpp"
#include "test/types/JavaTest.hpp"
#include "test/types/TestException.hpp"
#include "test/types/XTest.hpp"

namespace css = ::com::sun::star;

namespace {

class Service: public ::cppu::WeakImplHelper1< ::css::lang::XMain > {
public:
    explicit Service(
        ::css::uno::Reference< ::css::uno::XComponentContext > const & context):
        context_(context) {}

    virtual ::sal_Int32 SAL_CALL run(
        ::css::uno::Sequence< ::rtl::OUString > const &)
        throw (::css::uno::RuntimeException);

private:
    Service(Service &); // not defined
    void operator =(Service &); // not defined

    virtual ~Service() {}

    void test(
        ::css::uno::Reference< test::types::XTest > const & test,
        ::rtl::OUString const & name);

    ::css::uno::Reference< ::css::uno::XComponentContext > context_;
};

::sal_Int32 Service::run(::css::uno::Sequence< ::rtl::OUString > const &)
    throw (::css::uno::RuntimeException)
{
    osl_getThreadIdentifier(0); // check for sal
    (new salhelper::SimpleReferenceObject)->release(); // check for salhelper
    css::uno::getCurrentContext(); // check for cppu
    try { // check for cppuhelper
        std::auto_ptr< cppu::UnoUrl > dummy(new cppu::UnoUrl(rtl::OUString()));
    } catch (rtl::MalformedUriException &) {}
    { // check for stlport
        osl::Mutex m;
        std::auto_ptr< cppu::OMultiTypeInterfaceContainerHelperVar<
            int, std::hash< int >, std::equal_to< int > > > dummy(
                new cppu::OMultiTypeInterfaceContainerHelperVar<
                int, std::hash< int >, std::equal_to< int > >(m));
    }
    static char const * const services[] = {
        "com.sun.star.beans.Introspection",
        "com.sun.star.bridge.Bridge",
        "com.sun.star.bridge.BridgeFactory",
        "com.sun.star.bridge.IiopBridge",
        "com.sun.star.bridge.UnoUrlResolver",
        "com.sun.star.bridge.UrpBridge",
        "com.sun.star.connection.Acceptor",
        "com.sun.star.connection.Connector",
        "com.sun.star.io.DataInputStream",
        "com.sun.star.io.DataOutputStream",
        "com.sun.star.io.MarkableInputStream",
        "com.sun.star.io.MarkableOutputStream",
        "com.sun.star.io.ObjectInputStream",
        "com.sun.star.io.ObjectOutputStream",
        "com.sun.star.io.Pipe",
        "com.sun.star.io.Pump",
        "com.sun.star.io.TextInputStream",
        "com.sun.star.io.TextOutputStream",
        "com.sun.star.java.JavaVirtualMachine",
        "com.sun.star.lang.MultiServiceFactory",
        "com.sun.star.lang.RegistryServiceManager",
        "com.sun.star.lang.ServiceManager",
        "com.sun.star.loader.Java",
        "com.sun.star.loader.Java2",
        "com.sun.star.loader.SharedLibrary",
        "com.sun.star.reflection.CoreReflection",
        "com.sun.star.reflection.ProxyFactory",
        "com.sun.star.reflection.TypeDescriptionManager",
        "com.sun.star.reflection.TypeDescriptionProvider",
        "com.sun.star.registry.ImplementationRegistration",
        "com.sun.star.registry.NestedRegistry",
        "com.sun.star.registry.SimpleRegistry",
        "com.sun.star.script.Converter",
        "com.sun.star.script.Invocation",
        "com.sun.star.script.InvocationAdapterFactory",
        "com.sun.star.security.AccessController",
        "com.sun.star.security.Policy",
        "com.sun.star.uno.NamingService",
        "com.sun.star.uri.ExternalUriReferenceTranslator",
        "com.sun.star.uri.UriReferenceFactory",
        "com.sun.star.uri.UriSchemeParser_vndDOTsunDOTstarDOTscript",
        "com.sun.star.uri.VndSunStarPkgUrlReferenceFactory"
    };
    ::css::uno::Reference< ::css::lang::XMultiComponentFactory > manager(
        context_->getServiceManager());
    if (!manager.is()) {
        throw ::css::uno::RuntimeException(
            ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("no service manager")),
            static_cast< ::cppu::OWeakObject * >(this));
    }
    for (::std::size_t i = 0; i < SAL_N_ELEMENTS(services); ++i) {
        ::css::uno::Reference< ::css::uno::XInterface > instance;
        try {
            instance = manager->createInstanceWithContext(
                ::rtl::OUString::createFromAscii(services[i]), context_);
        } catch (::css::uno::RuntimeException &) {
            throw;
        } catch (::css::uno::Exception &) {
            throw ::css::uno::RuntimeException(
                ::rtl::OUString(
                    RTL_CONSTASCII_USTRINGPARAM("error creating instance")),
                static_cast< ::cppu::OWeakObject * >(this));
        }
        if (!instance.is()) {
            throw ::css::uno::RuntimeException(
                ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("no instance")),
                static_cast< ::cppu::OWeakObject * >(this));
        }
    }
    static char const * const singletons[] = {
        "com.sun.star.util.theMacroExpander" };
    for (::std::size_t i = 0; i < SAL_N_ELEMENTS(singletons); ++i)
    {
        ::rtl::OUStringBuffer b;
        b.appendAscii(RTL_CONSTASCII_STRINGPARAM("/singletons/"));
        b.appendAscii(singletons[i]);
        ::css::uno::Reference< ::css::uno::XInterface > instance(
            context_->getValueByName(b.makeStringAndClear()),
            ::css::uno::UNO_QUERY_THROW);
    }
    test(
        ::test::types::CppTest::create(context_),
        ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("test.types.CppTest")));
    test(
        ::test::types::JavaTest::create(context_),
        ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("test.types.JavaTest")));
    return 0;
}

void Service::test(
    ::css::uno::Reference< test::types::XTest > const & test,
    ::rtl::OUString const & name)
{
    bool ok = false;
    try {
        test->throwException();
    } catch (::test::types::TestException &) {
        ok = true;
    }
    if (!ok) {
        throw ::css::uno::RuntimeException(
            (name
             + ::rtl::OUString(
                 RTL_CONSTASCII_USTRINGPARAM(".throwException failed"))),
            static_cast< ::cppu::OWeakObject * >(this));
    }
}

namespace CppMain {

::css::uno::Reference< ::css::uno::XInterface > create(
    ::css::uno::Reference< ::css::uno::XComponentContext > const & context)
    SAL_THROW((::css::uno::Exception))
{
    try {
        return static_cast< ::cppu::OWeakObject * >(new Service(context));
    } catch (::std::bad_alloc &) {
        throw ::css::uno::RuntimeException(
            ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("std::bad_alloc")),
            ::css::uno::Reference< ::css::uno::XInterface >());
    }
}

::rtl::OUString getImplementationName() {
    return ::rtl::OUString(
        RTL_CONSTASCII_USTRINGPARAM("test.cpp.cppmain.Component"));
}

::css::uno::Sequence< ::rtl::OUString > getSupportedServiceNames() {
    return ::css::uno::Sequence< ::rtl::OUString >();
}

}

::cppu::ImplementationEntry entries[] = {
    { CppMain::create, CppMain::getImplementationName,
      CppMain::getSupportedServiceNames, ::cppu::createSingleComponentFactory,
      0, 0 },
    { 0, 0, 0, 0, 0, 0 } };

}

extern "C" ::sal_Bool SAL_CALL component_writeInfo(
    void * serviceManager, void * registryKey)
{
    return ::cppu::component_writeInfoHelper(
        serviceManager, registryKey, entries);
}

extern "C" void * SAL_CALL component_getFactory(
    char const * implName, void * serviceManager, void * registryKey)
{
    return ::cppu::component_getFactoryHelper(
        implName, serviceManager, registryKey, entries);
}

extern "C" void SAL_CALL component_getImplementationEnvironment(
    char const ** envTypeName, ::uno_Environment **)
{
    *envTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
}
<commit_msg>std::hash -> boost::hash<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#include "sal/config.h"
#include "sal/macros.h"

#include <cstddef>
#include <functional>
#include <memory>
#include <new>
#include <boost/unordered_map.hpp>

#include "com/sun/star/lang/XMain.hpp"
#include "com/sun/star/lang/XMultiComponentFactory.hpp"
#include "com/sun/star/uno/Exception.hpp"
#include "com/sun/star/uno/Reference.hxx"
#include "com/sun/star/uno/RuntimeException.hpp"
#include "com/sun/star/uno/Sequence.hxx"
#include "com/sun/star/uno/XComponentContext.hpp"
#include "com/sun/star/uno/XInterface.hpp"
#include "cppuhelper/factory.hxx"
#include "cppuhelper/implbase1.hxx"
#include "cppuhelper/implementationentry.hxx"
#include "cppuhelper/interfacecontainer.hxx"
#include "cppuhelper/unourl.hxx"
#include "cppuhelper/weak.hxx"
#include "osl/mutex.hxx"
#include "osl/thread.h"
#include "rtl/malformeduriexception.hxx"
#include "rtl/string.h"
#include "rtl/ustrbuf.hxx"
#include "rtl/ustring.h"
#include "rtl/ustring.hxx"
#include "sal/types.h"
#include "salhelper/simplereferenceobject.hxx"
#include "uno/current_context.hxx"
#include "uno/environment.h"
#include "uno/lbnames.h"

#include "test/types/CppTest.hpp"
#include "test/types/JavaTest.hpp"
#include "test/types/TestException.hpp"
#include "test/types/XTest.hpp"

namespace css = ::com::sun::star;

namespace {

class Service: public ::cppu::WeakImplHelper1< ::css::lang::XMain > {
public:
    explicit Service(
        ::css::uno::Reference< ::css::uno::XComponentContext > const & context):
        context_(context) {}

    virtual ::sal_Int32 SAL_CALL run(
        ::css::uno::Sequence< ::rtl::OUString > const &)
        throw (::css::uno::RuntimeException);

private:
    Service(Service &); // not defined
    void operator =(Service &); // not defined

    virtual ~Service() {}

    void test(
        ::css::uno::Reference< test::types::XTest > const & test,
        ::rtl::OUString const & name);

    ::css::uno::Reference< ::css::uno::XComponentContext > context_;
};

::sal_Int32 Service::run(::css::uno::Sequence< ::rtl::OUString > const &)
    throw (::css::uno::RuntimeException)
{
    osl_getThreadIdentifier(0); // check for sal
    (new salhelper::SimpleReferenceObject)->release(); // check for salhelper
    css::uno::getCurrentContext(); // check for cppu
    try { // check for cppuhelper
        std::auto_ptr< cppu::UnoUrl > dummy(new cppu::UnoUrl(rtl::OUString()));
    } catch (rtl::MalformedUriException &) {}
    { // check for stlport
        osl::Mutex m;
        std::auto_ptr< cppu::OMultiTypeInterfaceContainerHelperVar<
            int, boost::hash< int >, std::equal_to< int > > > dummy(
                new cppu::OMultiTypeInterfaceContainerHelperVar<
                int, boost::hash< int >, std::equal_to< int > >(m));
    }
    static char const * const services[] = {
        "com.sun.star.beans.Introspection",
        "com.sun.star.bridge.Bridge",
        "com.sun.star.bridge.BridgeFactory",
        "com.sun.star.bridge.IiopBridge",
        "com.sun.star.bridge.UnoUrlResolver",
        "com.sun.star.bridge.UrpBridge",
        "com.sun.star.connection.Acceptor",
        "com.sun.star.connection.Connector",
        "com.sun.star.io.DataInputStream",
        "com.sun.star.io.DataOutputStream",
        "com.sun.star.io.MarkableInputStream",
        "com.sun.star.io.MarkableOutputStream",
        "com.sun.star.io.ObjectInputStream",
        "com.sun.star.io.ObjectOutputStream",
        "com.sun.star.io.Pipe",
        "com.sun.star.io.Pump",
        "com.sun.star.io.TextInputStream",
        "com.sun.star.io.TextOutputStream",
        "com.sun.star.java.JavaVirtualMachine",
        "com.sun.star.lang.MultiServiceFactory",
        "com.sun.star.lang.RegistryServiceManager",
        "com.sun.star.lang.ServiceManager",
        "com.sun.star.loader.Java",
        "com.sun.star.loader.Java2",
        "com.sun.star.loader.SharedLibrary",
        "com.sun.star.reflection.CoreReflection",
        "com.sun.star.reflection.ProxyFactory",
        "com.sun.star.reflection.TypeDescriptionManager",
        "com.sun.star.reflection.TypeDescriptionProvider",
        "com.sun.star.registry.ImplementationRegistration",
        "com.sun.star.registry.NestedRegistry",
        "com.sun.star.registry.SimpleRegistry",
        "com.sun.star.script.Converter",
        "com.sun.star.script.Invocation",
        "com.sun.star.script.InvocationAdapterFactory",
        "com.sun.star.security.AccessController",
        "com.sun.star.security.Policy",
        "com.sun.star.uno.NamingService",
        "com.sun.star.uri.ExternalUriReferenceTranslator",
        "com.sun.star.uri.UriReferenceFactory",
        "com.sun.star.uri.UriSchemeParser_vndDOTsunDOTstarDOTscript",
        "com.sun.star.uri.VndSunStarPkgUrlReferenceFactory"
    };
    ::css::uno::Reference< ::css::lang::XMultiComponentFactory > manager(
        context_->getServiceManager());
    if (!manager.is()) {
        throw ::css::uno::RuntimeException(
            ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("no service manager")),
            static_cast< ::cppu::OWeakObject * >(this));
    }
    for (::std::size_t i = 0; i < SAL_N_ELEMENTS(services); ++i) {
        ::css::uno::Reference< ::css::uno::XInterface > instance;
        try {
            instance = manager->createInstanceWithContext(
                ::rtl::OUString::createFromAscii(services[i]), context_);
        } catch (::css::uno::RuntimeException &) {
            throw;
        } catch (::css::uno::Exception &) {
            throw ::css::uno::RuntimeException(
                ::rtl::OUString(
                    RTL_CONSTASCII_USTRINGPARAM("error creating instance")),
                static_cast< ::cppu::OWeakObject * >(this));
        }
        if (!instance.is()) {
            throw ::css::uno::RuntimeException(
                ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("no instance")),
                static_cast< ::cppu::OWeakObject * >(this));
        }
    }
    static char const * const singletons[] = {
        "com.sun.star.util.theMacroExpander" };
    for (::std::size_t i = 0; i < SAL_N_ELEMENTS(singletons); ++i)
    {
        ::rtl::OUStringBuffer b;
        b.appendAscii(RTL_CONSTASCII_STRINGPARAM("/singletons/"));
        b.appendAscii(singletons[i]);
        ::css::uno::Reference< ::css::uno::XInterface > instance(
            context_->getValueByName(b.makeStringAndClear()),
            ::css::uno::UNO_QUERY_THROW);
    }
    test(
        ::test::types::CppTest::create(context_),
        ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("test.types.CppTest")));
    test(
        ::test::types::JavaTest::create(context_),
        ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("test.types.JavaTest")));
    return 0;
}

void Service::test(
    ::css::uno::Reference< test::types::XTest > const & test,
    ::rtl::OUString const & name)
{
    bool ok = false;
    try {
        test->throwException();
    } catch (::test::types::TestException &) {
        ok = true;
    }
    if (!ok) {
        throw ::css::uno::RuntimeException(
            (name
             + ::rtl::OUString(
                 RTL_CONSTASCII_USTRINGPARAM(".throwException failed"))),
            static_cast< ::cppu::OWeakObject * >(this));
    }
}

namespace CppMain {

::css::uno::Reference< ::css::uno::XInterface > create(
    ::css::uno::Reference< ::css::uno::XComponentContext > const & context)
    SAL_THROW((::css::uno::Exception))
{
    try {
        return static_cast< ::cppu::OWeakObject * >(new Service(context));
    } catch (::std::bad_alloc &) {
        throw ::css::uno::RuntimeException(
            ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("std::bad_alloc")),
            ::css::uno::Reference< ::css::uno::XInterface >());
    }
}

::rtl::OUString getImplementationName() {
    return ::rtl::OUString(
        RTL_CONSTASCII_USTRINGPARAM("test.cpp.cppmain.Component"));
}

::css::uno::Sequence< ::rtl::OUString > getSupportedServiceNames() {
    return ::css::uno::Sequence< ::rtl::OUString >();
}

}

::cppu::ImplementationEntry entries[] = {
    { CppMain::create, CppMain::getImplementationName,
      CppMain::getSupportedServiceNames, ::cppu::createSingleComponentFactory,
      0, 0 },
    { 0, 0, 0, 0, 0, 0 } };

}

extern "C" ::sal_Bool SAL_CALL component_writeInfo(
    void * serviceManager, void * registryKey)
{
    return ::cppu::component_writeInfoHelper(
        serviceManager, registryKey, entries);
}

extern "C" void * SAL_CALL component_getFactory(
    char const * implName, void * serviceManager, void * registryKey)
{
    return ::cppu::component_getFactoryHelper(
        implName, serviceManager, registryKey, entries);
}

extern "C" void SAL_CALL component_getImplementationEnvironment(
    char const ** envTypeName, ::uno_Environment **)
{
    *envTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
}
<|endoftext|>