<commit_before>/*
* Copyright (C) 2011 Daniele E. Domenichelli <daniele.domenichelli@gmail.com>
* Copyright (C) 1999 Preston Brown <pbrown@kde.org>
*
* 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 "telepathy-handler-application.h"
#include "debug.h"

#include <cstdlib>

#include <QTimer>
#include <KCmdLineArgs>
#include <KDebug>

#include <TelepathyQt/Types>
#include <TelepathyQt/Debug>

extern bool kde_kdebug_enable_dbus_interface;

namespace KTp
{

class TelepathyHandlerApplication::Private
{
public:
    Private(TelepathyHandlerApplication *q);
    ~Private();

    void _k_onInitialTimeout();
    void _k_onTimeout();

    void init(int initialTimeout, int timeout);

    TelepathyHandlerApplication *q;

    static bool s_persist;
    static bool s_debug;

    int initialTimeout;
    int timeout;
    QTimer *timer;
    bool firstJobStarted;
    QAtomicInt jobCount;
};

TelepathyHandlerApplication::Private::Private(TelepathyHandlerApplication *q)
    : q(q),
      firstJobStarted(false),
      jobCount(0)
{
}

TelepathyHandlerApplication::Private::~Private()
{
}

void TelepathyHandlerApplication::Private::_k_onInitialTimeout()
{
    if (jobCount.load() == 0 && jobCount.fetchAndAddOrdered(-1) == 0) {
        // m_jobCount is now -1
        kDebug() << "No job received. Exiting";
        QCoreApplication::quit();
    }
}

void TelepathyHandlerApplication::Private::_k_onTimeout()
{
    if (jobCount.load() == 0 && jobCount.fetchAndAddOrdered(-1) == 0) {
        // m_jobCount is now -1
        kDebug() << "Timeout. Exiting";
        QCoreApplication::quit();
    }
}

void TelepathyHandlerApplication::Private::init(int initialTimeout, int timeout)
{
    this->initialTimeout = initialTimeout;
    this->timeout = timeout;

    // If timeout < 0 we let the application exit when the last window is closed,
    // Otherwise we handle it with the timeout
    if (timeout >= 0) {
        q->setQuitOnLastWindowClosed(false);
    }

    // Register TpQt4 types
    Tp::registerTypes();

    // Install TpQt4 debug callback
    KTp::Debug::installCallback(s_debug);

    // Enable KDebug DBus interface
    // FIXME This must be enabled here because there is a bug in plasma
    //       it should be removed when this is fixed
    kde_kdebug_enable_dbus_interface = s_debug;

    if (!Private::s_persist) {
        timer = new QTimer(q);
        if (initialTimeout >= 0) {
            q->connect(timer, SIGNAL(timeout()), q, SLOT(_k_onInitialTimeout()));
            timer->start(initialTimeout);
        }
    }
}

bool TelepathyHandlerApplication::Private::s_persist = false;
bool TelepathyHandlerApplication::Private::s_debug = false;

TelepathyHandlerApplication::TelepathyHandlerApplication(int &argc, char *argv[],
                                                         int initialTimeout,
                                                         int timeout)
    : QApplication(argc, argv),
      d(new Private(this))
{
    QCoreApplication::setApplicationName(i18n("KDE Telepathy"));

    QCommandLineOption persistOption(QStringLiteral("persist"), i18n("Persistent mode (do not exit on timeout)"));
    QCommandLineOption debugOption(QStringLiteral("debug"), i18n("Show Telepathy debugging information"));

    QCommandLineParser cmdParser;
    cmdParser.addHelpOption();
    cmdParser.addOption(persistOption);
    cmdParser.addOption(debugOption);
    cmdParser.process(qApp->arguments());

    Private::s_persist = cmdParser.isSet(QStringLiteral("persist"));
    Private::s_debug = cmdParser.isSet(QStringLiteral("debug"));

    d->init(initialTimeout, timeout);
}

TelepathyHandlerApplication::~TelepathyHandlerApplication()
{
    delete d;
}

int TelepathyHandlerApplication::newJob()
{
    TelepathyHandlerApplication *app = qobject_cast<TelepathyHandlerApplication*>(qApp);
    TelepathyHandlerApplication::Private *d = app->d;

    int ret = d->jobCount.fetchAndAddOrdered(1);
    if (!Private::s_persist) {
        if (d->timer->isActive()) {
            d->timer->stop();
        }
        if (!d->firstJobStarted) {
            if (d->initialTimeout) {
                disconnect(d->timer, SIGNAL(timeout()), app, SLOT(_k_onInitialTimeout()));
            }
            if (d->timeout >= 0) {
                connect(d->timer, SIGNAL(timeout()), app, SLOT(_k_onTimeout()));
            }
            d->firstJobStarted = true;
        }
    }
    kDebug() << "New job started." << d->jobCount.load() << "jobs currently running";
    return ret;
}

void TelepathyHandlerApplication::jobFinished()
{
    TelepathyHandlerApplication *app = qobject_cast<TelepathyHandlerApplication*>(qApp);
    TelepathyHandlerApplication::Private *d = app->d;

    if (d->jobCount.fetchAndAddOrdered(-1) <= 1) {
        if (!Private::s_persist && d->timeout >= 0) {
            kDebug() << "No other jobs at the moment. Starting timer.";
            d->timer->start(d->timeout);
        }
    }
    kDebug() << "Job finished." << d->jobCount.load() << "jobs currently running";
}

} // namespace KTp

#include "moc_telepathy-handler-application.cpp"
<commit_msg>Port TelepathyHandlerApplication away from kDebug<commit_after>/*
* Copyright (C) 2011 Daniele E. Domenichelli <daniele.domenichelli@gmail.com>
* Copyright (C) 1999 Preston Brown <pbrown@kde.org>
*
* 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 "telepathy-handler-application.h"
#include "debug.h"

#include <cstdlib>

#include <QTimer>
#include <KCmdLineArgs>
#include <KDebug>

#include <TelepathyQt/Types>
#include <TelepathyQt/Debug>

extern bool kde_kdebug_enable_dbus_interface;

namespace KTp
{

class TelepathyHandlerApplication::Private
{
public:
    Private(TelepathyHandlerApplication *q);
    ~Private();

    void _k_onInitialTimeout();
    void _k_onTimeout();

    void init(int initialTimeout, int timeout);

    TelepathyHandlerApplication *q;

    static bool s_persist;
    static bool s_debug;

    int initialTimeout;
    int timeout;
    QTimer *timer;
    bool firstJobStarted;
    QAtomicInt jobCount;
};

TelepathyHandlerApplication::Private::Private(TelepathyHandlerApplication *q)
    : q(q),
      firstJobStarted(false),
      jobCount(0)
{
}

TelepathyHandlerApplication::Private::~Private()
{
}

void TelepathyHandlerApplication::Private::_k_onInitialTimeout()
{
    if (jobCount.load() == 0 && jobCount.fetchAndAddOrdered(-1) == 0) {
        // m_jobCount is now -1
        qDebug() << "No job received. Exiting";
        QCoreApplication::quit();
    }
}

void TelepathyHandlerApplication::Private::_k_onTimeout()
{
    if (jobCount.load() == 0 && jobCount.fetchAndAddOrdered(-1) == 0) {
        // m_jobCount is now -1
        qDebug() << "Timeout. Exiting";
        QCoreApplication::quit();
    }
}

void TelepathyHandlerApplication::Private::init(int initialTimeout, int timeout)
{
    this->initialTimeout = initialTimeout;
    this->timeout = timeout;

    // If timeout < 0 we let the application exit when the last window is closed,
    // Otherwise we handle it with the timeout
    if (timeout >= 0) {
        q->setQuitOnLastWindowClosed(false);
    }

    // Register TpQt4 types
    Tp::registerTypes();

    // Install TpQt4 debug callback
    KTp::Debug::installCallback(s_debug);

    // Enable KDebug DBus interface
    // FIXME This must be enabled here because there is a bug in plasma
    //       it should be removed when this is fixed
    kde_kdebug_enable_dbus_interface = s_debug;

    if (!Private::s_persist) {
        timer = new QTimer(q);
        if (initialTimeout >= 0) {
            q->connect(timer, SIGNAL(timeout()), q, SLOT(_k_onInitialTimeout()));
            timer->start(initialTimeout);
        }
    }
}

bool TelepathyHandlerApplication::Private::s_persist = false;
bool TelepathyHandlerApplication::Private::s_debug = false;

TelepathyHandlerApplication::TelepathyHandlerApplication(int &argc, char *argv[],
                                                         int initialTimeout,
                                                         int timeout)
    : QApplication(argc, argv),
      d(new Private(this))
{
    QCoreApplication::setApplicationName(i18n("KDE Telepathy"));

    QCommandLineOption persistOption(QStringLiteral("persist"), i18n("Persistent mode (do not exit on timeout)"));
    QCommandLineOption debugOption(QStringLiteral("debug"), i18n("Show Telepathy debugging information"));

    QCommandLineParser cmdParser;
    cmdParser.addHelpOption();
    cmdParser.addOption(persistOption);
    cmdParser.addOption(debugOption);
    cmdParser.process(qApp->arguments());

    Private::s_persist = cmdParser.isSet(QStringLiteral("persist"));
    Private::s_debug = cmdParser.isSet(QStringLiteral("debug"));

    d->init(initialTimeout, timeout);
}

TelepathyHandlerApplication::~TelepathyHandlerApplication()
{
    delete d;
}

int TelepathyHandlerApplication::newJob()
{
    TelepathyHandlerApplication *app = qobject_cast<TelepathyHandlerApplication*>(qApp);
    TelepathyHandlerApplication::Private *d = app->d;

    int ret = d->jobCount.fetchAndAddOrdered(1);
    if (!Private::s_persist) {
        if (d->timer->isActive()) {
            d->timer->stop();
        }
        if (!d->firstJobStarted) {
            if (d->initialTimeout) {
                disconnect(d->timer, SIGNAL(timeout()), app, SLOT(_k_onInitialTimeout()));
            }
            if (d->timeout >= 0) {
                connect(d->timer, SIGNAL(timeout()), app, SLOT(_k_onTimeout()));
            }
            d->firstJobStarted = true;
        }
    }
    qDebug() << "New job started." << d->jobCount.load() << "jobs currently running";
    return ret;
}

void TelepathyHandlerApplication::jobFinished()
{
    TelepathyHandlerApplication *app = qobject_cast<TelepathyHandlerApplication*>(qApp);
    TelepathyHandlerApplication::Private *d = app->d;

    if (d->jobCount.fetchAndAddOrdered(-1) <= 1) {
        if (!Private::s_persist && d->timeout >= 0) {
            qDebug() << "No other jobs at the moment. Starting timer.";
            d->timer->start(d->timeout);
        }
    }
    qDebug() << "Job finished." << d->jobCount.load() << "jobs currently running";
}

} // namespace KTp

#include "moc_telepathy-handler-application.cpp"
<|endoftext|>


<commit_before>/*
 * message_opt.cc
 *
 *  Created on: Mar 18, 2013
 *      Author: yaowei
 */

#include <sys/socket.h>
#include "logic_opt.h"
#include "defines.h"
#include "json_opt.h"
#include "redis_conn_pool.h"
#include "global_settings.h"
#include "../../public/utils.h"
#include "../../public/redis_key.h"
#include "../../public/socket_wrapper.h"
#include "../../public/message.h"
#include "../../public/error_code.h"
#include "device_alive.h"

CLogicOpt::CLogicOpt(conn* c)
{
	conn_ = c;
	result_ = 0;
    is_online_ = false;
	jsonOpt_ptr_ = new CJsonOpt;
	assert(jsonOpt_ptr_ != NULL);
}

CLogicOpt::~CLogicOpt()
{
	utils::SafeDelete(jsonOpt_ptr_);
}

void CLogicOpt::StartLogicOpt(const std::string& message)
{
    int ret = 0;
	std::string custom_msg;
    string method;

	LOG4CXX_INFO(g_logger, "CLogicOperate::StartLogicOpt" << message);

	jsonOpt_ptr_->setJsonString(message);
    if (!jsonOpt_ptr_->JsonParseCommon())
    {
		LOG4CXX_ERROR(g_logger, "CLogicOperate::StartLogicOpt:JsonParseCommon failed:" << message);
        return;
    }

    ret = jsonOpt_ptr_->GetMethod(method);
    if (ret != 0)
    {
		LOG4CXX_ERROR(g_logger, "CLogicOperate::StartLogicOpt:GetMethod failed:" << message);
        return;
    }

    if (method == METHOD_DEVICE_LOGIN)
    {
        DeviceLogin();
        goto SEND_RESPONSE;
    }
    else if (method == METHOD_KEEP_ONLINE)
    {
        DeviceBeacon();
        goto SEND_RESPONSE;
    }
    else if (method == METHOD_SET_STREAMSERVER_ADDR)
    {
        HandlePushMsgResp();
        goto SEND_RESPONSE;
    }
    else
    {
		LOG4CXX_ERROR(g_logger, "CLogicOpt::StartLogicOpt method invalid");
        return;
    }

SEND_RESPONSE:
    string response_msg = utils::ReplaceString(responseToClient_, "\\r\\n", "\\\\r\\\\n");
    response_msg.append("\r\n");
    if (!SocketOperate::WriteSfd(conn_->sfd, response_msg.c_str(), response_msg.length()))
    {
        LOG4CXX_ERROR(g_logger, "SocketOperate::WriteSfd error, fd " << conn_->sfd << ", push_msg " << responseToClient_);
        ret = -ERROR_PUSH_MESSAGE;
    }

    return;
}

int CLogicOpt::DeviceLogin()
{
    int ret = 0;
    deque<int> auth_data;

	LOG4CXX_TRACE(g_logger, "CLogicOpt::DeviceLogin enter");

    ret = jsonOpt_ptr_->JsonParseLogin(dev_id_, auth_data);
    if (ret != 0)
    {
	    LOG4CXX_ERROR(g_logger, "CLogicOpt::DeviceLogin parse login error, ret is " << ret);
        goto out;
    }

    if (!conn_)
    {
        LOG4CXX_ERROR(g_logger, "DeviceLogin conn_ is NULL");
        ret = -ERROR_DEVICE_CONNECT;
        goto out;
    }

    // TODO: 认证设备的合法性

    if (!conn_->is_login)
    {
        conn_->is_login = true;
        conn_->dev_id = dev_id_;

        // 获取上线设备的ip
        struct sockaddr_in dev_addr;
        socklen_t len;
        memset(&dev_addr, 0, sizeof(struct sockaddr));
        ret = getpeername(conn_->sfd, (struct sockaddr*)&dev_addr, &len);
        if (ret != 0)
        {
	        LOG4CXX_ERROR(g_logger, "DeviceBeacon getpeername failed, errno is " << -errno);
            ret = -errno;
            goto out;
        }
        string dev_ip(inet_ntoa(dev_addr.sin_addr));

        // 更新设备在redis中的信息
        ret = CLogicOpt::SetDeviceFdCache(conn_->dev_id, conn_->sfd);
        if (ret != 0)
        {
	        LOG4CXX_ERROR(g_logger, "DeviceBeacon set fd cache failed");
            ret = -ERROR_SET_DEVICE_FD_CACHE;
            goto out;
        }

        ret = CLogicOpt::SetDeviceAddrCache(conn_->dev_id, utils::G<CGlobalSettings>().public_addr_, utils::G<CGlobalSettings>().private_addr_, dev_ip);
        if (ret != 0)
        {
	        LOG4CXX_ERROR(g_logger, "DeviceBeacon getsockname error");
            goto out;
        }

        // 通知设备上线
        time_t now;
        time(&now);
        string time_info(ctime(&now));
        CJsonOpt json_opt;
        string msg_info = json_opt.JsonJoinDeviceStateNotice(conn_->dev_id, 1, time_info);
        string url = utils::G<CGlobalSettings>().httpserver_url_;
        SendMsg send_msg(url, msg_info);
        g_http_client->SubmitMsg(send_msg);

	    LOG4CXX_TRACE(g_logger, "DeviceBeacon ok, dev_id is " << conn_->dev_id << ", sfd is " << conn_->sfd);
    }

out:
    responseToClient_ = jsonOpt_ptr_->JsonJoinLoginRes(ret);
    return ret;
}

int CLogicOpt::DeviceBeacon()
{
    int ret = 0;
    string dev_id;

	LOG4CXX_TRACE(g_logger, "CLogicOpt::DeviceBeacon enter");

    ret = jsonOpt_ptr_->JsonParseBeacon(dev_id);
    if (ret != 0)
    {
	    LOG4CXX_ERROR(g_logger, "CLogicOpt::StartLogicOpt:JsonParseBecon failed");
        goto out;
    }

    if (!conn_)
    {
	    LOG4CXX_ERROR(g_logger, "DeviceBeacon device conn_ is null");
        ret = -ERROR_DEVICE_CONNECT;
        goto out;
    }

    if (!conn_->is_login)
    {
	    LOG4CXX_ERROR(g_logger, "DeviceBeacon device conn_ is null");
        ret = -ERROR_DEVICE_NOT_LOGIN;
        goto out;
    }

    if (!conn_->is_online)
    {
        conn_->is_online = true;
    }

out:
    responseToClient_ = jsonOpt_ptr_->JsonJoinBeaconRes(ret);
    return ret;
}

int CLogicOpt::HandlePushMsgResp()
{
    int ret = 0;
    int msg_ret;
    int push_cnt = 0;
    string method;

    push_cnt = jsonOpt_ptr_->GetSendCnt();
    jsonOpt_ptr_->GetMethod(method);
    LOG4CXX_TRACE(g_logger, "handle push msg resp, method is " << method << ", push_cnt is " << push_cnt);

    JSONNode param_node;
    ret = jsonOpt_ptr_->JsonParsePushMsgResp(msg_ret, param_node);
    if (ret != 0)
    {
        msg_ret = -ERROR_PARSE_MSG;
	    LOG4CXX_ERROR(g_logger, "CLogicOpt::StartLogicOpt:HandlePushMsgResp failed");
    }

    g_wait_finish_push_msg_queue.FinishPushMsg(push_cnt, msg_ret, param_node);

    return 0;
}

int CLogicOpt::SetDeviceFdCache(string dev_id, int fd)
{
    int ret = 0;
    redisContext* redis_con = CRedisConnPool::GetInstance()->GetRedisContext();
    CRedisOpt redis_opt;
    redis_opt.SetRedisContext(redis_con);
    redis_opt.SelectDB(REDIS_DEVICE_INFO);

    if(!redis_opt.Hset(dev_id, REDIS_FIELD_FD, fd))
    {
        ret = -ERROR_SET_DEVICE_FD_CACHE;
        goto out;
    }

out:
	CRedisConnPool::GetInstance()->ReleaseRedisContext(redis_con);

    return ret;
}

int CLogicOpt::GetDeviceFdFromCache(string dev_id, int &fd)
{
    int ret = 0;
    redisContext* redis_con = CRedisConnPool::GetInstance()->GetRedisContext();
    CRedisOpt redis_opt;
    redis_opt.SetRedisContext(redis_con);
    redis_opt.SelectDB(REDIS_DEVICE_INFO);

    string fd_str;
    if(!redis_opt.Hget(dev_id, REDIS_FIELD_FD, fd_str))
    {
        ret = -ERROR_GET_DEVICE_FD_FROM_CACHE;
        goto out;
    }

    fd = atoi(fd_str.c_str());
out:
	CRedisConnPool::GetInstance()->ReleaseRedisContext(redis_con);

    return ret;
}

int CLogicOpt::RemoveDeviceFdFromCache(string dev_id)
{
    redisContext* redis_con = CRedisConnPool::GetInstance()->GetRedisContext();
    CRedisOpt redis_opt;
    redis_opt.SetRedisContext(redis_con);
    redis_opt.SelectDB(REDIS_DEVICE_INFO);

    redis_opt.Hdel(dev_id, REDIS_FIELD_FD);

	CRedisConnPool::GetInstance()->ReleaseRedisContext(redis_con);

    return 0;
}

int CLogicOpt::SetDeviceAddrCache(string dev_id, string public_addr, string private_addr, string dev_ip)
{
    int ret = 0;
    redisContext* redis_con = CRedisConnPool::GetInstance()->GetRedisContext();
    CRedisOpt redis_opt;
    redis_opt.SetRedisContext(redis_con);
    redis_opt.SelectDB(REDIS_DEVICE_INFO);

    if(!redis_opt.Hset(dev_id, REDIS_FIELD_PUBLIC_ADDR, public_addr))
    {
        ret = -ERROR_SET_DEVICE_ADDR_CACHE;
        goto out;
    }

    if (!redis_opt.Hset(dev_id, REDIS_FIELD_PRIVATE_ADDR, private_addr))
    {
        redis_opt.Hdel(dev_id, REDIS_FIELD_PUBLIC_ADDR);
        ret = -ERROR_SET_DEVICE_ADDR_CACHE;
        goto out;
    }

    if (!redis_opt.Hset(dev_id, REDIS_FIELD_DEV_IP, dev_ip))
    {
        redis_opt.Hdel(dev_id, REDIS_FIELD_PUBLIC_ADDR);
        redis_opt.Hdel(dev_id, REDIS_FIELD_PRIVATE_ADDR);
        ret = -ERROR_SET_DEVICE_ADDR_CACHE;
        goto out;
    }

out:
	CRedisConnPool::GetInstance()->ReleaseRedisContext(redis_con);

    return ret;
}

int CLogicOpt::GetDeviceAddrFromCache(string dev_id, string &public_addr, string &private_addr, string &dev_ip)
{
    int ret = 0;
    redisContext* redis_con = CRedisConnPool::GetInstance()->GetRedisContext();
    CRedisOpt redis_opt;
    redis_opt.SetRedisContext(redis_con);
    redis_opt.SelectDB(REDIS_DEVICE_INFO);

    if(!redis_opt.Hget(dev_id, REDIS_FIELD_PUBLIC_ADDR, public_addr))
    {
        ret = -ERROR_GET_DEVICE_ADDR_FROM_CACHE;
        goto out;
    }

    if(!redis_opt.Hget(dev_id, REDIS_FIELD_PRIVATE_ADDR, private_addr))
    {
        ret = -ERROR_GET_DEVICE_ADDR_FROM_CACHE;
        goto out;
    }

    if(!redis_opt.Hget(dev_id, REDIS_FIELD_DEV_IP, dev_ip))
    {
        ret = -ERROR_GET_DEVICE_ADDR_FROM_CACHE;
        goto out;
    }

out:
	CRedisConnPool::GetInstance()->ReleaseRedisContext(redis_con);

    return ret;
}

int CLogicOpt::RemoveDeviceAddrFromCache(string dev_id)
{
    redisContext* redis_con = CRedisConnPool::GetInstance()->GetRedisContext();
    CRedisOpt redis_opt;
    redis_opt.SetRedisContext(redis_con);
    redis_opt.SelectDB(REDIS_DEVICE_INFO);

    redis_opt.Hdel(dev_id, REDIS_FIELD_PUBLIC_ADDR);
    redis_opt.Hdel(dev_id, REDIS_FIELD_PRIVATE_ADDR);
    redis_opt.Hdel(dev_id, REDIS_FIELD_DEV_IP);

	CRedisConnPool::GetInstance()->ReleaseRedisContext(redis_con);

    return 0;
}

int CLogicOpt::RemoveDeviceFromCache(string dev_id)
{
    redisContext* redis_con = CRedisConnPool::GetInstance()->GetRedisContext();
    CRedisOpt redis_opt;
    redis_opt.SetRedisContext(redis_con);
    redis_opt.SelectDB(REDIS_DEVICE_INFO);

    redis_opt.Del(dev_id);

	CRedisConnPool::GetInstance()->ReleaseRedisContext(redis_con);

    return 0;
}

<commit_msg>1. 修改外部端口接收到的请求，如果请求的method除了设备端发送的消息，剩下的都认为是推送消息的回复消息<commit_after>/*
 * message_opt.cc
 *
 *  Created on: Mar 18, 2013
 *      Author: yaowei
 */

#include <sys/socket.h>
#include "logic_opt.h"
#include "defines.h"
#include "json_opt.h"
#include "redis_conn_pool.h"
#include "global_settings.h"
#include "../../public/utils.h"
#include "../../public/redis_key.h"
#include "../../public/socket_wrapper.h"
#include "../../public/message.h"
#include "../../public/error_code.h"
#include "device_alive.h"

CLogicOpt::CLogicOpt(conn* c)
{
	conn_ = c;
	result_ = 0;
    is_online_ = false;
	jsonOpt_ptr_ = new CJsonOpt;
	assert(jsonOpt_ptr_ != NULL);
}

CLogicOpt::~CLogicOpt()
{
	utils::SafeDelete(jsonOpt_ptr_);
}

void CLogicOpt::StartLogicOpt(const std::string& message)
{
    int ret = 0;
	std::string custom_msg;
    string method;

	LOG4CXX_INFO(g_logger, "CLogicOperate::StartLogicOpt" << message);

	jsonOpt_ptr_->setJsonString(message);
    if (!jsonOpt_ptr_->JsonParseCommon())
    {
		LOG4CXX_ERROR(g_logger, "CLogicOperate::StartLogicOpt:JsonParseCommon failed:" << message);
        return;
    }

    ret = jsonOpt_ptr_->GetMethod(method);
    if (ret != 0)
    {
		LOG4CXX_ERROR(g_logger, "CLogicOperate::StartLogicOpt:GetMethod failed:" << message);
        return;
    }

    if (method == METHOD_DEVICE_LOGIN)
    {
        DeviceLogin();
        goto SEND_RESPONSE;
    }
    else if (method == METHOD_KEEP_ONLINE)
    {
        DeviceBeacon();
        goto SEND_RESPONSE;
    }
    else // (method == METHOD_SET_STREAMSERVER_ADDR)
    {
        //其他的method认为是推送消息的回复消息
		LOG4CXX_ERROR(g_logger, "CLogicOpt::StartLogicOpt method is " << method);
        HandlePushMsgResp();
        goto SEND_RESPONSE;
    }

SEND_RESPONSE:
    string response_msg = utils::ReplaceString(responseToClient_, "\\r\\n", "\\\\r\\\\n");
    response_msg.append("\r\n");
    if (!SocketOperate::WriteSfd(conn_->sfd, response_msg.c_str(), response_msg.length()))
    {
        LOG4CXX_ERROR(g_logger, "SocketOperate::WriteSfd error, fd " << conn_->sfd << ", push_msg " << responseToClient_);
        ret = -ERROR_PUSH_MESSAGE;
    }

    return;
}

int CLogicOpt::DeviceLogin()
{
    int ret = 0;
    deque<int> auth_data;

	LOG4CXX_TRACE(g_logger, "CLogicOpt::DeviceLogin enter");

    ret = jsonOpt_ptr_->JsonParseLogin(dev_id_, auth_data);
    if (ret != 0)
    {
	    LOG4CXX_ERROR(g_logger, "CLogicOpt::DeviceLogin parse login error, ret is " << ret);
        goto out;
    }

    if (!conn_)
    {
        LOG4CXX_ERROR(g_logger, "DeviceLogin conn_ is NULL");
        ret = -ERROR_DEVICE_CONNECT;
        goto out;
    }

    // TODO: 认证设备的合法性

    if (!conn_->is_login)
    {
        conn_->is_login = true;
        conn_->dev_id = dev_id_;

        // 获取上线设备的ip
        struct sockaddr_in dev_addr;
        socklen_t len;
        memset(&dev_addr, 0, sizeof(struct sockaddr));
        ret = getpeername(conn_->sfd, (struct sockaddr*)&dev_addr, &len);
        if (ret != 0)
        {
	        LOG4CXX_ERROR(g_logger, "DeviceBeacon getpeername failed, errno is " << -errno);
            ret = -errno;
            goto out;
        }
        string dev_ip(inet_ntoa(dev_addr.sin_addr));

        // 更新设备在redis中的信息
        ret = CLogicOpt::SetDeviceFdCache(conn_->dev_id, conn_->sfd);
        if (ret != 0)
        {
	        LOG4CXX_ERROR(g_logger, "DeviceBeacon set fd cache failed");
            ret = -ERROR_SET_DEVICE_FD_CACHE;
            goto out;
        }

        ret = CLogicOpt::SetDeviceAddrCache(conn_->dev_id, utils::G<CGlobalSettings>().public_addr_, utils::G<CGlobalSettings>().private_addr_, dev_ip);
        if (ret != 0)
        {
	        LOG4CXX_ERROR(g_logger, "DeviceBeacon getsockname error");
            goto out;
        }

        // 通知设备上线
        time_t now;
        time(&now);
        string time_info(ctime(&now));
        CJsonOpt json_opt;
        string msg_info = json_opt.JsonJoinDeviceStateNotice(conn_->dev_id, 1, time_info);
        string url = utils::G<CGlobalSettings>().httpserver_url_;
        SendMsg send_msg(url, msg_info);
        g_http_client->SubmitMsg(send_msg);

	    LOG4CXX_TRACE(g_logger, "DeviceBeacon ok, dev_id is " << conn_->dev_id << ", sfd is " << conn_->sfd);
    }

out:
    responseToClient_ = jsonOpt_ptr_->JsonJoinLoginRes(ret);
    return ret;
}

int CLogicOpt::DeviceBeacon()
{
    int ret = 0;
    string dev_id;

	LOG4CXX_TRACE(g_logger, "CLogicOpt::DeviceBeacon enter");

    ret = jsonOpt_ptr_->JsonParseBeacon(dev_id);
    if (ret != 0)
    {
	    LOG4CXX_ERROR(g_logger, "CLogicOpt::StartLogicOpt:JsonParseBecon failed");
        goto out;
    }

    if (!conn_)
    {
	    LOG4CXX_ERROR(g_logger, "DeviceBeacon device conn_ is null");
        ret = -ERROR_DEVICE_CONNECT;
        goto out;
    }

    if (!conn_->is_login)
    {
	    LOG4CXX_ERROR(g_logger, "DeviceBeacon device conn_ is null");
        ret = -ERROR_DEVICE_NOT_LOGIN;
        goto out;
    }

    if (!conn_->is_online)
    {
        conn_->is_online = true;
    }

out:
    responseToClient_ = jsonOpt_ptr_->JsonJoinBeaconRes(ret);
    return ret;
}

int CLogicOpt::HandlePushMsgResp()
{
    int ret = 0;
    int msg_ret;
    int push_cnt = 0;
    string method;

    push_cnt = jsonOpt_ptr_->GetSendCnt();
    jsonOpt_ptr_->GetMethod(method);
    LOG4CXX_TRACE(g_logger, "handle push msg resp, method is " << method << ", push_cnt is " << push_cnt);

    JSONNode param_node;
    ret = jsonOpt_ptr_->JsonParsePushMsgResp(msg_ret, param_node);
    if (ret != 0)
    {
        msg_ret = -ERROR_PARSE_MSG;
	    LOG4CXX_ERROR(g_logger, "CLogicOpt::StartLogicOpt:HandlePushMsgResp failed");
    }

    g_wait_finish_push_msg_queue.FinishPushMsg(push_cnt, msg_ret, param_node);

    return 0;
}

int CLogicOpt::SetDeviceFdCache(string dev_id, int fd)
{
    int ret = 0;
    redisContext* redis_con = CRedisConnPool::GetInstance()->GetRedisContext();
    CRedisOpt redis_opt;
    redis_opt.SetRedisContext(redis_con);
    redis_opt.SelectDB(REDIS_DEVICE_INFO);

    if(!redis_opt.Hset(dev_id, REDIS_FIELD_FD, fd))
    {
        ret = -ERROR_SET_DEVICE_FD_CACHE;
        goto out;
    }

out:
	CRedisConnPool::GetInstance()->ReleaseRedisContext(redis_con);

    return ret;
}

int CLogicOpt::GetDeviceFdFromCache(string dev_id, int &fd)
{
    int ret = 0;
    redisContext* redis_con = CRedisConnPool::GetInstance()->GetRedisContext();
    CRedisOpt redis_opt;
    redis_opt.SetRedisContext(redis_con);
    redis_opt.SelectDB(REDIS_DEVICE_INFO);

    string fd_str;
    if(!redis_opt.Hget(dev_id, REDIS_FIELD_FD, fd_str))
    {
        ret = -ERROR_GET_DEVICE_FD_FROM_CACHE;
        goto out;
    }

    fd = atoi(fd_str.c_str());
out:
	CRedisConnPool::GetInstance()->ReleaseRedisContext(redis_con);

    return ret;
}

int CLogicOpt::RemoveDeviceFdFromCache(string dev_id)
{
    redisContext* redis_con = CRedisConnPool::GetInstance()->GetRedisContext();
    CRedisOpt redis_opt;
    redis_opt.SetRedisContext(redis_con);
    redis_opt.SelectDB(REDIS_DEVICE_INFO);

    redis_opt.Hdel(dev_id, REDIS_FIELD_FD);

	CRedisConnPool::GetInstance()->ReleaseRedisContext(redis_con);

    return 0;
}

int CLogicOpt::SetDeviceAddrCache(string dev_id, string public_addr, string private_addr, string dev_ip)
{
    int ret = 0;
    redisContext* redis_con = CRedisConnPool::GetInstance()->GetRedisContext();
    CRedisOpt redis_opt;
    redis_opt.SetRedisContext(redis_con);
    redis_opt.SelectDB(REDIS_DEVICE_INFO);

    if(!redis_opt.Hset(dev_id, REDIS_FIELD_PUBLIC_ADDR, public_addr))
    {
        ret = -ERROR_SET_DEVICE_ADDR_CACHE;
        goto out;
    }

    if (!redis_opt.Hset(dev_id, REDIS_FIELD_PRIVATE_ADDR, private_addr))
    {
        redis_opt.Hdel(dev_id, REDIS_FIELD_PUBLIC_ADDR);
        ret = -ERROR_SET_DEVICE_ADDR_CACHE;
        goto out;
    }

    if (!redis_opt.Hset(dev_id, REDIS_FIELD_DEV_IP, dev_ip))
    {
        redis_opt.Hdel(dev_id, REDIS_FIELD_PUBLIC_ADDR);
        redis_opt.Hdel(dev_id, REDIS_FIELD_PRIVATE_ADDR);
        ret = -ERROR_SET_DEVICE_ADDR_CACHE;
        goto out;
    }

out:
	CRedisConnPool::GetInstance()->ReleaseRedisContext(redis_con);

    return ret;
}

int CLogicOpt::GetDeviceAddrFromCache(string dev_id, string &public_addr, string &private_addr, string &dev_ip)
{
    int ret = 0;
    redisContext* redis_con = CRedisConnPool::GetInstance()->GetRedisContext();
    CRedisOpt redis_opt;
    redis_opt.SetRedisContext(redis_con);
    redis_opt.SelectDB(REDIS_DEVICE_INFO);

    if(!redis_opt.Hget(dev_id, REDIS_FIELD_PUBLIC_ADDR, public_addr))
    {
        ret = -ERROR_GET_DEVICE_ADDR_FROM_CACHE;
        goto out;
    }

    if(!redis_opt.Hget(dev_id, REDIS_FIELD_PRIVATE_ADDR, private_addr))
    {
        ret = -ERROR_GET_DEVICE_ADDR_FROM_CACHE;
        goto out;
    }

    if(!redis_opt.Hget(dev_id, REDIS_FIELD_DEV_IP, dev_ip))
    {
        ret = -ERROR_GET_DEVICE_ADDR_FROM_CACHE;
        goto out;
    }

out:
	CRedisConnPool::GetInstance()->ReleaseRedisContext(redis_con);

    return ret;
}

int CLogicOpt::RemoveDeviceAddrFromCache(string dev_id)
{
    redisContext* redis_con = CRedisConnPool::GetInstance()->GetRedisContext();
    CRedisOpt redis_opt;
    redis_opt.SetRedisContext(redis_con);
    redis_opt.SelectDB(REDIS_DEVICE_INFO);

    redis_opt.Hdel(dev_id, REDIS_FIELD_PUBLIC_ADDR);
    redis_opt.Hdel(dev_id, REDIS_FIELD_PRIVATE_ADDR);
    redis_opt.Hdel(dev_id, REDIS_FIELD_DEV_IP);

	CRedisConnPool::GetInstance()->ReleaseRedisContext(redis_con);

    return 0;
}

int CLogicOpt::RemoveDeviceFromCache(string dev_id)
{
    redisContext* redis_con = CRedisConnPool::GetInstance()->GetRedisContext();
    CRedisOpt redis_opt;
    redis_opt.SetRedisContext(redis_con);
    redis_opt.SelectDB(REDIS_DEVICE_INFO);

    redis_opt.Del(dev_id);

	CRedisConnPool::GetInstance()->ReleaseRedisContext(redis_con);

    return 0;
}

<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * 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 <stdio.h>
#include <iostream>
#include "OOXMLParserState.hxx"
#include "ooxmlLoggers.hxx"

namespace writerfilter {
namespace ooxml
{
/*
  class OOXMLParserState
*/

OOXMLParserState::OOXMLParserState() :
    mbInSectionGroup(false),
    mbInParagraphGroup(false),
    mbInCharacterGroup(false),
    mbLastParagraphInSection(false),
    mbForwardEvents(true),
    mnContexts(0),
    mnHandle(0),
    mpDocument(NULL)
{
}

OOXMLParserState::~OOXMLParserState()
{
}

void OOXMLParserState::setLastParagraphInSection(bool bLastParagraphInSection)
{
    mbLastParagraphInSection = bLastParagraphInSection;
}

bool OOXMLParserState::isLastParagraphInSection() const
{
    return mbLastParagraphInSection;
}

bool OOXMLParserState::isInSectionGroup() const
{
    return mbInSectionGroup;
}

void OOXMLParserState::setInSectionGroup(bool bInSectionGroup)
{
    mbInSectionGroup = bInSectionGroup;
}

bool OOXMLParserState::isInParagraphGroup() const
{
    return mbInParagraphGroup;
}

void OOXMLParserState::setInParagraphGroup(bool bInParagraphGroup)
{
    mbInParagraphGroup = bInParagraphGroup;
}

bool OOXMLParserState::isInCharacterGroup() const
{
    return mbInCharacterGroup;
}

void OOXMLParserState::setInCharacterGroup(bool bInCharacterGroup)
{
    mbInCharacterGroup = bInCharacterGroup;
}

void OOXMLParserState::setForwardEvents(bool bForwardEvents)
{
    mbForwardEvents = bForwardEvents;
}

bool OOXMLParserState::isForwardEvents() const
{
    return mbForwardEvents;
}

const string OOXMLParserState::getHandle() const
{
    char sBuffer[256];

    snprintf(sBuffer, sizeof(sBuffer), "%d", mnHandle);

    return sBuffer;
}

void OOXMLParserState::setHandle()
{
    mnHandle = mnContexts;
}

void OOXMLParserState::setDocument(OOXMLDocument * pDocument)
{
    mpDocument = pDocument;
}

OOXMLDocument * OOXMLParserState::getDocument() const
{
    return mpDocument;
}

void OOXMLParserState::setXNoteId(const sal_Int32 nId)
{
    mpDocument->setXNoteId(nId);
}

sal_Int32 OOXMLParserState::getXNoteId() const
{
    return mpDocument->getXNoteId();
}

const ::rtl::OUString & OOXMLParserState::getTarget() const
{
    return mpDocument->getTarget();
}

void OOXMLParserState::resolveCharacterProperties(Stream & rStream)
{
    if (mpCharacterProps.get() != NULL)
    {
#ifdef DEBUG_PROPERTIES
        debug_logger->startElement("resolveCharacterProperties");
#endif

        rStream.props(mpCharacterProps);
        mpCharacterProps.reset(new OOXMLPropertySetImpl());

#ifdef DEBUG_PROPERTIES
        debug_logger->endElement();
#endif
    }
}

void OOXMLParserState::setCharacterProperties
(OOXMLPropertySet::Pointer_t pProps)
{
    if (mpCharacterProps.get() == NULL)
        mpCharacterProps = pProps;
    else
        mpCharacterProps->add(pProps);
}

void OOXMLParserState::setCellProperties
(OOXMLPropertySet::Pointer_t pProps)
{
    if (mCellProps.size() > 0)
    {
        OOXMLPropertySet::Pointer_t & rCellProps = mCellProps.top();

        if (rCellProps.get() == NULL)
            rCellProps = pProps;
        else
            rCellProps->add(pProps);
    }
}

void OOXMLParserState::setRowProperties
(OOXMLPropertySet::Pointer_t pProps)
{
    if (mRowProps.size() > 0)
    {
        OOXMLPropertySet::Pointer_t & rRowProps = mRowProps.top();

        if (rRowProps.get() == NULL)
            rRowProps = pProps;
        else
            rRowProps->add(pProps);
    }
}

void OOXMLParserState::resolveCellProperties(Stream & rStream)
{
    if (mCellProps.size() > 0)
    {
        OOXMLPropertySet::Pointer_t & rCellProps = mCellProps.top();

        if (rCellProps.get() != NULL)
        {
            rStream.props(rCellProps);
            rCellProps.reset(new OOXMLPropertySetImpl());
        }
    }
}

void OOXMLParserState::resolveRowProperties(Stream & rStream)
{
    if (mRowProps.size() > 0)
    {
        OOXMLPropertySet::Pointer_t & rRowProps = mRowProps.top();

        if (rRowProps.get() != NULL)
        {
            rStream.props(rRowProps);
            rRowProps.reset(new OOXMLPropertySetImpl());
        }
    }
}

void OOXMLParserState::resolveTableProperties(Stream & rStream)
{
    if (mTableProps.size() > 0)
    {
        OOXMLPropertySet::Pointer_t & rTableProps = mTableProps.top();

        if (rTableProps.get() != NULL)
        {
            rStream.props(rTableProps);
            rTableProps.reset(new OOXMLPropertySetImpl());
        }
    }
}

void OOXMLParserState::setTableProperties
(OOXMLPropertySet::Pointer_t pProps)
{
    if (mTableProps.size() > 0)
    {
        OOXMLPropertySet::Pointer_t & rTableProps = mTableProps.top();
        if (rTableProps.get() == NULL)
            rTableProps = pProps;
        else
            rTableProps->add(pProps);
    }
}

void OOXMLParserState::startTable()
{
    OOXMLPropertySet::Pointer_t pCellProps;
    OOXMLPropertySet::Pointer_t pRowProps;
    OOXMLPropertySet::Pointer_t pTableProps;

    mCellProps.push(pCellProps);
    mRowProps.push(pRowProps);
    mTableProps.push(pTableProps);
}

void OOXMLParserState::endTable()
{
    mCellProps.pop();
    mRowProps.pop();
    mTableProps.pop();
}

void OOXMLParserState::incContextCount()
{
    mnContexts++;
}

#if OSL_DEBUG_LEVEL > 1
unsigned int OOXMLParserState::getContextCount() const
{
    return mnContexts;
}

void OOXMLParserState::dumpXml( const TagLogger::Pointer_t& pLogger )
{
    pLogger->startElement("parserstate");

    string sTmp;

    if (isInSectionGroup())
        sTmp += "s";
    else
        sTmp += "-";

    if (isInParagraphGroup())
        sTmp += "p";
    else
        sTmp += "-";

    if (isInCharacterGroup())
        sTmp += "c";
    else
        sTmp += "-";

    if (isForwardEvents())
        sTmp += "f";
    else
        sTmp += "-";

    pLogger->attribute("state", sTmp);
    pLogger->attribute("XNoteId",
                  OUStringToOString(getXNoteId(),
                                    RTL_TEXTENCODING_ASCII_US).getStr());
    if (mpCharacterProps != OOXMLPropertySet::Pointer_t())
        pLogger->chars(mpCharacterProps->toString());

    pLogger->endElement();
 }

XPathLogger & OOXMLParserState::getXPathLogger()
{
    return m_xPathLogger;
}
#endif

}}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>writerfilter: Fixed debug build<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * 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 <stdio.h>
#include <iostream>
#include "OOXMLParserState.hxx"
#include "ooxmlLoggers.hxx"

namespace writerfilter {
namespace ooxml
{
/*
  class OOXMLParserState
*/

OOXMLParserState::OOXMLParserState() :
    mbInSectionGroup(false),
    mbInParagraphGroup(false),
    mbInCharacterGroup(false),
    mbLastParagraphInSection(false),
    mbForwardEvents(true),
    mnContexts(0),
    mnHandle(0),
    mpDocument(NULL)
{
}

OOXMLParserState::~OOXMLParserState()
{
}

void OOXMLParserState::setLastParagraphInSection(bool bLastParagraphInSection)
{
    mbLastParagraphInSection = bLastParagraphInSection;
}

bool OOXMLParserState::isLastParagraphInSection() const
{
    return mbLastParagraphInSection;
}

bool OOXMLParserState::isInSectionGroup() const
{
    return mbInSectionGroup;
}

void OOXMLParserState::setInSectionGroup(bool bInSectionGroup)
{
    mbInSectionGroup = bInSectionGroup;
}

bool OOXMLParserState::isInParagraphGroup() const
{
    return mbInParagraphGroup;
}

void OOXMLParserState::setInParagraphGroup(bool bInParagraphGroup)
{
    mbInParagraphGroup = bInParagraphGroup;
}

bool OOXMLParserState::isInCharacterGroup() const
{
    return mbInCharacterGroup;
}

void OOXMLParserState::setInCharacterGroup(bool bInCharacterGroup)
{
    mbInCharacterGroup = bInCharacterGroup;
}

void OOXMLParserState::setForwardEvents(bool bForwardEvents)
{
    mbForwardEvents = bForwardEvents;
}

bool OOXMLParserState::isForwardEvents() const
{
    return mbForwardEvents;
}

const string OOXMLParserState::getHandle() const
{
    char sBuffer[256];

    snprintf(sBuffer, sizeof(sBuffer), "%d", mnHandle);

    return sBuffer;
}

void OOXMLParserState::setHandle()
{
    mnHandle = mnContexts;
}

void OOXMLParserState::setDocument(OOXMLDocument * pDocument)
{
    mpDocument = pDocument;
}

OOXMLDocument * OOXMLParserState::getDocument() const
{
    return mpDocument;
}

void OOXMLParserState::setXNoteId(const sal_Int32 nId)
{
    mpDocument->setXNoteId(nId);
}

sal_Int32 OOXMLParserState::getXNoteId() const
{
    return mpDocument->getXNoteId();
}

const ::rtl::OUString & OOXMLParserState::getTarget() const
{
    return mpDocument->getTarget();
}

void OOXMLParserState::resolveCharacterProperties(Stream & rStream)
{
    if (mpCharacterProps.get() != NULL)
    {
#ifdef DEBUG_PROPERTIES
        debug_logger->startElement("resolveCharacterProperties");
#endif

        rStream.props(mpCharacterProps);
        mpCharacterProps.reset(new OOXMLPropertySetImpl());

#ifdef DEBUG_PROPERTIES
        debug_logger->endElement();
#endif
    }
}

void OOXMLParserState::setCharacterProperties
(OOXMLPropertySet::Pointer_t pProps)
{
    if (mpCharacterProps.get() == NULL)
        mpCharacterProps = pProps;
    else
        mpCharacterProps->add(pProps);
}

void OOXMLParserState::setCellProperties
(OOXMLPropertySet::Pointer_t pProps)
{
    if (mCellProps.size() > 0)
    {
        OOXMLPropertySet::Pointer_t & rCellProps = mCellProps.top();

        if (rCellProps.get() == NULL)
            rCellProps = pProps;
        else
            rCellProps->add(pProps);
    }
}

void OOXMLParserState::setRowProperties
(OOXMLPropertySet::Pointer_t pProps)
{
    if (mRowProps.size() > 0)
    {
        OOXMLPropertySet::Pointer_t & rRowProps = mRowProps.top();

        if (rRowProps.get() == NULL)
            rRowProps = pProps;
        else
            rRowProps->add(pProps);
    }
}

void OOXMLParserState::resolveCellProperties(Stream & rStream)
{
    if (mCellProps.size() > 0)
    {
        OOXMLPropertySet::Pointer_t & rCellProps = mCellProps.top();

        if (rCellProps.get() != NULL)
        {
            rStream.props(rCellProps);
            rCellProps.reset(new OOXMLPropertySetImpl());
        }
    }
}

void OOXMLParserState::resolveRowProperties(Stream & rStream)
{
    if (mRowProps.size() > 0)
    {
        OOXMLPropertySet::Pointer_t & rRowProps = mRowProps.top();

        if (rRowProps.get() != NULL)
        {
            rStream.props(rRowProps);
            rRowProps.reset(new OOXMLPropertySetImpl());
        }
    }
}

void OOXMLParserState::resolveTableProperties(Stream & rStream)
{
    if (mTableProps.size() > 0)
    {
        OOXMLPropertySet::Pointer_t & rTableProps = mTableProps.top();

        if (rTableProps.get() != NULL)
        {
            rStream.props(rTableProps);
            rTableProps.reset(new OOXMLPropertySetImpl());
        }
    }
}

void OOXMLParserState::setTableProperties
(OOXMLPropertySet::Pointer_t pProps)
{
    if (mTableProps.size() > 0)
    {
        OOXMLPropertySet::Pointer_t & rTableProps = mTableProps.top();
        if (rTableProps.get() == NULL)
            rTableProps = pProps;
        else
            rTableProps->add(pProps);
    }
}

void OOXMLParserState::startTable()
{
    OOXMLPropertySet::Pointer_t pCellProps;
    OOXMLPropertySet::Pointer_t pRowProps;
    OOXMLPropertySet::Pointer_t pTableProps;

    mCellProps.push(pCellProps);
    mRowProps.push(pRowProps);
    mTableProps.push(pTableProps);
}

void OOXMLParserState::endTable()
{
    mCellProps.pop();
    mRowProps.pop();
    mTableProps.pop();
}

void OOXMLParserState::incContextCount()
{
    mnContexts++;
}

#if OSL_DEBUG_LEVEL > 1
unsigned int OOXMLParserState::getContextCount() const
{
    return mnContexts;
}

void OOXMLParserState::dumpXml( const TagLogger::Pointer_t& pLogger )
{
    pLogger->startElement("parserstate");

    string sTmp;

    if (isInSectionGroup())
        sTmp += "s";
    else
        sTmp += "-";

    if (isInParagraphGroup())
        sTmp += "p";
    else
        sTmp += "-";

    if (isInCharacterGroup())
        sTmp += "c";
    else
        sTmp += "-";

    if (isForwardEvents())
        sTmp += "f";
    else
        sTmp += "-";

    pLogger->attribute("state", sTmp);
    pLogger->attribute("XNoteId", getXNoteId() );
    if (mpCharacterProps != OOXMLPropertySet::Pointer_t())
        pLogger->chars(mpCharacterProps->toString());

    pLogger->endElement();
 }

XPathLogger & OOXMLParserState::getXPathLogger()
{
    return m_xPathLogger;
}
#endif

}}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>/* Copyright (c) 2015 Connectal Project
 *
 * 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 <stdio.h>
#include <sys/mman.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>

#include "dmaManager.h"
#include "DmaIndication.h"
#include "DmaRequest.h"

class DmaIndication;
DmaManager *dma;
static int proxyNames[] = { IfcNames_DmaRequestS2H0, IfcNames_DmaRequestS2H1 };
static int wrapperNames[] = { IfcNames_DmaIndicationH2S0, IfcNames_DmaIndicationH2S1 };

pthread_t threads[2];

class DmaBuffer {
    DmaManager *mgr;
    const int size;
    int fd;
    char *buf;
    int ref;
public:
    // Allocates a portal memory object of specified size and maps it into user process
    DmaBuffer(DmaManager *mgr, int size) : mgr(mgr), size(size), ref(-1) {
	fd = portalAlloc(size, 1);
	buf = (char *)portalMmap(fd, size);
    }
    // Dereferences and deallocates the portal memory object
    // if destructor is not called, the object is automatically
    // unreferenced and freed when the process exits
    ~DmaBuffer() {
	mgr->dereference(fd);
	portalMunmap(buf, size);
	close(fd);
    }
    // returns the address of the mapped buffer
    char *buffer() {
	return buf;
    }
    // returns the reference to the object
    //
    // Sends the address translation table to hardware MMU if necessary.
    int reference() {
	if (ref == -1)
	    ref = mgr->reference(fd);
	return ref;
    }
    // Removes the address translation table from the hardware MMU
    void dereference() {
	if (ref != -1)
	    mgr->dereference(ref);
	ref = -1;
    }
};

// ChannelWorker processes one channel
class ChannelWorker {
  PortalPoller *poller;
  DmaIndication *dmaIndication;
  DmaRequestProxy *dmaRequest;
  int channel;
  DmaBuffer *buffers[4];
  int size;
  volatile int waitCount;
public:
    ChannelWorker(int channel);
    void run();
    void post() { waitCount--; }
    static void *threadfn(void *c);
};

class DmaIndication : public DmaIndicationWrapper
{
    ChannelWorker *channel;
    sem_t sem;
public:
    DmaIndication(unsigned int id, PortalPoller *poller = 0, ChannelWorker *channel = 0)
	: DmaIndicationWrapper(id, poller), channel(channel) {
	sem_init(&sem, 0, 0);
    }

    void readDone ( uint32_t sglId, uint32_t base, const uint8_t tag ) {
    fprintf(stderr, "[%s:%d] sglId=%d base=%08x tag=%d\n", __FUNCTION__, __LINE__, sglId, base, tag);
	sem_post(&sem);
	if (channel)
	    channel->post();
    }
    void writeDone ( uint32_t sglId, uint32_t base, uint8_t tag ) {
    fprintf(stderr, "[%s:%d] sglId=%d base=%08x tag=%d\n", __FUNCTION__, __LINE__, sglId, base, tag);
	sem_post(&sem);
	if (channel)
	    channel->post();
    }
    void wait() {
	sem_wait(&sem);
    }
};

ChannelWorker::ChannelWorker(int channel)
  : poller(new PortalPoller(0)), channel(channel), size(1024*1024), waitCount(0)
{
    dmaRequest    = new DmaRequestProxy(proxyNames[channel], poller);
    dmaIndication = new DmaIndication(wrapperNames[channel], poller, this);
    fprintf(stderr, "[%s:%d] channel %d dma mgr %p allocating buffers\n", __FUNCTION__, __LINE__, channel, dma);
    for (int i = 0; i < 4; i++) {
	buffers[i] = new DmaBuffer(dma, size);
    }
  }

void ChannelWorker::run()
{
    fprintf(stderr, "[%s:%d] channel %d requesting first dma\n", __FUNCTION__, __LINE__, channel);
    dmaRequest->read(buffers[0]->reference(), 0, size/2, 0);
    waitCount++;

    dmaRequest->write(buffers[1]->reference(), 0, size/2, 1);
    waitCount++;

    fprintf(stderr, "[%s:%d] channel %d requesting second dma\n", __FUNCTION__, __LINE__, channel);
    dmaRequest->read(buffers[2]->reference(), size/2, size/2, 2);
    waitCount++;

    dmaRequest->write(buffers[3]->reference(), size/2, size/2, 3);
    waitCount++;

    fprintf(stderr, "[%s:%d] channel %d waiting for responses\n", __FUNCTION__, __LINE__, channel);
    // poll
    while (waitCount > 0) {
	poller->event();
    }
}

void *ChannelWorker::threadfn(void *c)
{
    ChannelWorker *channelp = (ChannelWorker *)c;
    channelp->run();
    return 0;
}

int main(int argc, const char **argv)
{
    fprintf(stderr, "[%s:%d] calling platformInit\n", __FUNCTION__, __LINE__);
    dma = platformInit();
    fprintf(stderr, "[%s:%d] creating proxy and wrapper\n", __FUNCTION__, __LINE__);

    for (int i = 0; i < 2; i++) {
      ChannelWorker *channel = new ChannelWorker(i);
      pthread_create(&threads[i], 0, channel->threadfn, channel);
    }

    // wait for threads to exit
    for (int i = 0; i < 2; i++) {
      void *ret;
      pthread_join(threads[i], &ret);
      fprintf(stderr, "thread exited ret=%p\n", ret);
    }
    return 0;
}
<commit_msg>added performance measurement<commit_after>/* Copyright (c) 2015 Connectal Project
 *
 * 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 <stdio.h>
#include <sys/mman.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>

#include "dmaManager.h"
#include "DmaIndication.h"
#include "DmaRequest.h"

class DmaIndication;
DmaManager *dma;
static int proxyNames[] = { IfcNames_DmaRequestS2H0, IfcNames_DmaRequestS2H1 };
static int wrapperNames[] = { IfcNames_DmaIndicationH2S0, IfcNames_DmaIndicationH2S1 };

pthread_t threads[2];

class DmaBuffer {
    DmaManager *mgr;
    const int size;
    int fd;
    char *buf;
    int ref;
public:
    // Allocates a portal memory object of specified size and maps it into user process
    DmaBuffer(DmaManager *mgr, int size) : mgr(mgr), size(size), ref(-1) {
	fd = portalAlloc(size, 1);
	buf = (char *)portalMmap(fd, size);
    }
    // Dereferences and deallocates the portal memory object
    // if destructor is not called, the object is automatically
    // unreferenced and freed when the process exits
    ~DmaBuffer() {
	mgr->dereference(fd);
	portalMunmap(buf, size);
	close(fd);
    }
    // returns the address of the mapped buffer
    char *buffer() {
	return buf;
    }
    // returns the reference to the object
    //
    // Sends the address translation table to hardware MMU if necessary.
    int reference() {
	if (ref == -1)
	    ref = mgr->reference(fd);
	return ref;
    }
    // Removes the address translation table from the hardware MMU
    void dereference() {
	if (ref != -1)
	    mgr->dereference(ref);
	ref = -1;
    }
};

// ChannelWorker processes one channel
class ChannelWorker {
  PortalPoller *poller;
  DmaIndication *dmaIndication;
  DmaRequestProxy *dmaRequest;
  int channel;
  DmaBuffer *buffers[4];
  int size;
  volatile int waitCount;
public:
    ChannelWorker(int channel);
    void run();
    void post() { waitCount--; }
    static void *threadfn(void *c);
};

class DmaIndication : public DmaIndicationWrapper
{
    ChannelWorker *channel;
    sem_t sem;
public:
    DmaIndication(unsigned int id, PortalPoller *poller = 0, ChannelWorker *channel = 0)
	: DmaIndicationWrapper(id, poller), channel(channel) {
	sem_init(&sem, 0, 0);
    }

    void readDone ( uint32_t sglId, uint32_t base, const uint8_t tag ) {
    fprintf(stderr, "[%s:%d] sglId=%d base=%08x tag=%d\n", __FUNCTION__, __LINE__, sglId, base, tag);
	sem_post(&sem);
	if (channel)
	    channel->post();
    }
    void writeDone ( uint32_t sglId, uint32_t base, uint8_t tag ) {
    fprintf(stderr, "[%s:%d] sglId=%d base=%08x tag=%d\n", __FUNCTION__, __LINE__, sglId, base, tag);
	sem_post(&sem);
	if (channel)
	    channel->post();
    }
    void wait() {
	sem_wait(&sem);
    }
};

ChannelWorker::ChannelWorker(int channel)
  : poller(new PortalPoller(0)), channel(channel), size(8*1024*1024), waitCount(0)
{
    dmaRequest    = new DmaRequestProxy(proxyNames[channel], poller);
    dmaIndication = new DmaIndication(wrapperNames[channel], poller, this);
    fprintf(stderr, "[%s:%d] channel %d dma mgr %p allocating buffers\n", __FUNCTION__, __LINE__, channel, dma);
    for (int i = 0; i < 4; i++) {
	buffers[i] = new DmaBuffer(dma, size);
    }
  }

volatile int started;
void ChannelWorker::run()
{
    while (!started) {
	// wait for other threads to be ready
    }

    fprintf(stderr, "[%s:%d] channel %d requesting first dma\n", __FUNCTION__, __LINE__, channel);
    dmaRequest->read(buffers[0]->reference(), 0, size/2, 0);
    waitCount++;

    dmaRequest->write(buffers[1]->reference(), 0, size/2, 1);
    waitCount++;

    fprintf(stderr, "[%s:%d] channel %d requesting second dma\n", __FUNCTION__, __LINE__, channel);
    dmaRequest->read(buffers[2]->reference(), size/2, size/2, 2);
    waitCount++;

    dmaRequest->write(buffers[3]->reference(), size/2, size/2, 3);
    waitCount++;

    fprintf(stderr, "[%s:%d] channel %d waiting for responses\n", __FUNCTION__, __LINE__, channel);
    // poll
    while (waitCount > 0) {
	poller->event();
    }
}

void *ChannelWorker::threadfn(void *c)
{
    ChannelWorker *channelp = (ChannelWorker *)c;
    channelp->run();
    return 0;
}

int main(int argc, const char **argv)
{
    fprintf(stderr, "[%s:%d] calling platformInit\n", __FUNCTION__, __LINE__);
    dma = platformInit();
    fprintf(stderr, "[%s:%d] creating proxy and wrapper\n", __FUNCTION__, __LINE__);

    for (int i = 0; i < 2; i++) {
      ChannelWorker *channel = new ChannelWorker(i);
      pthread_create(&threads[i], 0, channel->threadfn, channel);
    }
    portalTimerStart(0);
    started = 1;
    // wait for threads to exit
    for (int i = 0; i < 2; i++) {
      void *ret;
      pthread_join(threads[i], &ret);
      fprintf(stderr, "thread exited ret=%p\n", ret);
    }
    platformStatistics();
    return 0;
}
<|endoftext|>


<commit_before>/*
MIT License
Copyright (c) 2017 Arlen Keshabyan (arlen.albert@gmail.com)
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 <iostream>
#include "strings.hpp"
#include "string_id.hpp"
#include "platform_utilities.hpp"

int main()
{
    nstd::platform::utilities::scoped_console_utf8 set_console_utf8;

    using namespace std::string_literals;
    using namespace nstd::str;
    using namespace nstd::str::sid::literals;

    std::u16string u16str(trim(u"    Hello World!      "));

    std::cout << u8"Всем привет :)" << std::endl;
    std::cout << std::string(trim("    Hello World!      ")) << std::endl;
    std::wcout << trim(L"    Hello World!      ") << std::endl;
    std::cout << from_utf16_to_utf8(u16str) << std::endl;
    std::cout << from_utf32_to_utf8(std::u32string(trim(U"    Hello World!      "))) << std::endl;

    std::cout << from_utf32_to_utf8(replace_all(U"good strings (UTF-32)"s, U"o"s, U"OO"s)) << std::endl;
    std::cout << replace_regex("good strings (string)"s, "o"s, "[$&]"s) << std::endl;
    std::wcout << replace_regex(L"good strings (wstring)"s, L"o"s, L"[$&]"s) << std::endl;

    auto str_container = { 1, 2, 3 };
    std::wcout << L"{" << join(str_container, L"}{"s) << L"}" << std::endl;

    auto str_to_split { L"let's  split       every  word   "s };

    std::wcout << "to split: '" << str_to_split << "'" << std::endl;

    auto splitted { split_regex(str_to_split, LR"(\s+)"s) };

    for (auto &&str : splitted) std::wcout << str << std::endl;

    std::wcout << "joined: '" << replace_all(join(splitted, L" "s), L"split"s, L"join"s) << "'" << std::endl;

    std::cout << "Is empty or white space: " << boolalpha[is_empty_or_ws(""s)] << std::endl;
    std::cout << "Is empty or white space: " << boolalpha[is_empty_or_ws(std::wstring{})] << std::endl;
    std::cout << "Is empty or white space: " << boolalpha[is_empty_or_ws("   \n\t      "s)] << std::endl;
    std::cout << "Is empty or white space: " << boolalpha[is_empty_or_ws(L"   \n\t      "s)] << std::endl;
    std::cout << "Is empty or white space: " << boolalpha[is_empty_or_ws("   \n\t  ABC  "s)] << std::endl;
    std::cout << "Is empty or white space: " << boolalpha[is_empty_or_ws(L"   \n\t ABC  "s)] << std::endl;

    auto nr { 3 };
    auto s { "'a const char array'" };
    auto true_val { true };
    std::cout << compose_string("\n", "The value is ", nr, " and another value is ", 8, "; string value is:\t", s, ";\nmax long double precision: ", std::numeric_limits<long double>::max_digits10,
                                            "; double: ", numeric_to_string(123.56789012L, std::numeric_limits<long double>::max_digits10),
                                            "\ninfinity: ", numeric_to_string(-std::numeric_limits<double>::infinity()), "\n", "\n", boolalpha[true_val], ", ",
                                            boolalpha[false]) << std::endl;

    std::cout << std::setprecision(std::numeric_limits<long double>::max_digits10) << wstring_to_numeric<long double>(L"123.56789012") << std::endl;

    // create database to store the strings in
    // it must stay valid as long as each string_id using it
    sid::default_database database;

    //=== string_id usage ===//
    // create an id
    sid::string_id sid("Test0815", database);
    std::cout << "Hash code " << sid.hash_code() << " belongs to string \"" << sid.string() << "\"\n";
    // Output (Database supports retrieving): Hash code 16741300784925887095 belongs to string "Test0815"
    // Output (Database doesn't): Hash code 16741300784925887095 belongs to string "string_id database disabled"

    sid::string_id a("Hello", database), b("World", database);

    // compare two ids
    std::cout << std::boolalpha << (a == b) << '\n';
    // Output: false

    // compare id with constant
    std::cout << (a == "Hello"_id) << '\n';
    // Output: true

    // literal is compile-time
    switch (b.hash_code())
    {
    case "Hello"_id:
        std::cout << "Hello\n";
        break;
    case "world"_id: // case-sensitive
        std::cout << "world\n";
        break;
    case "World"_id:
        std::cout << "World\n";
        break;
    }

    //=== generation ===//
    // the prefix for all generated ids
    sid::string_id prefix("entity-", database);
    try
    {
        // a generator type appending 8 random characters to the prefix
        // it uses the std::mt19937 generator for the actual generation
        typedef sid::random_generator<std::mt19937, 8> generator_t;
        // create a generator, seed the random number generator with the current time
        generator_t generator(prefix, std::mt19937(std::int_fast32_t(std::time(nullptr))));

        std::vector<sid::string_id> ids;
        for (auto i = 0; i != 10; ++i)
            // generate new identifier
            // it is guaranteed unique and will be stored in the database of the prefix
            ids.push_back(generator());

        // print the name of all the ids
        for (auto &id : ids)
            std::cout << id.string() << '\n';
        // possible generated name: entity-jXRnZAVG
    }
    catch (sid::generation_error &ex)
    {
        // the generator was unable to generate a new unique identifier (very unlikely)
        std::cerr << "[ERROR] " << ex.what() << '\n';
    }

    try
    {
        // a generator appending an increasing number to the prefix
        typedef sid::counter_generator generator_t;

        // create a generator starting with 0, each number will be 4 digits long
        generator_t generator(prefix, 0, 4);

        std::vector<sid::string_id> ids;
        for (auto i = 0; i != 10; ++i)
            // generate new identifier
            // it is guaranteed unique and will be stored in the database of the prefix
            ids.push_back(generator());

        // print the name of all the ids
        for (auto &id : ids)
            std::cout << id.string() << '\n';
        // possible generated name: entity-0006
    }
    catch (sid::generation_error &ex)
    {
        // the generator was unable to generate a new unique identifier (very unlikely)
        std::cerr << "[ERROR] " << ex.what() << '\n';
    }

    std::cout << "exitting..." << std::endl;

    return 0;
}
<commit_msg>u8 output fixed<commit_after>/*
MIT License
Copyright (c) 2017 Arlen Keshabyan (arlen.albert@gmail.com)
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 <iostream>
#include "strings.hpp"
#include "string_id.hpp"
#include "platform_utilities.hpp"

int main()
{
    nstd::platform::utilities::scoped_console_utf8 set_console_utf8;

    using namespace std::string_literals;
    using namespace nstd::str;
    using namespace nstd::str::sid::literals;

    auto u8_to_str = [](const std::u8string &str) { return std::string(std::begin(str), std::end(str)); };

    std::u16string u16str(trim(u"    Hello World!      "));

    std::cout << u8"Всем привет :)" << std::endl;
    std::cout << trim("    Hello World!      ") << std::endl;
    std::wcout << trim(L"    Hello World!      ") << std::endl;
    std::cout << u8_to_str(from_utf16_to_utf8(u16str)) << std::endl;
    std::cout << u8_to_str(from_utf32_to_utf8(std::u32string(trim(U"    Hello World!      ")))) << std::endl;

    std::cout << u8_to_str(from_utf32_to_utf8(replace_all(U"good strings (UTF-32)"s, U"o"s, U"OO"s))) << std::endl;
    std::cout << replace_regex("good strings (string)"s, "o"s, "[$&]"s) << std::endl;
    std::wcout << replace_regex(L"good strings (wstring)"s, L"o"s, L"[$&]"s) << std::endl;

    auto str_container = { 1, 2, 3 };
    std::wcout << L"{" << join(str_container, L"}{"s) << L"}" << std::endl;

    auto str_to_split { L"let's  split       every  word   "s };

    std::wcout << "to split: '" << str_to_split << "'" << std::endl;

    auto splitted { split_regex(str_to_split, LR"(\s+)"s) };

    for (auto &&str : splitted) std::wcout << str << std::endl;

    std::wcout << "joined: '" << replace_all(join(splitted, L" "s), L"split"s, L"join"s) << "'" << std::endl;

    std::cout << "Is empty or white space: " << boolalpha[is_empty_or_ws(""s)] << std::endl;
    std::cout << "Is empty or white space: " << boolalpha[is_empty_or_ws(std::wstring{})] << std::endl;
    std::cout << "Is empty or white space: " << boolalpha[is_empty_or_ws("   \n\t      "s)] << std::endl;
    std::cout << "Is empty or white space: " << boolalpha[is_empty_or_ws(L"   \n\t      "s)] << std::endl;
    std::cout << "Is empty or white space: " << boolalpha[is_empty_or_ws("   \n\t  ABC  "s)] << std::endl;
    std::cout << "Is empty or white space: " << boolalpha[is_empty_or_ws(L"   \n\t ABC  "s)] << std::endl;

    auto nr { 3 };
    auto s { "'a const char array'" };
    auto true_val { true };
    std::cout << compose_string("\n", "The value is ", nr, " and another value is ", 8, "; string value is:\t", s, ";\nmax long double precision: ", std::numeric_limits<long double>::max_digits10,
                                            "; double: ", numeric_to_string(123.56789012L, std::numeric_limits<long double>::max_digits10),
                                            "\ninfinity: ", numeric_to_string(-std::numeric_limits<double>::infinity()), "\n", "\n", boolalpha[true_val], ", ",
                                            boolalpha[false]) << std::endl;

    std::cout << std::setprecision(std::numeric_limits<long double>::max_digits10) << wstring_to_numeric<long double>(L"123.56789012") << std::endl;

    // create database to store the strings in
    // it must stay valid as long as each string_id using it
    sid::default_database database;

    //=== string_id usage ===//
    // create an id
    sid::string_id sid("Test0815", database);
    std::cout << "Hash code " << sid.hash_code() << " belongs to string \"" << sid.string() << "\"\n";
    // Output (Database supports retrieving): Hash code 16741300784925887095 belongs to string "Test0815"
    // Output (Database doesn't): Hash code 16741300784925887095 belongs to string "string_id database disabled"

    sid::string_id a("Hello", database), b("World", database);

    // compare two ids
    std::cout << std::boolalpha << (a == b) << '\n';
    // Output: false

    // compare id with constant
    std::cout << (a == "Hello"_id) << '\n';
    // Output: true

    // literal is compile-time
    switch (b.hash_code())
    {
    case "Hello"_id:
        std::cout << "Hello\n";
        break;
    case "world"_id: // case-sensitive
        std::cout << "world\n";
        break;
    case "World"_id:
        std::cout << "World\n";
        break;
    }

    //=== generation ===//
    // the prefix for all generated ids
    sid::string_id prefix("entity-", database);
    try
    {
        // a generator type appending 8 random characters to the prefix
        // it uses the std::mt19937 generator for the actual generation
        typedef sid::random_generator<std::mt19937, 8> generator_t;
        // create a generator, seed the random number generator with the current time
        generator_t generator(prefix, std::mt19937(std::int_fast32_t(std::time(nullptr))));

        std::vector<sid::string_id> ids;
        for (auto i = 0; i != 10; ++i)
            // generate new identifier
            // it is guaranteed unique and will be stored in the database of the prefix
            ids.push_back(generator());

        // print the name of all the ids
        for (auto &id : ids)
            std::cout << id.string() << '\n';
        // possible generated name: entity-jXRnZAVG
    }
    catch (sid::generation_error &ex)
    {
        // the generator was unable to generate a new unique identifier (very unlikely)
        std::cerr << "[ERROR] " << ex.what() << '\n';
    }

    try
    {
        // a generator appending an increasing number to the prefix
        typedef sid::counter_generator generator_t;

        // create a generator starting with 0, each number will be 4 digits long
        generator_t generator(prefix, 0, 4);

        std::vector<sid::string_id> ids;
        for (auto i = 0; i != 10; ++i)
            // generate new identifier
            // it is guaranteed unique and will be stored in the database of the prefix
            ids.push_back(generator());

        // print the name of all the ids
        for (auto &id : ids)
            std::cout << id.string() << '\n';
        // possible generated name: entity-0006
    }
    catch (sid::generation_error &ex)
    {
        // the generator was unable to generate a new unique identifier (very unlikely)
        std::cerr << "[ERROR] " << ex.what() << '\n';
    }

    std::cout << "exitting..." << std::endl;

    return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: MultiPropertySetHelper.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2003-12-01 16:22:49 $
 *
 *  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 _XMLOFF_MULTIPROPERTYSETHELPER_HXX
#include "MultiPropertySetHelper.hxx"
#endif

#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSETINFO_HPP_
#include <com/sun/star/beans/XPropertySetInfo.hpp>
#endif

#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif

#ifndef _COM_SUN_STAR_BEANS_XMULTIPROPERTYSET_HPP_
#include <com/sun/star/beans/XMultiPropertySet.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif

#ifndef _COMPHELPER_STLTYPES_HXX_
#include <comphelper/stl_types.hxx>
#endif

// STL includes
#include <algorithm>

using ::com::sun::star::beans::XMultiPropertySet;
using ::com::sun::star::beans::XPropertySet;
using ::com::sun::star::beans::XPropertySetInfo;
using ::com::sun::star::lang::XServiceInfo;
using ::com::sun::star::uno::Any;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Sequence;
using ::com::sun::star::uno::UNO_QUERY;
using ::comphelper::UStringLess;
using ::rtl::OUString;
using ::std::sort;

MultiPropertySetHelper::MultiPropertySetHelper(
    const sal_Char** pNames ) :
        pPropertyNames( NULL ),
        nLength( 0 ),
        aPropertySequence(),
        pSequenceIndex( NULL ),
        aValues(),
        pValues( NULL )
{
    // first count the elements
    for( const sal_Char** pPtr = pNames; *pPtr != NULL; pPtr++ )
        nLength++;

    // allocate array and create strings
    pPropertyNames = new OUString[nLength];
    for( sal_Int16 i = 0; i < nLength; i++ )
        pPropertyNames[i] = OUString::createFromAscii( pNames[i] );
}

MultiPropertySetHelper::MultiPropertySetHelper(
    const OUString* pNames ) :
        pPropertyNames( NULL ),
        nLength( 0 ),
        aPropertySequence(),
        pSequenceIndex( NULL ),
        aValues(),
        pValues( NULL )
{
    // count elements
    for( const OUString* pPtr = pNames; pPtr != NULL; pPtr++ )
        nLength++;

    // allocate array and assign strings
    pPropertyNames = new OUString[nLength];
    for( sal_Int16 i = 0; i < nLength; i++ )
        pPropertyNames[i] = pNames[i];
}

MultiPropertySetHelper::~MultiPropertySetHelper()
{
    pValues = NULL; // memory 'owned' by aValues

    delete[] pSequenceIndex;
    delete[] pPropertyNames;
}

void MultiPropertySetHelper::hasProperties(
    const Reference<XPropertySetInfo> & rInfo )
{
    DBG_ASSERT( rInfo.is(), "I'd really like an XPropertySetInfo here." );

    // allocate sequence index
    if ( NULL == pSequenceIndex )
        pSequenceIndex = new sal_Int16[nLength] ;

    // construct pSequenceIndex
    sal_Int16 nNumberOfProperties = 0;
    sal_Int16 i;

    for( i = 0; i < nLength; i++ )
    {
        // ask for property
        sal_Bool bHasProperty =
            rInfo->hasPropertyByName( pPropertyNames[i] );

        // set index and increment (if appropriate)
        pSequenceIndex[i]= bHasProperty ? nNumberOfProperties : -1;
        if ( bHasProperty )
            nNumberOfProperties++;
    }

    // construct property sequence from index array
    if ( aPropertySequence.getLength() != nNumberOfProperties )
        aPropertySequence.realloc( nNumberOfProperties );
    OUString* pPropertySequence = aPropertySequence.getArray();
    for( i = 0; i < nLength; i ++ )
    {
        sal_Int16 nIndex = pSequenceIndex[i];
        if ( nIndex != -1 )
            pPropertySequence[nIndex] = pPropertyNames[i];
    }
}

sal_Bool MultiPropertySetHelper::checkedProperties()
{
    return (NULL != pSequenceIndex);
}

void MultiPropertySetHelper::getValues(
    const Reference<XMultiPropertySet> & rMultiPropertySet )
{
    DBG_ASSERT( rMultiPropertySet.is(), "We need an XMultiPropertySet." );

    aValues = rMultiPropertySet->getPropertyValues( aPropertySequence );
    pValues = aValues.getConstArray();
}

void MultiPropertySetHelper::getValues(
    const Reference<XPropertySet> & rPropertySet )
{
    DBG_ASSERT( rPropertySet.is(), "We need an XPropertySet." );

    // re-alloc aValues (if necessary) and fill with values from XPropertySet
    sal_Int16 nSupportedPropertiesCount =
        (sal_Int16)aPropertySequence.getLength();
    if ( aValues.getLength() != nSupportedPropertiesCount )
        aValues.realloc( nSupportedPropertiesCount );
    Any* pMutableArray = aValues.getArray();
    for( sal_Int16 i = 0; i < nSupportedPropertiesCount; i++ )
    {
        pMutableArray[i] = rPropertySet->getPropertyValue(
            pPropertyNames[ pSequenceIndex[ i ] ] );
    }

    // re-establish pValues pointer
    pValues = aValues.getConstArray();
}

const Any& MultiPropertySetHelper::getValue( sal_Int16 nIndex,
                     const Reference< XPropertySet> & rPropSet,
                     sal_Bool bTryMulti )
{
    if( !pValues )
    {
        if( bTryMulti )
        {
            Reference < XMultiPropertySet > xMultiPropSet( rPropSet,
                                                           UNO_QUERY );
            if( xMultiPropSet.is() )
                getValues( xMultiPropSet );
            else
                getValues( rPropSet );
        }
        else
        {
            getValues( rPropSet );
        }
    }

    return getValue( nIndex );
}

const Any& MultiPropertySetHelper::getValue( sal_Int16 nIndex,
                     const Reference< XMultiPropertySet> & rMultiPropSet )
{
    if( !pValues )
        getValues( rMultiPropSet );

    return getValue( nIndex );
}

// inline methods defined in header:
// inline Any& MultiPropertySetHelper::getValue( sal_Int16 nIndex )
// inline sal_Bool MultiPropertySetHelper::hasProperty( sal_Int16 nValueNo )
<commit_msg>INTEGRATION: CWS ooo19126 (1.4.404); FILE MERGED 2005/09/05 14:39:12 rt 1.4.404.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: MultiPropertySetHelper.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 14:24:49 $
 *
 *  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 _XMLOFF_MULTIPROPERTYSETHELPER_HXX
#include "MultiPropertySetHelper.hxx"
#endif

#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSETINFO_HPP_
#include <com/sun/star/beans/XPropertySetInfo.hpp>
#endif

#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif

#ifndef _COM_SUN_STAR_BEANS_XMULTIPROPERTYSET_HPP_
#include <com/sun/star/beans/XMultiPropertySet.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif

#ifndef _COMPHELPER_STLTYPES_HXX_
#include <comphelper/stl_types.hxx>
#endif

// STL includes
#include <algorithm>

using ::com::sun::star::beans::XMultiPropertySet;
using ::com::sun::star::beans::XPropertySet;
using ::com::sun::star::beans::XPropertySetInfo;
using ::com::sun::star::lang::XServiceInfo;
using ::com::sun::star::uno::Any;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Sequence;
using ::com::sun::star::uno::UNO_QUERY;
using ::comphelper::UStringLess;
using ::rtl::OUString;
using ::std::sort;

MultiPropertySetHelper::MultiPropertySetHelper(
    const sal_Char** pNames ) :
        pPropertyNames( NULL ),
        nLength( 0 ),
        aPropertySequence(),
        pSequenceIndex( NULL ),
        aValues(),
        pValues( NULL )
{
    // first count the elements
    for( const sal_Char** pPtr = pNames; *pPtr != NULL; pPtr++ )
        nLength++;

    // allocate array and create strings
    pPropertyNames = new OUString[nLength];
    for( sal_Int16 i = 0; i < nLength; i++ )
        pPropertyNames[i] = OUString::createFromAscii( pNames[i] );
}

MultiPropertySetHelper::MultiPropertySetHelper(
    const OUString* pNames ) :
        pPropertyNames( NULL ),
        nLength( 0 ),
        aPropertySequence(),
        pSequenceIndex( NULL ),
        aValues(),
        pValues( NULL )
{
    // count elements
    for( const OUString* pPtr = pNames; pPtr != NULL; pPtr++ )
        nLength++;

    // allocate array and assign strings
    pPropertyNames = new OUString[nLength];
    for( sal_Int16 i = 0; i < nLength; i++ )
        pPropertyNames[i] = pNames[i];
}

MultiPropertySetHelper::~MultiPropertySetHelper()
{
    pValues = NULL; // memory 'owned' by aValues

    delete[] pSequenceIndex;
    delete[] pPropertyNames;
}

void MultiPropertySetHelper::hasProperties(
    const Reference<XPropertySetInfo> & rInfo )
{
    DBG_ASSERT( rInfo.is(), "I'd really like an XPropertySetInfo here." );

    // allocate sequence index
    if ( NULL == pSequenceIndex )
        pSequenceIndex = new sal_Int16[nLength] ;

    // construct pSequenceIndex
    sal_Int16 nNumberOfProperties = 0;
    sal_Int16 i;

    for( i = 0; i < nLength; i++ )
    {
        // ask for property
        sal_Bool bHasProperty =
            rInfo->hasPropertyByName( pPropertyNames[i] );

        // set index and increment (if appropriate)
        pSequenceIndex[i]= bHasProperty ? nNumberOfProperties : -1;
        if ( bHasProperty )
            nNumberOfProperties++;
    }

    // construct property sequence from index array
    if ( aPropertySequence.getLength() != nNumberOfProperties )
        aPropertySequence.realloc( nNumberOfProperties );
    OUString* pPropertySequence = aPropertySequence.getArray();
    for( i = 0; i < nLength; i ++ )
    {
        sal_Int16 nIndex = pSequenceIndex[i];
        if ( nIndex != -1 )
            pPropertySequence[nIndex] = pPropertyNames[i];
    }
}

sal_Bool MultiPropertySetHelper::checkedProperties()
{
    return (NULL != pSequenceIndex);
}

void MultiPropertySetHelper::getValues(
    const Reference<XMultiPropertySet> & rMultiPropertySet )
{
    DBG_ASSERT( rMultiPropertySet.is(), "We need an XMultiPropertySet." );

    aValues = rMultiPropertySet->getPropertyValues( aPropertySequence );
    pValues = aValues.getConstArray();
}

void MultiPropertySetHelper::getValues(
    const Reference<XPropertySet> & rPropertySet )
{
    DBG_ASSERT( rPropertySet.is(), "We need an XPropertySet." );

    // re-alloc aValues (if necessary) and fill with values from XPropertySet
    sal_Int16 nSupportedPropertiesCount =
        (sal_Int16)aPropertySequence.getLength();
    if ( aValues.getLength() != nSupportedPropertiesCount )
        aValues.realloc( nSupportedPropertiesCount );
    Any* pMutableArray = aValues.getArray();
    for( sal_Int16 i = 0; i < nSupportedPropertiesCount; i++ )
    {
        pMutableArray[i] = rPropertySet->getPropertyValue(
            pPropertyNames[ pSequenceIndex[ i ] ] );
    }

    // re-establish pValues pointer
    pValues = aValues.getConstArray();
}

const Any& MultiPropertySetHelper::getValue( sal_Int16 nIndex,
                     const Reference< XPropertySet> & rPropSet,
                     sal_Bool bTryMulti )
{
    if( !pValues )
    {
        if( bTryMulti )
        {
            Reference < XMultiPropertySet > xMultiPropSet( rPropSet,
                                                           UNO_QUERY );
            if( xMultiPropSet.is() )
                getValues( xMultiPropSet );
            else
                getValues( rPropSet );
        }
        else
        {
            getValues( rPropSet );
        }
    }

    return getValue( nIndex );
}

const Any& MultiPropertySetHelper::getValue( sal_Int16 nIndex,
                     const Reference< XMultiPropertySet> & rMultiPropSet )
{
    if( !pValues )
        getValues( rMultiPropSet );

    return getValue( nIndex );
}

// inline methods defined in header:
// inline Any& MultiPropertySetHelper::getValue( sal_Int16 nIndex )
// inline sal_Bool MultiPropertySetHelper::hasProperty( sal_Int16 nValueNo )
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: StyleOASISTContext.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: hr $ $Date: 2004-11-09 12:25:22 $
 *
 *  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 _XMLOFF_STYLEOASISTCONTEXT_HXX
#define _XMLOFF_STYLEOASISTCONTEXT_HXX

#ifndef _RTL_REF_HXX_
#include <rtl/ref.hxx>
#endif

#ifndef _XMLOFF_DEEPTCONTEXT_HXX
#include "DeepTContext.hxx"
#endif

class XMLTransformerActions;
class XMLPropertiesTContext_Impl;
class XMLStyleOASISTContext : public XMLPersElemContentTContext
{
    ::rtl::Reference< XMLPropertiesTContext_Impl > m_xPropContext;

    sal_Bool m_bPersistent;
    sal_Bool m_bControlStyle;

public:
    TYPEINFO();

    XMLStyleOASISTContext( XMLTransformerBase& rTransformer,
                           const ::rtl::OUString& rQName,
                              sal_Bool bPersistent=sal_False );
    XMLStyleOASISTContext( XMLTransformerBase& rTransformer,
                           const ::rtl::OUString& rQName,
                              sal_uInt16 nPrefix,
                              ::xmloff::token::XMLTokenEnum eToken,
                              sal_Bool bPersistent=sal_False );

    virtual ~XMLStyleOASISTContext();

    virtual XMLTransformerContext *CreateChildContext( sal_uInt16 nPrefix,
                                   const ::rtl::OUString& rLocalName,
                                   const ::rtl::OUString& rQName,
                                   const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList );

    virtual void StartElement( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList );
    virtual void EndElement();
    virtual void Characters( const ::rtl::OUString& rChars );

    virtual void ExportContent();

    virtual sal_Bool IsPersistent() const;

    static XMLTransformerActions *CreateTransformerActions( sal_uInt16 nType );
};

#endif  //  _XMLOFF_STYLEOASISTCONTEXT_HXX

<commit_msg>INTEGRATION: CWS impress17 (1.2.90); FILE MERGED 2004/10/26 14:50:38 cl 1.2.90.1: #i35792# renamed draw:writing-mode to style:writing-mode<commit_after>/*************************************************************************
 *
 *  $RCSfile: StyleOASISTContext.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2004-11-17 10:39:21 $
 *
 *  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 _XMLOFF_STYLEOASISTCONTEXT_HXX
#define _XMLOFF_STYLEOASISTCONTEXT_HXX

#ifndef _RTL_REF_HXX_
#include <rtl/ref.hxx>
#endif

#ifndef _XMLOFF_DEEPTCONTEXT_HXX
#include "DeepTContext.hxx"
#endif

class XMLTransformerActions;
class XMLPropertiesTContext_Impl;
class XMLStyleOASISTContext : public XMLPersElemContentTContext
{
    ::rtl::Reference< XMLPropertiesTContext_Impl > m_xPropContext;

    sal_Bool m_bPersistent;
    sal_Bool m_bControlStyle;

    ::rtl::OUString m_aStyleFamily;
public:
    TYPEINFO();

    XMLStyleOASISTContext( XMLTransformerBase& rTransformer,
                           const ::rtl::OUString& rQName,
                              sal_Bool bPersistent=sal_False );
    XMLStyleOASISTContext( XMLTransformerBase& rTransformer,
                           const ::rtl::OUString& rQName,
                              sal_uInt16 nPrefix,
                              ::xmloff::token::XMLTokenEnum eToken,
                              sal_Bool bPersistent=sal_False );

    virtual ~XMLStyleOASISTContext();

    virtual XMLTransformerContext *CreateChildContext( sal_uInt16 nPrefix,
                                   const ::rtl::OUString& rLocalName,
                                   const ::rtl::OUString& rQName,
                                   const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList );

    virtual void StartElement( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList );
    virtual void EndElement();
    virtual void Characters( const ::rtl::OUString& rChars );

    virtual void ExportContent();

    virtual sal_Bool IsPersistent() const;

    static XMLTransformerActions *CreateTransformerActions( sal_uInt16 nType );
};

#endif  //  _XMLOFF_STYLEOASISTCONTEXT_HXX

<|endoftext|>


<commit_before>/*
 * File:   Composite.hpp
 * Author: Benedikt Vogler
 *
 * Created on 21. August 2014, 10:51
 */

#ifndef COMPOSITE_HPP
#define	COMPOSITE_HPP

#include "RenderObject.hpp"
#include <vector>

class Composite : public RenderObject {
public:
    Composite(string const& name):
        RenderObject(name,Material())
    {}

    void add_child(RenderObject* const& child);
    virtual Intersection intersect(const Ray& ray) const;

    virtual void translate(glm::vec3 const& translateLocation);
    virtual void rotate(double angle, glm::vec3 const& vector);
    virtual void scale(glm::vec3 const& axis);

private:
    std::vector<RenderObject*> children;

};

#endif	/* COMPOSITE_HPP */

<commit_msg>cons cor. order<commit_after>/*
 * File:   Composite.hpp
 * Author: Benedikt Vogler
 *
 * Created on 21. August 2014, 10:51
 */

#ifndef COMPOSITE_HPP
#define	COMPOSITE_HPP

#include "RenderObject.hpp"
#include <vector>

class Composite : public RenderObject {
public:
    Composite(string const& name):
        RenderObject(name,Material())
    {}

    void add_child(RenderObject* const& child);
    virtual Intersection intersect(Ray const& ray) const;

    virtual void translate(glm::vec3 const& translateLocation);
    virtual void rotate(double angle, glm::vec3 const& vector);
    virtual void scale(glm::vec3 const& axis);

private:
    std::vector<RenderObject*> children;

};

#endif	/* COMPOSITE_HPP */

<|endoftext|>