<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: getfilenamewrapper.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: obo $ $Date: 2006-10-12 10:53:22 $
 *
 *  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
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_fpicker.hxx"

//------------------------------------------------------------------------
// includes
//------------------------------------------------------------------------

#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif

#ifndef _GETFILENAMEWRAPPER_HXX_
#include "getfilenamewrapper.hxx"
#endif

#if defined _MSC_VER
#pragma warning(push, 1)
#endif
#include <objbase.h>
#include <process.h>
#if defined _MSC_VER
#pragma warning(pop)
#endif

namespace /* private */
{

    //-----------------------------------------------
    //
    //-----------------------------------------------

    struct GetFileNameParam
    {
        GetFileNameParam(bool bOpen, LPOPENFILENAME lpofn) :
            m_bOpen(bOpen),
            m_lpofn(lpofn),
            m_bRet(false),
            m_ExtErr(0)
        {}

        bool            m_bOpen;
        LPOPENFILENAME  m_lpofn;
        bool            m_bRet;
        int             m_ExtErr;
    };

    //-----------------------------------------------
    //
    //-----------------------------------------------

    unsigned __stdcall ThreadProc(void* pParam)
    {
        GetFileNameParam* lpgfnp =
            reinterpret_cast<GetFileNameParam*>(pParam);

        HRESULT hr = OleInitialize( NULL );

        if (lpgfnp->m_bOpen)
            lpgfnp->m_bRet = GetOpenFileName(lpgfnp->m_lpofn);
        else
            lpgfnp->m_bRet = GetSaveFileName(lpgfnp->m_lpofn);

        lpgfnp->m_ExtErr = CommDlgExtendedError();

        if ( SUCCEEDED( hr ) )
            OleUninitialize();

        return 0;
    }

    //-----------------------------------------------
    // exceutes GetOpenFileName/GetSaveFileName in
    // a separat thread
    //-----------------------------------------------

    bool ThreadExecGetFileName(LPOPENFILENAME lpofn, bool bOpen, /*out*/ int& ExtErr)
    {
        GetFileNameParam gfnp(bOpen,lpofn);
        unsigned         id;

        HANDLE hThread = reinterpret_cast<HANDLE>(
            _beginthreadex(0, 0, ThreadProc, &gfnp, 0, &id));

        OSL_POSTCOND(hThread, "could not create STA thread");

        WaitForSingleObject(hThread, INFINITE);
        CloseHandle(hThread);

        ExtErr = gfnp.m_ExtErr;

        return gfnp.m_bRet;
    }

    //-----------------------------------------------
    // This function returns true if the calling
    // thread belongs to a Multithreaded Appartment
    // (MTA)
    //-----------------------------------------------

    bool IsMTA()
    {
        HRESULT hr = CoInitialize(NULL);

        if (RPC_E_CHANGED_MODE == hr)
            return true;

        if(SUCCEEDED(hr))
            CoUninitialize();

        return false;
    }

} // namespace private

//-----------------------------------------------
//
//-----------------------------------------------

CGetFileNameWrapper::CGetFileNameWrapper() :
    m_ExtendedDialogError(0)
{
}

//-----------------------------------------------
//
//-----------------------------------------------

bool CGetFileNameWrapper::getOpenFileName(LPOPENFILENAME lpofn)
{
    OSL_PRECOND(lpofn,"invalid parameter");

    bool bRet = false;

    if (IsMTA())
    {
        bRet = ThreadExecGetFileName(
            lpofn, true, m_ExtendedDialogError);
    }
    else
    {
        HRESULT hr = OleInitialize( NULL );

        bRet = GetOpenFileName(lpofn);
        m_ExtendedDialogError = CommDlgExtendedError();

        if ( SUCCEEDED( hr ) )
            OleUninitialize();
    }

    return bRet;
}

//-----------------------------------------------
//
//-----------------------------------------------

bool CGetFileNameWrapper::getSaveFileName(LPOPENFILENAME lpofn)
{
    OSL_PRECOND(lpofn,"invalid parameter");

    bool bRet = false;

    if (IsMTA())
    {
        bRet = ThreadExecGetFileName(
            lpofn, false, m_ExtendedDialogError);
    }
    else
    {
        bRet = GetSaveFileName(lpofn);
        m_ExtendedDialogError = CommDlgExtendedError();
    }

    return bRet;
}

//-----------------------------------------------
//
//-----------------------------------------------

int CGetFileNameWrapper::commDlgExtendedError( )
{
    return m_ExtendedDialogError;
}

<commit_msg>INTEGRATION: CWS fwk56 (1.8.22); FILE MERGED 2006/11/28 09:26:47 mav 1.8.22.2: #i21747# fix long path handling 2006/11/15 14:42:49 mav 1.8.22.1: #i21747# preserv the current directory value<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: getfilenamewrapper.cxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: ihi $ $Date: 2006-12-19 13:54:09 $
 *
 *  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
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_fpicker.hxx"

//------------------------------------------------------------------------
// includes
//------------------------------------------------------------------------

#include <stdio.h>

#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif

#ifndef _GETFILENAMEWRAPPER_HXX_
#include "getfilenamewrapper.hxx"
#endif

#if defined _MSC_VER
#pragma warning(push, 1)
#endif
#include <objbase.h>
#include <process.h>
#if defined _MSC_VER
#pragma warning(pop)
#endif

namespace /* private */
{

    //-----------------------------------------------
    // This class prevents changing of the working
    // directory.
    //-----------------------------------------------
    class CurDirGuard
    {
        BOOL m_bValid;
        wchar_t* m_pBuffer;
        DWORD m_nBufLen;

    public:
        CurDirGuard()
        : m_bValid( FALSE )
        , m_pBuffer( NULL )
        , m_nBufLen( 0 )
        {
            m_nBufLen = GetCurrentDirectoryW( 0, NULL );
            if ( m_nBufLen )
            {
                m_pBuffer = new wchar_t[m_nBufLen];
                m_bValid = ( GetCurrentDirectoryW( m_nBufLen, m_pBuffer ) == ( m_nBufLen - 1 ) );
            }
        }

        ~CurDirGuard()
        {
            BOOL bDirSet = FALSE;

            if ( m_pBuffer )
            {
                if ( m_bValid )
                {
                    if ( m_nBufLen - 1 > MAX_PATH )
                    {
                        if ( (LONG32)GetVersion() < 0 )
                        {
                            // this is Win 98/ME branch, such a long path can not be set
                            // use the system path as fallback later
                        }
                        else
                        {
                            DWORD nNewLen = m_nBufLen + 8;
                            wchar_t* pNewBuffer = new wchar_t[nNewLen];
                            if ( m_nBufLen > 3 && m_pBuffer[0] == (wchar_t)'\\' && m_pBuffer[1] == (wchar_t)'\\' )
                            {
                                if ( m_pBuffer[2] == (wchar_t)'?' )
                                    _snwprintf( pNewBuffer, nNewLen, L"%s", m_pBuffer );
                                else
                                    _snwprintf( pNewBuffer, nNewLen, L"\\\\?\\UNC\\%s", m_pBuffer+2 );
                            }
                            else
                                _snwprintf( pNewBuffer, nNewLen, L"\\\\?\\%s", m_pBuffer );
                            bDirSet = SetCurrentDirectoryW( pNewBuffer );

                            delete [] pNewBuffer;
                        }
                    }
                    else
                        bDirSet = SetCurrentDirectoryW( m_pBuffer );
                }

                delete [] m_pBuffer;
                m_pBuffer = NULL;
            }

            if ( !bDirSet )
            {
                // the fallback solution
                wchar_t pPath[MAX_PATH+1];
                if ( GetWindowsDirectoryW( pPath, MAX_PATH+1 ) <= MAX_PATH )
                {
                    SetCurrentDirectoryW( pPath );
                }
                else
                {
                    // the system path is also too long?!!
                }
            }
        }
    };

    //-----------------------------------------------
    //
    //-----------------------------------------------

    struct GetFileNameParam
    {
        GetFileNameParam(bool bOpen, LPOPENFILENAME lpofn) :
            m_bOpen(bOpen),
            m_lpofn(lpofn),
            m_bRet(false),
            m_ExtErr(0)
        {}

        bool            m_bOpen;
        LPOPENFILENAME  m_lpofn;
        bool            m_bRet;
        int             m_ExtErr;
    };

    //-----------------------------------------------
    //
    //-----------------------------------------------

    unsigned __stdcall ThreadProc(void* pParam)
    {
        CurDirGuard aGuard;

        GetFileNameParam* lpgfnp =
            reinterpret_cast<GetFileNameParam*>(pParam);

        HRESULT hr = OleInitialize( NULL );

        if (lpgfnp->m_bOpen)
            lpgfnp->m_bRet = GetOpenFileName(lpgfnp->m_lpofn);
        else
            lpgfnp->m_bRet = GetSaveFileName(lpgfnp->m_lpofn);

        lpgfnp->m_ExtErr = CommDlgExtendedError();

        if ( SUCCEEDED( hr ) )
            OleUninitialize();

        return 0;
    }

    //-----------------------------------------------
    // exceutes GetOpenFileName/GetSaveFileName in
    // a separat thread
    //-----------------------------------------------

    bool ThreadExecGetFileName(LPOPENFILENAME lpofn, bool bOpen, /*out*/ int& ExtErr)
    {
        GetFileNameParam gfnp(bOpen,lpofn);
        unsigned         id;

        HANDLE hThread = reinterpret_cast<HANDLE>(
            _beginthreadex(0, 0, ThreadProc, &gfnp, 0, &id));

        OSL_POSTCOND(hThread, "could not create STA thread");

        WaitForSingleObject(hThread, INFINITE);
        CloseHandle(hThread);

        ExtErr = gfnp.m_ExtErr;

        return gfnp.m_bRet;
    }

    //-----------------------------------------------
    // This function returns true if the calling
    // thread belongs to a Multithreaded Appartment
    // (MTA)
    //-----------------------------------------------

    bool IsMTA()
    {
        HRESULT hr = CoInitialize(NULL);

        if (RPC_E_CHANGED_MODE == hr)
            return true;

        if(SUCCEEDED(hr))
            CoUninitialize();

        return false;
    }

} // namespace private

//-----------------------------------------------
//
//-----------------------------------------------

CGetFileNameWrapper::CGetFileNameWrapper() :
    m_ExtendedDialogError(0)
{
}

//-----------------------------------------------
//
//-----------------------------------------------

bool CGetFileNameWrapper::getOpenFileName(LPOPENFILENAME lpofn)
{
    OSL_PRECOND(lpofn,"invalid parameter");

    bool bRet = false;

    if (IsMTA())
    {
        bRet = ThreadExecGetFileName(
            lpofn, true, m_ExtendedDialogError);
    }
    else
    {
        CurDirGuard aGuard;

        HRESULT hr = OleInitialize( NULL );

        bRet = GetOpenFileName(lpofn);
        m_ExtendedDialogError = CommDlgExtendedError();

        if ( SUCCEEDED( hr ) )
            OleUninitialize();
    }

    return bRet;
}

//-----------------------------------------------
//
//-----------------------------------------------

bool CGetFileNameWrapper::getSaveFileName(LPOPENFILENAME lpofn)
{
    OSL_PRECOND(lpofn,"invalid parameter");

    bool bRet = false;

    if (IsMTA())
    {
        bRet = ThreadExecGetFileName(
            lpofn, false, m_ExtendedDialogError);
    }
    else
    {
        CurDirGuard aGuard;

        bRet = GetSaveFileName(lpofn);
        m_ExtendedDialogError = CommDlgExtendedError();
    }

    return bRet;
}

//-----------------------------------------------
//
//-----------------------------------------------

int CGetFileNameWrapper::commDlgExtendedError( )
{
    return m_ExtendedDialogError;
}

<|endoftext|>


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

#include "cybertron/transport/qos/qos_profile_conf.h"

namespace apollo {
namespace cybertron {
namespace transport {

QosProfileConf::QosProfileConf() {}

QosProfileConf::~QosProfileConf() {}

QosProfile QosProfileConf::CreateQosProfile(
    const QosHistoryPolicy& history, size_t depth, size_t mps,
    const QosReliabilityPolicy& reliability,
    const QosDurabilityPolicy& durability) {
  QosProfile qos_profile;
  qos_profile.set_history(history);
  qos_profile.set_depth(depth);
  qos_profile.set_mps(mps);
  qos_profile.set_reliability(reliability);
  qos_profile.set_durability(durability);

  return qos_profile;
}

const size_t QosProfileConf::QOS_HISTORY_DEPTH_SYSTEM_DEFAULT = 0;
const size_t QosProfileConf::QOS_MPS_SYSTEM_DEFAULT = 0;

const QosProfile QosProfileConf::QOS_PROFILE_DEFAULT = CreateQosProfile(
    QosHistoryPolicy::HISTORY_KEEP_LAST, 2000, QOS_MPS_SYSTEM_DEFAULT,
    QosReliabilityPolicy::RELIABILITY_RELIABLE,
    QosDurabilityPolicy::DURABILITY_VOLATILE);

const QosProfile QosProfileConf::QOS_PROFILE_SENSOR_DATA = CreateQosProfile(
    QosHistoryPolicy::HISTORY_KEEP_LAST, 5, QOS_MPS_SYSTEM_DEFAULT,
    QosReliabilityPolicy::RELIABILITY_BEST_EFFORT,
    QosDurabilityPolicy::DURABILITY_VOLATILE);

const QosProfile QosProfileConf::QOS_PROFILE_PARAMETERS = CreateQosProfile(
    QosHistoryPolicy::HISTORY_KEEP_LAST, 1000, QOS_MPS_SYSTEM_DEFAULT,
    QosReliabilityPolicy::RELIABILITY_RELIABLE,
    QosDurabilityPolicy::DURABILITY_VOLATILE);

const QosProfile QosProfileConf::QOS_PROFILE_SERVICES_DEFAULT =
    CreateQosProfile(QosHistoryPolicy::HISTORY_KEEP_LAST, 10,
                     QOS_MPS_SYSTEM_DEFAULT,
                     QosReliabilityPolicy::RELIABILITY_RELIABLE,
                     QosDurabilityPolicy::DURABILITY_TRANSIENT_LOCAL);

const QosProfile QosProfileConf::QOS_PROFILE_PARAM_EVENT = CreateQosProfile(
    QosHistoryPolicy::HISTORY_KEEP_LAST, 1000, QOS_MPS_SYSTEM_DEFAULT,
    QosReliabilityPolicy::RELIABILITY_RELIABLE,
    QosDurabilityPolicy::DURABILITY_VOLATILE);

const QosProfile QosProfileConf::QOS_PROFILE_SYSTEM_DEFAULT = CreateQosProfile(
    QosHistoryPolicy::HISTORY_SYSTEM_DEFAULT, QOS_HISTORY_DEPTH_SYSTEM_DEFAULT,
    QOS_MPS_SYSTEM_DEFAULT, QosReliabilityPolicy::RELIABILITY_RELIABLE,
    QosDurabilityPolicy::DURABILITY_TRANSIENT_LOCAL);

const QosProfile QosProfileConf::QOS_PROFILE_TF_STATIC = CreateQosProfile(
    QosHistoryPolicy::HISTORY_KEEP_ALL, 10, QOS_MPS_SYSTEM_DEFAULT,
    QosReliabilityPolicy::RELIABILITY_RELIABLE,
    QosDurabilityPolicy::DURABILITY_TRANSIENT_LOCAL);

const QosProfile QosProfileConf::QOS_PROFILE_TOPO_CHANGE = CreateQosProfile(
    QosHistoryPolicy::HISTORY_KEEP_ALL, 10, QOS_MPS_SYSTEM_DEFAULT,
    QosReliabilityPolicy::RELIABILITY_RELIABLE,
    QosDurabilityPolicy::DURABILITY_TRANSIENT_LOCAL);

}  // namespace transport
}  // namespace cybertron
}  // namespace apollo
<commit_msg>framework: change default history depth to 1<commit_after>/******************************************************************************
 * Copyright 2018 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

#include "cybertron/transport/qos/qos_profile_conf.h"

namespace apollo {
namespace cybertron {
namespace transport {

QosProfileConf::QosProfileConf() {}

QosProfileConf::~QosProfileConf() {}

QosProfile QosProfileConf::CreateQosProfile(
    const QosHistoryPolicy& history, size_t depth, size_t mps,
    const QosReliabilityPolicy& reliability,
    const QosDurabilityPolicy& durability) {
  QosProfile qos_profile;
  qos_profile.set_history(history);
  qos_profile.set_depth(depth);
  qos_profile.set_mps(mps);
  qos_profile.set_reliability(reliability);
  qos_profile.set_durability(durability);

  return qos_profile;
}

const size_t QosProfileConf::QOS_HISTORY_DEPTH_SYSTEM_DEFAULT = 0;
const size_t QosProfileConf::QOS_MPS_SYSTEM_DEFAULT = 0;

const QosProfile QosProfileConf::QOS_PROFILE_DEFAULT = CreateQosProfile(
    QosHistoryPolicy::HISTORY_KEEP_LAST, 1, QOS_MPS_SYSTEM_DEFAULT,
    QosReliabilityPolicy::RELIABILITY_RELIABLE,
    QosDurabilityPolicy::DURABILITY_VOLATILE);

const QosProfile QosProfileConf::QOS_PROFILE_SENSOR_DATA = CreateQosProfile(
    QosHistoryPolicy::HISTORY_KEEP_LAST, 5, QOS_MPS_SYSTEM_DEFAULT,
    QosReliabilityPolicy::RELIABILITY_BEST_EFFORT,
    QosDurabilityPolicy::DURABILITY_VOLATILE);

const QosProfile QosProfileConf::QOS_PROFILE_PARAMETERS = CreateQosProfile(
    QosHistoryPolicy::HISTORY_KEEP_LAST, 1000, QOS_MPS_SYSTEM_DEFAULT,
    QosReliabilityPolicy::RELIABILITY_RELIABLE,
    QosDurabilityPolicy::DURABILITY_VOLATILE);

const QosProfile QosProfileConf::QOS_PROFILE_SERVICES_DEFAULT =
    CreateQosProfile(QosHistoryPolicy::HISTORY_KEEP_LAST, 10,
                     QOS_MPS_SYSTEM_DEFAULT,
                     QosReliabilityPolicy::RELIABILITY_RELIABLE,
                     QosDurabilityPolicy::DURABILITY_TRANSIENT_LOCAL);

const QosProfile QosProfileConf::QOS_PROFILE_PARAM_EVENT = CreateQosProfile(
    QosHistoryPolicy::HISTORY_KEEP_LAST, 1000, QOS_MPS_SYSTEM_DEFAULT,
    QosReliabilityPolicy::RELIABILITY_RELIABLE,
    QosDurabilityPolicy::DURABILITY_VOLATILE);

const QosProfile QosProfileConf::QOS_PROFILE_SYSTEM_DEFAULT = CreateQosProfile(
    QosHistoryPolicy::HISTORY_SYSTEM_DEFAULT, QOS_HISTORY_DEPTH_SYSTEM_DEFAULT,
    QOS_MPS_SYSTEM_DEFAULT, QosReliabilityPolicy::RELIABILITY_RELIABLE,
    QosDurabilityPolicy::DURABILITY_TRANSIENT_LOCAL);

const QosProfile QosProfileConf::QOS_PROFILE_TF_STATIC = CreateQosProfile(
    QosHistoryPolicy::HISTORY_KEEP_ALL, 10, QOS_MPS_SYSTEM_DEFAULT,
    QosReliabilityPolicy::RELIABILITY_RELIABLE,
    QosDurabilityPolicy::DURABILITY_TRANSIENT_LOCAL);

const QosProfile QosProfileConf::QOS_PROFILE_TOPO_CHANGE = CreateQosProfile(
    QosHistoryPolicy::HISTORY_KEEP_ALL, 10, QOS_MPS_SYSTEM_DEFAULT,
    QosReliabilityPolicy::RELIABILITY_RELIABLE,
    QosDurabilityPolicy::DURABILITY_TRANSIENT_LOCAL);

}  // namespace transport
}  // namespace cybertron
}  // namespace apollo
<|endoftext|>


<commit_before>#include <QSqlError>
#include <QFile>
#include <QDataStream>
#include <QDir>
#include <QDataStream>
#include <QUrl>
#include <fstream>
#include <iomanip>
#include "kernel.h"
#include "ilwisdata.h"
#include "ilwiscontext.h"
#include "errorobject.h"
#include "issuelogger.h"

using namespace Ilwis;

std::map<std::thread::id, bool> IssueLogger::_silentThreads;

IssueObject::IssueObject()
{
}

Ilwis::IssueObject::IssueObject(const QString &message, int it, quint64 id)
{
    _message = message;
    _itype = it;
    _itime = QDateTime::currentDateTime();
    _id = id;
}

QString Ilwis::IssueObject::message() const
{
    return _message;
}

QDateTime Ilwis::IssueObject::time() const
{
    return _itime;
}

int Ilwis::IssueObject::type() const
{
    return _itype;
}

QString Ilwis::IssueObject::logMessage(Ilwis::IssueObject::LogMessageFormat) const{
    return QString("%1: (%2) %3").arg(type2String(), _itime.toString(), _message);
}

int IssueObject::codeLine() const {
    return _line;
}

QString IssueObject::codeFunc() const {
    return _func;
}

QString IssueObject::codeFile() const {
    return _file;
}

void IssueObject::addCodeInfo(int line, const QString &func, const QString &file)
{
    _line = line;
    _func = func;
    _file = file;
}

void IssueObject::stream(std::ofstream& stream, LogMessageFormat frmt) {
    stream << std::setw(4) << _id << " ; " << std::setw(9) << type2String().toStdString() << " ; " << std::setw(27)<<_itime.toString().toStdString() << " ; " << _message.toStdString() << std::endl;
    if ( frmt == lmCODE) {
        stream << std::setw(4) << _id << " ; " << _line << " : " << _func.toStdString() << " ; " << _file.toStdString() << std::endl;
    }
}

quint64 IssueObject::id() const
{
    return _id;
}

QString IssueObject::type2String() const{
    switch(_itype) {
    case itCritical:
        return "Critical";
    case itError:
        return "Error";
    case itWarning:
        return "Warning";
    case itMessage:
        return "Message";
    case itDebug:
        return "Debug";
    }
    return "Text";
}

//---------------------------------------------------------------------------
IssueLogger::IssueLogger(QObject *parent) : QObject(parent), _repeatCount(0)
{
    QString apploc= context()->ilwisFolder().absoluteFilePath();
    apploc += "/log";
    QDir dir(apploc);
    if ( !dir.exists())
        dir.mkdir(apploc);
    QString rlogFilePath = apploc + "/logfile.txt";
    QString clogFilePath = apploc + "/logfile_ext.txt";
    _logFileRegular.open(rlogFilePath.toLatin1());
    _logFileCode.open(clogFilePath.toLatin1());
}

IssueLogger::~IssueLogger()
{
    if (_logFileCode.is_open())
        _logFileCode.close();
    if ( _logFileRegular.is_open())
        _logFileRegular.close();
}

quint64 IssueLogger::log(const QString &message, int it)
{
    ++_repeatCount;
    std::thread::id id = std::this_thread::get_id();
    if ( _silentThreads.find(id)!= _silentThreads.end() && it != IssueObject::itCritical)
        return i64UNDEF;

    if ( _lastmessage == message && _repeatCount == 10) {
        return _issueId;
    } else {
        if ( _repeatCount > 10 && _lastmessage != message ){
            _issues.enqueue(IssueObject(QString("Message repeated %1 times").arg(_repeatCount), it, _issueId));
            throw ErrorObject("Error message cascade");
        }
        _repeatCount = 0;
    }

    _issues.enqueue(IssueObject(message, it, _issueId));
    if ( _lastmessage == message)
        return _issueId;
    IssueObject& obj = _issues.back();
    if ( _logFileRegular.is_open()) {
        obj.stream(_logFileRegular, IssueObject::lmREGULAR);
    }
    emit ilwiserrormessage(obj.logMessage());

    _lastmessage = message;
    return _issueId++;
}

quint64 IssueLogger::log(const QString& objectName, const QString &message, int it)
{
    QString newmessage = objectName + ":" + message;
    return log(newmessage, it);
}

void IssueLogger::addCodeInfo(quint64 issueid, int line, const QString &func, const QString &file)
{
    for(auto iter=_issues.begin(); iter != _issues.end(); ++iter) {
        IssueObject& issue = *iter;
        if ( issue.id() == issueid) {
            issue.addCodeInfo(line, func, file);
            if ( _logFileCode.is_open()) {
                issue.stream(_logFileCode, IssueObject::lmCODE);
            }
            break;
        }
    }
}

bool IssueLogger::silent() const
{
    std::thread::id id = std::this_thread::get_id();
    auto iter = _silentThreads.find(id);
    if ( iter != _silentThreads.end())
        return iter->second;
    return false;
}

void IssueLogger::silent(bool yesno)
{
    std::thread::id id = std::this_thread::get_id();
    if ( yesno == false){
        auto iter = _silentThreads.find(id) ;
        if (iter != _silentThreads.end())
            _silentThreads.erase(iter);
    }else
        _silentThreads[id] = true;
}

quint64 IssueLogger::logSql(const QSqlError &err)
{
   return log(err.text(), IssueObject::itError);
}

IssueObject::IssueType IssueLogger::maxIssueLevel() const
{
    int type = IssueObject::itNone;
    foreach(IssueObject issue, _issues) {
        type |= issue.type();
    }
    if ( type & IssueObject::itCritical)
        return IssueObject::itCritical;
    if ( type & IssueObject::itError)
        return IssueObject::itError;
    if ( type & IssueObject::itWarning)
        return IssueObject::itWarning;
    if ( type & IssueObject::itMessage)
        return IssueObject::itMessage;
    return IssueObject::itNone;
}

void IssueLogger::copy(IssueLogger &other)
{
  foreach(IssueObject issue, _issues) {
      other._issues.enqueue(issue);
  }
}

QString IssueLogger::popfirst(int tp) {
    if ( tp != IssueObject::itAll){
        for(auto iter= --_issues.end(); iter != _issues.begin(); --iter ){
            if (hasType((*iter).type(), tp)){
                QString mes = (*iter).message();
                _issues.erase(iter);
                return mes;
            }
        }
    }
    if ( _issues.size() > 0)
        return _issues.dequeue().message();
    return "?";
}

QString IssueLogger::poplast(int tp) {
    if ( tp != IssueObject::itAll){
        for(auto iter= _issues.begin(); iter != _issues.end(); ++iter ){
            if (hasType((*iter).type(), tp)){
                QString mes = (*iter).message();
                _issues.erase(iter);
                return mes;
            }
        }
    }
    if ( _issues.size() >0 )
        return _issues.takeLast().message();
    return "?";
}

void IssueLogger::clear() {
    _issues.clear();
}

<commit_msg>added comment about the error cascade mechanism<commit_after>#include <QSqlError>
#include <QFile>
#include <QDataStream>
#include <QDir>
#include <QDataStream>
#include <QUrl>
#include <fstream>
#include <iomanip>
#include "kernel.h"
#include "ilwisdata.h"
#include "ilwiscontext.h"
#include "errorobject.h"
#include "issuelogger.h"

using namespace Ilwis;

std::map<std::thread::id, bool> IssueLogger::_silentThreads;

IssueObject::IssueObject()
{
}

Ilwis::IssueObject::IssueObject(const QString &message, int it, quint64 id)
{
    _message = message;
    _itype = it;
    _itime = QDateTime::currentDateTime();
    _id = id;
}

QString Ilwis::IssueObject::message() const
{
    return _message;
}

QDateTime Ilwis::IssueObject::time() const
{
    return _itime;
}

int Ilwis::IssueObject::type() const
{
    return _itype;
}

QString Ilwis::IssueObject::logMessage(Ilwis::IssueObject::LogMessageFormat) const{
    return QString("%1: (%2) %3").arg(type2String(), _itime.toString(), _message);
}

int IssueObject::codeLine() const {
    return _line;
}

QString IssueObject::codeFunc() const {
    return _func;
}

QString IssueObject::codeFile() const {
    return _file;
}

void IssueObject::addCodeInfo(int line, const QString &func, const QString &file)
{
    _line = line;
    _func = func;
    _file = file;
}

void IssueObject::stream(std::ofstream& stream, LogMessageFormat frmt) {
    stream << std::setw(4) << _id << " ; " << std::setw(9) << type2String().toStdString() << " ; " << std::setw(27)<<_itime.toString().toStdString() << " ; " << _message.toStdString() << std::endl;
    if ( frmt == lmCODE) {
        stream << std::setw(4) << _id << " ; " << _line << " : " << _func.toStdString() << " ; " << _file.toStdString() << std::endl;
    }
}

quint64 IssueObject::id() const
{
    return _id;
}

QString IssueObject::type2String() const{
    switch(_itype) {
    case itCritical:
        return "Critical";
    case itError:
        return "Error";
    case itWarning:
        return "Warning";
    case itMessage:
        return "Message";
    case itDebug:
        return "Debug";
    }
    return "Text";
}

//---------------------------------------------------------------------------
IssueLogger::IssueLogger(QObject *parent) : QObject(parent), _repeatCount(0)
{
    QString apploc= context()->ilwisFolder().absoluteFilePath();
    apploc += "/log";
    QDir dir(apploc);
    if ( !dir.exists())
        dir.mkdir(apploc);
    QString rlogFilePath = apploc + "/logfile.txt";
    QString clogFilePath = apploc + "/logfile_ext.txt";
    _logFileRegular.open(rlogFilePath.toLatin1());
    _logFileCode.open(clogFilePath.toLatin1());
}

IssueLogger::~IssueLogger()
{
    if (_logFileCode.is_open())
        _logFileCode.close();
    if ( _logFileRegular.is_open())
        _logFileRegular.close();
}

quint64 IssueLogger::log(const QString &message, int it)
{
    ++_repeatCount;
    std::thread::id id = std::this_thread::get_id();
    if ( _silentThreads.find(id)!= _silentThreads.end() && it != IssueObject::itCritical)
        return i64UNDEF;

    if ( _lastmessage == message && _repeatCount == 10) {
        return _issueId;
    } else {
        // Mechanism to prevent(some) 'stuck in a loop' kind of errors.
        // this should basically be solved at the place the loop is happening but oversights happen.
        // This is a last fallback to break the loop without the need to stop the process
        if ( _repeatCount > 10 && _lastmessage != message ){
            _issues.enqueue(IssueObject(QString("Message repeated %1 times").arg(_repeatCount), it, _issueId));
            throw ErrorObject(QString("Error message cascade : %1").arg(message));
        }
        _repeatCount = 0;
    }

    _issues.enqueue(IssueObject(message, it, _issueId));
    if ( _lastmessage == message)
        return _issueId;
    IssueObject& obj = _issues.back();
    if ( _logFileRegular.is_open()) {
        obj.stream(_logFileRegular, IssueObject::lmREGULAR);
    }
    emit ilwiserrormessage(obj.logMessage());

    _lastmessage = message;
    return _issueId++;
}

quint64 IssueLogger::log(const QString& objectName, const QString &message, int it)
{
    QString newmessage = objectName + ":" + message;
    return log(newmessage, it);
}

void IssueLogger::addCodeInfo(quint64 issueid, int line, const QString &func, const QString &file)
{
    for(auto iter=_issues.begin(); iter != _issues.end(); ++iter) {
        IssueObject& issue = *iter;
        if ( issue.id() == issueid) {
            issue.addCodeInfo(line, func, file);
            if ( _logFileCode.is_open()) {
                issue.stream(_logFileCode, IssueObject::lmCODE);
            }
            break;
        }
    }
}

bool IssueLogger::silent() const
{
    std::thread::id id = std::this_thread::get_id();
    auto iter = _silentThreads.find(id);
    if ( iter != _silentThreads.end())
        return iter->second;
    return false;
}

void IssueLogger::silent(bool yesno)
{
    std::thread::id id = std::this_thread::get_id();
    if ( yesno == false){
        auto iter = _silentThreads.find(id) ;
        if (iter != _silentThreads.end())
            _silentThreads.erase(iter);
    }else
        _silentThreads[id] = true;
}

quint64 IssueLogger::logSql(const QSqlError &err)
{
   return log(err.text(), IssueObject::itError);
}

IssueObject::IssueType IssueLogger::maxIssueLevel() const
{
    int type = IssueObject::itNone;
    foreach(IssueObject issue, _issues) {
        type |= issue.type();
    }
    if ( type & IssueObject::itCritical)
        return IssueObject::itCritical;
    if ( type & IssueObject::itError)
        return IssueObject::itError;
    if ( type & IssueObject::itWarning)
        return IssueObject::itWarning;
    if ( type & IssueObject::itMessage)
        return IssueObject::itMessage;
    return IssueObject::itNone;
}

void IssueLogger::copy(IssueLogger &other)
{
  foreach(IssueObject issue, _issues) {
      other._issues.enqueue(issue);
  }
}

QString IssueLogger::popfirst(int tp) {
    if ( tp != IssueObject::itAll){
        for(auto iter= --_issues.end(); iter != _issues.begin(); --iter ){
            if (hasType((*iter).type(), tp)){
                QString mes = (*iter).message();
                _issues.erase(iter);
                return mes;
            }
        }
    }
    if ( _issues.size() > 0)
        return _issues.dequeue().message();
    return "?";
}

QString IssueLogger::poplast(int tp) {
    if ( tp != IssueObject::itAll){
        for(auto iter= _issues.begin(); iter != _issues.end(); ++iter ){
            if (hasType((*iter).type(), tp)){
                QString mes = (*iter).message();
                _issues.erase(iter);
                return mes;
            }
        }
    }
    if ( _issues.size() >0 )
        return _issues.takeLast().message();
    return "?";
}

void IssueLogger::clear() {
    _issues.clear();
}

<|endoftext|>


<commit_before>#ifndef MCMC_TRAITS
#define MCMC_TRAITS
#define MCMC_HEADER
#include <cmath>
#include <cstddef>
namespace mcmc_utilities
{
  /**
     Get the size of an array object
     \param x the array object
     \return the size of the array object
   */
  template <typename T>
  inline size_t get_size(const T& x)
  {
    return x.size();
  }

  /**
     \brief Trait class, in which the types of elements in an array are defined
     \tparam the type of the array object
   */
  template <typename T>
  class element_type_trait
  {
  public:
    /**
       Default definition of element_type
     */
    typedef typename T::value_type element_type;
  };

  /**
     \brief The return type trait of some certain data types.
  */
  template <typename T>
  class return_type_trait
  {
  public:
    typedef T value_type;
    typedef T& reference_type;
    typedef const T& const_reference_type;
  };

  /**
     Help function to get the i-th element from an array
     \tparam T the type of the array object
     \param x the array object
     \param i the order of the element
     \return the fetched element value, const reference
   */
  template <typename T>
  inline typename
  return_type_trait<typename element_type_trait<T>::element_type>::
  const_reference_type get_element(const T& x,size_t i)
  {
    return x[i];
  }

  /**
     set ths i-th element by a given value
     \tparam T the type of the array object
     \tparam Tx the type of the element
     \param x the array object
     \param i the order of the element
     \param v the value of the element to be set
   */
  template<typename T,typename TX>
  inline void set_element(T& x,size_t i,
			  const TX& v)
  {
    x[i]=v;
  }

  template <typename T,typename TX>
  inline void push_back(T& x,const TX& v)
  {
    x.push_back(v);
  }

  template <typename T>
  inline typename return_type_trait<typename element_type_trait<T>::element_type>::
  const_reference_type last_element(const T& x)
  {
    return x.back();
  }

  template <typename T>
  inline typename return_type_trait<typename element_type_trait<T>::element_type>::
  reference_type last_element(T& x)
  {
    return x.back();
  }

  /**
     resize an array object
     \tparam T the type of the array
     \param x the array object
     \param s the new size
   */
  template <typename T>
  inline void resize(T& x,size_t s)
  {
    x.resize(s);
  }

  template <typename T>
  inline void reserve(T& x,size_t s)
  {
    x.reserve(s);
  }

  /**
     Assignment operator of two array objects
     \tparam Tl the type of left-hand array
     \tparam Tr the type of right-hand array
     \param lhs the left-hand array
     \param rhs the right-hand array
     \return the reference of the left-hand array
   */
  template <typename Tl,typename Tr>
  inline Tl& mcmc_assign(Tl& lhs,const Tr& rhs)
  {
    return (lhs=rhs);
  }

  template <typename T>
  constexpr T C_ONE()
  {
    return static_cast<T>(1);
  }

  template <typename T>
  constexpr T C_ZERO()
  {
    return static_cast<T>(0);
  }

  template <typename T,unsigned int N>
  constexpr T C_N2T()
  {
    return static_cast<T>(N);
  }

  template <typename T>
  constexpr T C_NAN()
  {
    return static_cast<T>(std::nan(""));
  }
}

#endif
<commit_msg>	modified:   core/mcmc_traits.hpp<commit_after>#ifndef MCMC_TRAITS
#define MCMC_TRAITS
#define MCMC_HEADER
#include <cmath>
#include <cstddef>
namespace mcmc_utilities
{
  /**
     Get the size of an array object
     \param x the array object
     \return the size of the array object
   */
  template <typename T>
  inline size_t get_size(const T& x)
  {
    return x.size();
  }

  /**
     \brief Trait class, in which the types of elements in an array are defined
     \tparam the type of the array object
   */
  template <typename T>
  class element_type_trait
  {
  public:
    /**
       Default definition of element_type
     */
    typedef typename T::value_type element_type;
  };

  /**
     \brief The return type trait of some certain data types.
  */
  template <typename T>
  class return_type_trait
  {
  public:
    typedef T value_type;
    typedef T& reference_type;
    typedef const T& const_reference_type;
  };

  /**
     Help function to get the i-th element from an array
     \tparam T the type of the array object
     \param x the array object
     \param i the order of the element
     \return the fetched element value, const reference
   */
  template <typename T>
  inline typename
  return_type_trait<typename element_type_trait<T>::element_type>::
  const_reference_type get_element(const T& x,size_t i)
  {
    return x[i];
  }

  /**
     set ths i-th element by a given value
     \tparam T the type of the array object
     \tparam Tx the type of the element
     \param x the array object
     \param i the order of the element
     \param v the value of the element to be set
   */
  template<typename T,typename TX>
  inline void set_element(T& x,size_t i,
			  const TX& v)
  {
    x[i]=v;
  }

  template <typename T,typename TX>
  inline void push_back(T& x,const TX& v)
  {
    x.push_back(v);
  }

  template <typename T>
  inline typename return_type_trait<typename element_type_trait<T>::element_type>::
  const_reference_type last_element(const T& x)
  {
    return x.back();
  }

  template <typename T>
  inline typename return_type_trait<typename element_type_trait<T>::element_type>::
  reference_type last_element(T& x)
  {
    return x.back();
  }

  /**
     resize an array object
     \tparam T the type of the array
     \param x the array object
     \param s the new size
   */
  template <typename T>
  inline void resize(T& x,size_t s)
  {
    x.resize(s);
  }

  template <typename T>
  inline void reserve(T& x,size_t s)
  {
    x.reserve(s);
  }

  /**
     Assignment operator of two array objects
     \tparam Tl the type of left-hand array
     \tparam Tr the type of right-hand array
     \param lhs the left-hand array
     \param rhs the right-hand array
     \return the reference of the left-hand array
   */
  template <typename Tl,typename Tr>
  inline Tl& mcmc_assign(Tl& lhs,const Tr& rhs)
  {
    return (lhs=rhs);
  }

  template <typename T>
  constexpr T C_ONE()
  {
    return static_cast<T>(1);
  }

  template <typename T>
  constexpr T C_ZERO()
  {
    return static_cast<T>(0);
  }

  template <typename T,unsigned int N>
  constexpr T C_N2T()
  {
    return static_cast<T>(N);
  }

  template <typename T>
  constexpr T C_NAN()
  {
    //return static_cast<T>(std::nan(""));
    return static_cast<T>(NAN);
  }
}

#endif
<|endoftext|>


<commit_before>/*
    Copyright (C) 1998 by Jorrit Tyberghein

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public
    License along with this library; if not, write to the Free
    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include "cssys/csshlib.h"

#include <windows.h>

csLibraryHandle csLoadLibrary (const char* szLibName)
{
  return LoadLibrary (szLibName);
}

void* csGetLibrarySymbol(csLibraryHandle Handle, const char* Name)
{
  void* ptr=GetProcAddress ((HMODULE)Handle, Name);
  if(!ptr) {
    char *Name2;
    Name2=new char[strlen(Name)+2];
    strcpy(Name2, "_");
    strcat(Name2, Name);
    ptr=GetProcAddress ((HMODULE)Handle, Name2);
    delete [] Name2;
  }
  return ptr;
}

bool csUnloadLibrary (csLibraryHandle Handle)
{
  return FreeLibrary ((HMODULE)Handle)!=0;
}
<commit_msg>Now includes sysdef.h in order to eliminate some warnings from windows.h under VC5.<commit_after>/*
    Copyright (C) 1998 by Jorrit Tyberghein

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public
    License along with this library; if not, write to the Free
    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include "sysdef.h"
#include "cssys/csshlib.h"

#include <windows.h>

csLibraryHandle csLoadLibrary (const char* szLibName)
{
  return LoadLibrary (szLibName);
}

void* csGetLibrarySymbol(csLibraryHandle Handle, const char* Name)
{
  void* ptr=GetProcAddress ((HMODULE)Handle, Name);
  if(!ptr) {
    char *Name2;
    Name2=new char[strlen(Name)+2];
    strcpy(Name2, "_");
    strcat(Name2, Name);
    ptr=GetProcAddress ((HMODULE)Handle, Name2);
    delete [] Name2;
  }
  return ptr;
}

bool csUnloadLibrary (csLibraryHandle Handle)
{
  return FreeLibrary ((HMODULE)Handle)!=0;
}
<|endoftext|>


<commit_before>#pragma once
#include <iterator>
#include <memory>

#include "TimingTag.hpp"
#include "tatum_range.hpp"

namespace tatum {

/**
 * The 'TimingTags' class represents a collection of timing tags (see the 'TimingTag' class)
 * that belong to a particular node in the timing graph.
 *
 * Any operations performed using this task generally consider *all* associated tags.
 * For example, preforming a max_arr() call will apply the max accross all tags with matching
 * clock domain.  If no matching tag is found, the tag will be added to the set of tags.
 *
 * Implementation
 * ====================
 * Since each node in the timing graph typically has only a few tags (usually 1 or 2), we
 * perform linear searches to find match tags and tag ranges.
 *
 * Note that to allow efficient iteration of tag ranges (by type) we ensure that tags of the
 * same type are adjacent in the storage vector (i.e. the vector is sorted by type)
 */
class TimingTags {
    public:
        template<class T>
        class Iterator;
    private:
        //In practice the vast majority of nodes have only two or one
        //tags, so we reserve space for two to avoid costly memory
        //allocations
        constexpr static size_t DEFAULT_TAGS_TO_RESERVE = 3;
        constexpr static size_t GROWTH_FACTOR = 2;

    public:

        typedef Iterator<TimingTag> iterator;
        typedef Iterator<const TimingTag> const_iterator;

        typedef tatum::util::Range<const_iterator> tag_range;

    public:

        //Constructors
        TimingTags(size_t num_reserve=DEFAULT_TAGS_TO_RESERVE);
        TimingTags(const TimingTags&);
        TimingTags(TimingTags&&);
        TimingTags& operator=(TimingTags);
        ~TimingTags() = default;
        friend void swap(TimingTags& lhs, TimingTags& rhs);

        /*
         * Getters
         */
        ///\returns The number of timing tags in this set
        size_t size() const;
        bool empty() const { return size() == 0; }

        ///\returns A range of all tags
        tag_range tags() const;

        ///\returns A range of all tags matching type
        tag_range tags(const TagType type) const;

        /*
         * Modifiers
         */
        ///Adds a TimingTag to the current set provided it has a valid clock domain
        ///\param tag_pool The pool memory allocator used to allocate the tag
        ///\param src_tag The source tag who is inserted. Note that the src_tag is copied when inserted (the original is unchanged)
        void add_tag(const TimingTag& src_tag);

        /*
         * Operations
         */
        ///Updates the arrival time of this set of tags to be the maximum.
        ///\param new_time The new arrival time to compare against
        ///\param base_tag The associated metat-data for new_time
        ///\remark Finds (or creates) the tag with the same clock domain as base_tag and update the arrival time if new_time is larger
        void max(const Time& new_time, const TimingTag& base_tag, bool arr_must_be_valid=false);

        ///Updates the required time of this set of tags to be the minimum.
        ///\param new_time The new arrival time to compare against
        ///\param base_tag The associated metat-data for new_time
        ///\remark Finds (or creates) the tag with the same clock domain as base_tag and update the required time if new_time is smaller
        void min(const Time& new_time, const TimingTag& base_tag, bool arr_must_be_valid=false);

        ///Clears the tags in the current set
        void clear();

    public:

        //Iterator definition
        template<class T>
        class Iterator : public std::iterator<std::random_access_iterator_tag, T> {
            friend TimingTags;
            public:
                using value_type = typename std::iterator<std::random_access_iterator_tag, T>::value_type;
                using difference_type = typename std::iterator<std::random_access_iterator_tag, T>::difference_type;
                using pointer = typename std::iterator<std::random_access_iterator_tag, T>::pointer;
                using reference = typename std::iterator<std::random_access_iterator_tag, T>::reference;
                using iterator_category = typename std::iterator<std::random_access_iterator_tag, T>::iterator_category;
            public:
                Iterator(): p_(nullptr) {}
                Iterator(pointer p): p_(p) {}
                Iterator(const Iterator& other): p_(other.p_) {}
                Iterator& operator=(const Iterator& other) { p_ = other.p_; return *this; }

                friend bool operator==(Iterator a, Iterator b) { return a.p_ == b.p_; }
                friend bool operator!=(Iterator a, Iterator b) { return a.p_ != b.p_; }

                reference operator*() { return *p_; }
                pointer operator->() { return p_; }
                reference operator[](size_t n) { return *(p_ + n); }

                Iterator& operator++() { ++p_; return *this; }
                Iterator operator++(int) { Iterator old = *this; ++p_; return old; }
                Iterator& operator--() { --p_; return *this; }
                Iterator operator--(int) { Iterator old = *this; --p_; return old; }
                Iterator& operator+=(size_t n) { p_ += n; return *this; }
                Iterator& operator-=(size_t n) { p_ -= n; return *this; }
                friend Iterator operator+(Iterator lhs, size_t rhs) { return lhs += rhs; }
                friend Iterator operator-(Iterator lhs, size_t rhs) { return lhs += rhs; }

                friend difference_type operator-(const Iterator lhs, const Iterator rhs) { return lhs.p_ - rhs.p_; }

                friend bool operator<(Iterator lhs, Iterator rhs) { return lhs.p_ < rhs.p_; }
                friend bool operator>(Iterator lhs, Iterator rhs) { return lhs.p_ > rhs.p_; }
                friend bool operator<=(Iterator lhs, Iterator rhs) { return lhs.p_ <= rhs.p_; }
                friend bool operator>=(Iterator lhs, Iterator rhs) { return lhs.p_ >= rhs.p_; }
                friend void swap(Iterator lhs, Iterator rhs) { std::swap(lhs.p_, rhs.p_); }
            private:
                T* p_ = nullptr;
        };

    private:

        ///\returns An iterator to the first tag in the current set
        iterator begin();
        const_iterator begin() const;
        iterator begin(TagType type);
        const_iterator begin(TagType type) const;

        ///\returns An iterator 'one-past-the-end' of the current set
        iterator end();
        const_iterator end() const;
        iterator end(TagType type);
        const_iterator end(TagType type) const;

        size_t capacity() const;

        std::pair<iterator,bool> find_matching_tag(const TimingTag& tag, bool arr_must_be_valid);

        ///Finds a TimingTag in the current set that has clock domain id matching domain_id
        ///\returns An iterator to the tag if found, or end(tag.type()) if not found
        std::pair<iterator,bool> find_matching_tag(const TimingTag& tag);

        //Find a TimingTag matching the specified DATA_REQUIRED tag provided there is a valid associated
        //DATA_ARRIVAL tag
        std::pair<iterator,bool> find_matching_tag_with_valid_arrival(const TimingTag& tag);

        iterator insert(iterator iter, const TimingTag& tag);
        void grow_insert(size_t index, const TimingTag& tag);

        void increment_size(TagType type);

    private:
        //We don't expect many tags in a node so unsigned short's/unsigned char's
        //should be more than sufficient. This also allows the class
        //to be packed down to 16 bytes (8 for counters, 8 for pointer)
        //
        //In its current configuration we can store at most:
        //  65536           total tags (size_ and capacity_)
        //  256             clock launch tags (num_clock_launch_tags_)
        //  256             clock capture tags (num_clock_capture_tags_)
        //  256             data arrival tags (num_data_arrival_tags_)
        //  (65536 - 3*256) data required tags (size_ - num_*)
        unsigned short size_ = 0;
        unsigned short capacity_ = 0;
        unsigned char num_clock_launch_tags_ = 0;
        unsigned char num_clock_capture_tags_ = 0;
        unsigned char num_data_arrival_tags_ = 0;
        std::unique_ptr<TimingTag[]> tags_;

};

} //namepsace

//Implementation
#include "TimingTags.inl"
<commit_msg>Fix iterator subtraction<commit_after>#pragma once
#include <iterator>
#include <memory>

#include "TimingTag.hpp"
#include "tatum_range.hpp"

namespace tatum {

/**
 * The 'TimingTags' class represents a collection of timing tags (see the 'TimingTag' class)
 * that belong to a particular node in the timing graph.
 *
 * Any operations performed using this task generally consider *all* associated tags.
 * For example, preforming a max_arr() call will apply the max accross all tags with matching
 * clock domain.  If no matching tag is found, the tag will be added to the set of tags.
 *
 * Implementation
 * ====================
 * Since each node in the timing graph typically has only a few tags (usually 1 or 2), we
 * perform linear searches to find match tags and tag ranges.
 *
 * Note that to allow efficient iteration of tag ranges (by type) we ensure that tags of the
 * same type are adjacent in the storage vector (i.e. the vector is sorted by type)
 */
class TimingTags {
    public:
        template<class T>
        class Iterator;
    private:
        //In practice the vast majority of nodes have only a handful of tags,
        //so we reserve space for some to avoid costly memory allocations
        constexpr static size_t DEFAULT_TAGS_TO_RESERVE = 3;
        constexpr static size_t GROWTH_FACTOR = 2;

    public:

        typedef Iterator<TimingTag> iterator;
        typedef Iterator<const TimingTag> const_iterator;

        typedef tatum::util::Range<const_iterator> tag_range;

    public:

        //Constructors
        TimingTags(size_t num_reserve=DEFAULT_TAGS_TO_RESERVE);
        TimingTags(const TimingTags&);
        TimingTags(TimingTags&&);
        TimingTags& operator=(TimingTags);
        ~TimingTags() = default;
        friend void swap(TimingTags& lhs, TimingTags& rhs);

        /*
         * Getters
         */
        ///\returns The number of timing tags in this set
        size_t size() const;
        bool empty() const { return size() == 0; }

        ///\returns A range of all tags
        tag_range tags() const;

        ///\returns A range of all tags matching type
        tag_range tags(const TagType type) const;

        /*
         * Modifiers
         */
        ///Adds a TimingTag to the current set provided it has a valid clock domain
        ///\param tag_pool The pool memory allocator used to allocate the tag
        ///\param src_tag The source tag who is inserted. Note that the src_tag is copied when inserted (the original is unchanged)
        void add_tag(const TimingTag& src_tag);

        /*
         * Operations
         */
        ///Updates the arrival time of this set of tags to be the maximum.
        ///\param new_time The new arrival time to compare against
        ///\param base_tag The associated metat-data for new_time
        ///\remark Finds (or creates) the tag with the same clock domain as base_tag and update the arrival time if new_time is larger
        void max(const Time& new_time, const TimingTag& base_tag, bool arr_must_be_valid=false);

        ///Updates the required time of this set of tags to be the minimum.
        ///\param new_time The new arrival time to compare against
        ///\param base_tag The associated metat-data for new_time
        ///\remark Finds (or creates) the tag with the same clock domain as base_tag and update the required time if new_time is smaller
        void min(const Time& new_time, const TimingTag& base_tag, bool arr_must_be_valid=false);

        ///Clears the tags in the current set
        void clear();

    public:

        //Iterator definition
        template<class T>
        class Iterator : public std::iterator<std::random_access_iterator_tag, T> {
            friend TimingTags;
            public:
                using value_type = typename std::iterator<std::random_access_iterator_tag, T>::value_type;
                using difference_type = typename std::iterator<std::random_access_iterator_tag, T>::difference_type;
                using pointer = typename std::iterator<std::random_access_iterator_tag, T>::pointer;
                using reference = typename std::iterator<std::random_access_iterator_tag, T>::reference;
                using iterator_category = typename std::iterator<std::random_access_iterator_tag, T>::iterator_category;
            public:
                Iterator(): p_(nullptr) {}
                Iterator(pointer p): p_(p) {}
                Iterator(const Iterator& other): p_(other.p_) {}
                Iterator& operator=(const Iterator& other) { p_ = other.p_; return *this; }

                friend bool operator==(Iterator a, Iterator b) { return a.p_ == b.p_; }
                friend bool operator!=(Iterator a, Iterator b) { return a.p_ != b.p_; }

                reference operator*() { return *p_; }
                pointer operator->() { return p_; }
                reference operator[](size_t n) { return *(p_ + n); }

                Iterator& operator++() { ++p_; return *this; }
                Iterator operator++(int) { Iterator old = *this; ++p_; return old; }
                Iterator& operator--() { --p_; return *this; }
                Iterator operator--(int) { Iterator old = *this; --p_; return old; }
                Iterator& operator+=(size_t n) { p_ += n; return *this; }
                Iterator& operator-=(size_t n) { p_ -= n; return *this; }
                friend Iterator operator+(Iterator lhs, size_t rhs) { return lhs += rhs; }
                friend Iterator operator-(Iterator lhs, size_t rhs) { return lhs -= rhs; }

                friend difference_type operator-(const Iterator lhs, const Iterator rhs) { return lhs.p_ - rhs.p_; }

                friend bool operator<(Iterator lhs, Iterator rhs) { return lhs.p_ < rhs.p_; }
                friend bool operator>(Iterator lhs, Iterator rhs) { return lhs.p_ > rhs.p_; }
                friend bool operator<=(Iterator lhs, Iterator rhs) { return lhs.p_ <= rhs.p_; }
                friend bool operator>=(Iterator lhs, Iterator rhs) { return lhs.p_ >= rhs.p_; }
                friend void swap(Iterator lhs, Iterator rhs) { std::swap(lhs.p_, rhs.p_); }
            private:
                T* p_ = nullptr;
        };

    private:

        ///\returns An iterator to the first tag in the current set
        iterator begin();
        const_iterator begin() const;
        iterator begin(TagType type);
        const_iterator begin(TagType type) const;

        ///\returns An iterator 'one-past-the-end' of the current set
        iterator end();
        const_iterator end() const;
        iterator end(TagType type);
        const_iterator end(TagType type) const;

        size_t capacity() const;

        std::pair<iterator,bool> find_matching_tag(const TimingTag& tag, bool arr_must_be_valid);

        ///Finds a TimingTag in the current set that has clock domain id matching domain_id
        ///\returns An iterator to the tag if found, or end(tag.type()) if not found
        std::pair<iterator,bool> find_matching_tag(const TimingTag& tag);

        //Find a TimingTag matching the specified DATA_REQUIRED tag provided there is a valid associated
        //DATA_ARRIVAL tag
        std::pair<iterator,bool> find_matching_tag_with_valid_arrival(const TimingTag& tag);

        iterator insert(iterator iter, const TimingTag& tag);
        void grow_insert(size_t index, const TimingTag& tag);

        void increment_size(TagType type);

    private:
        //We don't expect many tags in a node so unsigned short's/unsigned char's
        //should be more than sufficient. This also allows the class
        //to be packed down to 16 bytes (8 for counters, 8 for pointer)
        //
        //In its current configuration we can store at most:
        //  65536           total tags (size_ and capacity_)
        //  256             clock launch tags (num_clock_launch_tags_)
        //  256             clock capture tags (num_clock_capture_tags_)
        //  256             data arrival tags (num_data_arrival_tags_)
        //  (65536 - 3*256) data required tags (size_ - num_*)
        unsigned short size_ = 0;
        unsigned short capacity_ = 0;
        unsigned char num_clock_launch_tags_ = 0;
        unsigned char num_clock_capture_tags_ = 0;
        unsigned char num_data_arrival_tags_ = 0;
        std::unique_ptr<TimingTag[]> tags_;

};

} //namepsace

//Implementation
#include "TimingTags.inl"
<|endoftext|>


<commit_before>// Copyright (c) 2013 Maciej Gajewski

#ifndef COROUTINES_MUTEX_HPP
#define COROUTINES_MUTEX_HPP

#include "profiling/profiling.hpp"

#include <mutex>
#include <atomic>

namespace coroutines {

class spinlock
{
public:

    spinlock()
    : _flag(ATOMIC_FLAG_INIT)
    { }

    spinlock(const char* name)
    : _flag(ATOMIC_FLAG_INIT)
    {
        #ifdef COROUTINES_SPINLOCKS_PROFILING
            CORO_PROF("spinlock", this, "created", name);
        #else
            (void)name;
        #endif
    }

    void lock()
    {
        #ifdef COROUTINES_SPINLOCKS_PROFILING
            // only report contested lock events
            if (try_lock())
                return;
            CORO_PROF("spinlock", this, "spinning begin");
        #endif
        while(_flag.test_and_set(std::memory_order_acquire))
            ; // spin
        #ifdef COROUTINES_SPINLOCKS_PROFILING
            CORO_PROF("spinlock", this, "spinning end");
        #endif
    }

    bool try_lock()
    {
        #ifdef COROUTINES_SPINLOCKS_PROFILING
            if (!_flag.test_and_set(std::memory_order_acquire))
            {
                CORO_PROF("spinlock", this, "locked");
                return true;
            }
            else
                return false;
        #else
            return !_flag.test_and_set(std::memory_order_acquire);
        #endif
    }

    void unlock()
    {
        #ifdef COROUTINES_SPINLOCKS_PROFILING
            CORO_PROF("spinlock", this, "unlocked");
        #endif
        _flag.clear(std::memory_order_release);
    }

private:

    std::atomic_flag _flag;
};

//typedef std::mutex mutex;
typedef spinlock mutex;

}

#endif
<commit_msg>rw_spinlock code added, now its time for testing<commit_after>// Copyright (c) 2013 Maciej Gajewski

#ifndef COROUTINES_MUTEX_HPP
#define COROUTINES_MUTEX_HPP

#include "profiling/profiling.hpp"

#include <mutex>
#include <atomic>
#include <cstdint>

namespace coroutines {

class spinlock
{
public:

    spinlock()
    : _flag(ATOMIC_FLAG_INIT)
    { }

    spinlock(const char* name)
    : _flag(ATOMIC_FLAG_INIT)
    {
        #ifdef COROUTINES_SPINLOCKS_PROFILING
            CORO_PROF("spinlock", this, "created", name);
        #else
            (void)name;
        #endif
    }

    void lock()
    {
        #ifdef COROUTINES_SPINLOCKS_PROFILING
            // only report contested lock events
            if (try_lock())
                return;
            CORO_PROF("spinlock", this, "spinning begin");
        #endif
        while(_flag.test_and_set(std::memory_order_acquire))
            ; // spin
        #ifdef COROUTINES_SPINLOCKS_PROFILING
            CORO_PROF("spinlock", this, "spinning end");
        #endif
    }

    bool try_lock()
    {
        #ifdef COROUTINES_SPINLOCKS_PROFILING
            if (!_flag.test_and_set(std::memory_order_acquire))
            {
                CORO_PROF("spinlock", this, "locked");
                return true;
            }
            else
                return false;
        #else
            return !_flag.test_and_set(std::memory_order_acquire);
        #endif
    }

    void unlock()
    {
        #ifdef COROUTINES_SPINLOCKS_PROFILING
            CORO_PROF("spinlock", this, "unlocked");
        #endif
        _flag.clear(std::memory_order_release);
    }

private:

    std::atomic_flag _flag;
};

//typedef std::mutex mutex;
typedef spinlock mutex;

// based on folly's RWSpinLock
class rw_spinlock
{
    enum : std::int32_t { READER = 4, UPGRADED = 2, WRITER = 1 };

public:
    rw_spinlock() : _bits(0) {}

    void lock()
    {
        while (!try_lock())
            ;
    }

    // Writer is responsible for clearing up both the UPGRADED and WRITER bits.
    void unlock()
    {
        static_assert(READER > WRITER + UPGRADED, "wrong bits!");
        _bits.fetch_and(~(WRITER | UPGRADED), std::memory_order_release);
    }

    // SharedLockable Concept
    void lock_shared()
    {
        while (try_lock_shared())
            ;
    }

    void unlock_shared()
    {
        _bits.fetch_add(-READER, std::memory_order_release);
    }

    // Downgrade the lock from writer status to reader status.
    void unlock_and_lock_shared()
    {
        _bits.fetch_add(READER, std::memory_order_acquire);
        unlock();
    }

    // UpgradeLockable Concept
    void lock_upgrade()
    {
        while (!try_lock_upgrade())
            ;
    }

    void unlock_upgrade()
    {
        _bits.fetch_add(-UPGRADED, std::memory_order_acq_rel);
    }

    // unlock upgrade and try to acquire write lock
    void unlock_upgrade_and_lock()
    {
        while (!try_unlock_upgrade_and_lock())
            ;
    }

    // unlock upgrade and read lock atomically
    void unlock_upgrade_and_lock_shared()
    {
        _bits.fetch_add(READER - UPGRADED, std::memory_order_acq_rel);
    }

    // write unlock and upgrade lock atomically
    void unlock_and_lock_upgrade()
    {
        // need to do it in two steps here -- as the UPGRADED bit might be OR-ed at
        // the same time when other threads are trying do try_lock_upgrade().
        _bits.fetch_or(UPGRADED, std::memory_order_acquire);
        _bits.fetch_add(-WRITER, std::memory_order_release);
    }

    // Attempt to acquire writer permission. Return false if we didn't get it.
    bool try_lock()
    {
        std::int32_t expect = 0;
        return _bits.compare_exchange_strong(expect, WRITER, std::memory_order_acq_rel);
    }

    // Try to get reader permission on the lock. This can fail if we
    // find out someone is a writer or upgrader.
    // Setting the UPGRADED bit would allow a writer-to-be to indicate
    // its intention to write and block any new readers while waiting
    // for existing readers to finish and release their read locks. This
    // helps avoid starving writers (promoted from upgraders).
    bool try_lock_shared()
    {
        // fetch_add is considerably (100%) faster than compare_exchange,
        // so here we are optimizing for the common (lock success) case.
        std::int32_t value = _bits.fetch_add(READER, std::memory_order_acquire);
        if (value & (WRITER|UPGRADED))
        {
            _bits.fetch_add(-READER, std::memory_order_release);
            return false;
        }
        return true;
    }

    // try to unlock upgrade and write lock atomically
    bool try_unlock_upgrade_and_lock()
    {
        std::int32_t expect = UPGRADED;
        return _bits.compare_exchange_strong(expect, WRITER, std::memory_order_acq_rel);
    }

    // try to acquire an upgradable lock.
    bool try_lock_upgrade()
    {
        std::int32_t value = _bits.fetch_or(UPGRADED, std::memory_order_acquire);

        // Note: when failed, we cannot flip the UPGRADED bit back,
        // as in this case there is either another upgrade lock or a write lock.
        // If it's a write lock, the bit will get cleared up when that lock's done
        // with unlock().
        return ((value & (UPGRADED | WRITER)) == 0);
    }

private:

    std::atomic<int32_t> _bits;
};

}

#endif
<|endoftext|>


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

#include "webkit/plugins/ppapi/ppb_nacl_private_impl.h"

#include "base/rand_util_c.h"
#include "ppapi/c/private/ppb_nacl_private.h"
#include "webkit/glue/webkit_glue.h"

namespace webkit {
namespace ppapi {

namespace {

bool LaunchSelLdr(const char* alleged_url, int socket_count,
                  void* imc_handles, void* nacl_process_handle,
                  int* nacl_process_id) {
#if !defined(DISABLE_NACL)
  return webkit_glue::LaunchSelLdr(alleged_url, socket_count, imc_handles,
                                   nacl_process_handle, nacl_process_id);
#else
  return 0;
#endif
}

int UrandomFD(void) {
#if defined(OS_POSIX)
  return GetUrandomFD();
#else
  return 0;
#endif
}

}  // namespace

const PPB_NaCl_Private ppb_nacl = {
  &LaunchSelLdr,
  &UrandomFD,
};

// static
const PPB_NaCl_Private* PPB_NaCl_Private_Impl::GetInterface() {
  return &ppb_nacl;
}

}  // namespace ppapi
}  // namespace webkit
<commit_msg>By zero, I mean false<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "webkit/plugins/ppapi/ppb_nacl_private_impl.h"

#include "base/rand_util_c.h"
#include "ppapi/c/private/ppb_nacl_private.h"
#include "webkit/glue/webkit_glue.h"

namespace webkit {
namespace ppapi {

namespace {

bool LaunchSelLdr(const char* alleged_url, int socket_count,
                  void* imc_handles, void* nacl_process_handle,
                  int* nacl_process_id) {
#if !defined(DISABLE_NACL)
  return webkit_glue::LaunchSelLdr(alleged_url, socket_count, imc_handles,
                                   nacl_process_handle, nacl_process_id);
#else
  return false;
#endif
}

int UrandomFD(void) {
#if defined(OS_POSIX)
  return GetUrandomFD();
#else
  return 0;
#endif
}

}  // namespace

const PPB_NaCl_Private ppb_nacl = {
  &LaunchSelLdr,
  &UrandomFD,
};

// static
const PPB_NaCl_Private* PPB_NaCl_Private_Impl::GetInterface() {
  return &ppb_nacl;
}

}  // namespace ppapi
}  // namespace webkit
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2010 Digital Bazaar, Inc. All rights reserved.
 */
#define __STDC_FORMAT_MACROS
#define __STDC_LIMIT_MACROS
#define __STDC_CONSTANT_MACROS

#include "monarch/ws/WebServer.h"

#include "monarch/crypto/AsymmetricKeyFactory.h"
#include "monarch/data/json/JsonWriter.h"
#include "monarch/logging/Logging.h"
#include "monarch/net/NullSocketDataPresenter.h"
#include "monarch/net/SslSocketDataPresenter.h"

using namespace std;
using namespace monarch::config;
using namespace monarch::crypto;
using namespace monarch::data::json;
using namespace monarch::http;
using namespace monarch::io;
using namespace monarch::net;
using namespace monarch::rt;
using namespace monarch::util;
using namespace monarch::ws;

WebServer::WebServer() :
   mServer(NULL),
   mHostAddress(NULL),
   mSslContext(NULL),
   mSocketDataPresenterList(NULL),
   mServiceId(Server::sInvalidServiceId)
{
}

WebServer::~WebServer()
{
}

bool WebServer::initialize(Config& cfg)
{
   bool rval = true;

   MO_CAT_DEBUG(MO_WS_CAT, "WebServer initializing...");

   // create default container if one is not set
   if(mContainer.isNull())
   {
      mContainer = new WebServiceContainer();
   }

   // get basic config
   // security: on/off/both
   bool secure;
   bool nonSecure;
   const char* security = cfg["security"]->getString();
   if(strcasecmp(security, "on") == 0)
   {
      secure = true;
      nonSecure = false;
   }
   else if(strcasecmp(security, "off") == 0)
   {
      secure = false;
      nonSecure = true;
   }
   else
   {
      secure = nonSecure = true;
   }

   if(secure)
   {
      MO_CAT_DEBUG(MO_WS_CAT, "WebServer enabling SSL...");

      // FIXME: make configurable
      /* Create SSL server context. "TLS" is most secure and recent SSL but we
         must use "ALL" to handle browsers that use SSL 3.0. */
      mSslContext = new SslContext("ALL", false);

      // setup certificate file and private key
      File certFile(cfg["certificate"]->getString());
      File pkeyFile(cfg["privateKey"]->getString());

      MO_CAT_DEBUG(MO_WS_CAT,
         "WebServer setting SSL certificate and private key...");

      // set certificate and private key for SSL context
      rval =
         mSslContext->setCertificate(certFile) &&
         mSslContext->setPrivateKey(pkeyFile);
      if(rval)
      {
         MO_CAT_DEBUG(MO_WS_CAT, "WebServer reading SSL certificate...");

         // set default virtual host based on certificate common name
         ByteBuffer b(certFile->getLength());
         rval = certFile.readBytes(&b);
         if(rval)
         {
            MO_CAT_DEBUG(MO_WS_CAT,
               "WebServer loading SSL certificate from PEM...");

            AsymmetricKeyFactory afk;
            X509CertificateRef cert = afk.loadCertificateFromPem(
               b.data(), b.length());
            rval = !cert.isNull();
            if(rval)
            {
               DynamicObject subject = cert->getSubject();
               string commonName = cert->getField(subject, "CN");
               MO_CAT_DEBUG(MO_WS_CAT,
                  "Setting default virtual host to common name: %s",
                  commonName.c_str());
               mSslContext->setVirtualHost(commonName.c_str());
            }
         }
      }

      MO_CAT_DEBUG(MO_WS_CAT, "WebServer SSL setup complete.");
   }

   if(rval)
   {
      // setup host address
      const char* host = cfg["host"]->getString();
      uint32_t port = cfg["port"]->getUInt32();
      mHostAddress = new InternetAddress(host, port);

      // handle socket presentation layer
      mSocketDataPresenterList = new SocketDataPresenterList(true);
      if(secure)
      {
         SslSocketDataPresenter* ssdp =
            new SslSocketDataPresenter(&(*mSslContext));
         mSocketDataPresenterList->add(ssdp);
      }
      if(nonSecure)
      {
         NullSocketDataPresenter* nsdp = new NullSocketDataPresenter();
         mSocketDataPresenterList->add(nsdp);
      }

      // get the list of default domains
      DynamicObject domains(NULL);
      if(cfg->hasMember("domains"))
      {
         domains = cfg["domains"].clone();
         if(domains->length() == 0)
         {
            // add wildcard if no domains specified
            domains->append() = "*";
         }
      }
      else
      {
         // no specified default domains, so use "*"
         domains = DynamicObject();
         domains->append() = "*";
      }
      mContainer->setDefaultDomains(domains);

      MO_CAT_INFO(MO_WS_CAT, "WebServer running web services on domains: %s",
         JsonWriter::writeToString(domains, false, false).c_str());
   }

   if(rval)
   {
      MO_CAT_DEBUG(MO_WS_CAT, "WebServer initialized.");
   }

   return rval;
}

void WebServer::cleanup()
{
   // reset container
   mContainer->clear();
   DynamicObject domains;
   domains->append() = "*";
   mContainer->setDefaultDomains(domains);

   // clean up
   mHostAddress.setNull();
   mSslContext.setNull();
   mSocketDataPresenterList.setNull();
}

bool WebServer::enable(Server* server, const char* name)
{
   bool rval = true;

   // add http connection service
   mServiceId = server->addConnectionService(
      &(*mHostAddress), mContainer->getServicer(),
      &(*mSocketDataPresenterList), name);
   if(mServiceId == Server::sInvalidServiceId)
   {
      // could not add connection service
      rval = false;
   }
   else
   {
      mServer = server;
      MO_CAT_INFO(MO_WS_CAT, "WebServer serving on %s",
         mHostAddress->toString(false).c_str());
   }

   return rval;
}

void WebServer::disable()
{
   // remove http connection service
   if(mServiceId != Server::sInvalidServiceId)
   {
      mServer->removePortService(mServiceId);
      mServiceId = Server::sInvalidServiceId;
      mServer = NULL;
   }
}

void WebServer::setContainer(WebServiceContainerRef& c)
{
   mContainer = c;
}

WebServiceContainerRef& WebServer::getContainer()
{
   return mContainer;
}

InternetAddressRef WebServer::getHostAddress()
{
   return mHostAddress;
}

SslContextRef WebServer::getSslContext()
{
   return mSslContext;
}
<commit_msg>Added WebServer name to log output.<commit_after>/*
 * Copyright (c) 2010 Digital Bazaar, Inc. All rights reserved.
 */
#define __STDC_FORMAT_MACROS
#define __STDC_LIMIT_MACROS
#define __STDC_CONSTANT_MACROS

#include "monarch/ws/WebServer.h"

#include "monarch/crypto/AsymmetricKeyFactory.h"
#include "monarch/data/json/JsonWriter.h"
#include "monarch/logging/Logging.h"
#include "monarch/net/NullSocketDataPresenter.h"
#include "monarch/net/SslSocketDataPresenter.h"

using namespace std;
using namespace monarch::config;
using namespace monarch::crypto;
using namespace monarch::data::json;
using namespace monarch::http;
using namespace monarch::io;
using namespace monarch::net;
using namespace monarch::rt;
using namespace monarch::util;
using namespace monarch::ws;

WebServer::WebServer() :
   mServer(NULL),
   mHostAddress(NULL),
   mSslContext(NULL),
   mSocketDataPresenterList(NULL),
   mServiceId(Server::sInvalidServiceId)
{
}

WebServer::~WebServer()
{
}

bool WebServer::initialize(Config& cfg)
{
   bool rval = true;

   MO_CAT_DEBUG(MO_WS_CAT, "WebServer initializing...");

   // create default container if one is not set
   if(mContainer.isNull())
   {
      mContainer = new WebServiceContainer();
   }

   // get basic config
   // security: on/off/both
   bool secure;
   bool nonSecure;
   const char* security = cfg["security"]->getString();
   if(strcasecmp(security, "on") == 0)
   {
      secure = true;
      nonSecure = false;
   }
   else if(strcasecmp(security, "off") == 0)
   {
      secure = false;
      nonSecure = true;
   }
   else
   {
      secure = nonSecure = true;
   }

   if(secure)
   {
      MO_CAT_DEBUG(MO_WS_CAT, "WebServer enabling SSL...");

      // FIXME: make configurable
      /* Create SSL server context. "TLS" is most secure and recent SSL but we
         must use "ALL" to handle browsers that use SSL 3.0. */
      mSslContext = new SslContext("ALL", false);

      // setup certificate file and private key
      File certFile(cfg["certificate"]->getString());
      File pkeyFile(cfg["privateKey"]->getString());

      MO_CAT_DEBUG(MO_WS_CAT,
         "WebServer setting SSL certificate and private key...");

      // set certificate and private key for SSL context
      rval =
         mSslContext->setCertificate(certFile) &&
         mSslContext->setPrivateKey(pkeyFile);
      if(rval)
      {
         MO_CAT_DEBUG(MO_WS_CAT, "WebServer reading SSL certificate...");

         // set default virtual host based on certificate common name
         ByteBuffer b(certFile->getLength());
         rval = certFile.readBytes(&b);
         if(rval)
         {
            MO_CAT_DEBUG(MO_WS_CAT,
               "WebServer loading SSL certificate from PEM...");

            AsymmetricKeyFactory afk;
            X509CertificateRef cert = afk.loadCertificateFromPem(
               b.data(), b.length());
            rval = !cert.isNull();
            if(rval)
            {
               DynamicObject subject = cert->getSubject();
               string commonName = cert->getField(subject, "CN");
               MO_CAT_DEBUG(MO_WS_CAT,
                  "Setting default virtual host to common name: %s",
                  commonName.c_str());
               mSslContext->setVirtualHost(commonName.c_str());
            }
         }
      }

      MO_CAT_DEBUG(MO_WS_CAT, "WebServer SSL setup complete.");
   }

   if(rval)
   {
      // setup host address
      const char* host = cfg["host"]->getString();
      uint32_t port = cfg["port"]->getUInt32();
      mHostAddress = new InternetAddress(host, port);

      // handle socket presentation layer
      mSocketDataPresenterList = new SocketDataPresenterList(true);
      if(secure)
      {
         SslSocketDataPresenter* ssdp =
            new SslSocketDataPresenter(&(*mSslContext));
         mSocketDataPresenterList->add(ssdp);
      }
      if(nonSecure)
      {
         NullSocketDataPresenter* nsdp = new NullSocketDataPresenter();
         mSocketDataPresenterList->add(nsdp);
      }

      // get the list of default domains
      DynamicObject domains(NULL);
      if(cfg->hasMember("domains"))
      {
         domains = cfg["domains"].clone();
         if(domains->length() == 0)
         {
            // add wildcard if no domains specified
            domains->append() = "*";
         }
      }
      else
      {
         // no specified default domains, so use "*"
         domains = DynamicObject();
         domains->append() = "*";
      }
      mContainer->setDefaultDomains(domains);

      MO_CAT_INFO(MO_WS_CAT, "WebServer running web services on domains: %s",
         JsonWriter::writeToString(domains, false, false).c_str());
   }

   if(rval)
   {
      MO_CAT_DEBUG(MO_WS_CAT, "WebServer initialized.");
   }

   return rval;
}

void WebServer::cleanup()
{
   // reset container
   mContainer->clear();
   DynamicObject domains;
   domains->append() = "*";
   mContainer->setDefaultDomains(domains);

   // clean up
   mHostAddress.setNull();
   mSslContext.setNull();
   mSocketDataPresenterList.setNull();
}

bool WebServer::enable(Server* server, const char* name)
{
   bool rval = true;

   // add http connection service
   mServiceId = server->addConnectionService(
      &(*mHostAddress), mContainer->getServicer(),
      &(*mSocketDataPresenterList), name);
   if(mServiceId == Server::sInvalidServiceId)
   {
      // could not add connection service
      rval = false;
   }
   else
   {
      mServer = server;
      MO_CAT_INFO(MO_WS_CAT, "WebServer %s serving on %s",
         name, mHostAddress->toString(false).c_str());
   }

   return rval;
}

void WebServer::disable()
{
   // remove http connection service
   if(mServiceId != Server::sInvalidServiceId)
   {
      mServer->removePortService(mServiceId);
      mServiceId = Server::sInvalidServiceId;
      mServer = NULL;
   }
}

void WebServer::setContainer(WebServiceContainerRef& c)
{
   mContainer = c;
}

WebServiceContainerRef& WebServer::getContainer()
{
   return mContainer;
}

InternetAddressRef WebServer::getHostAddress()
{
   return mHostAddress;
}

SslContextRef WebServer::getSslContext()
{
   return mSslContext;
}
<|endoftext|>


<commit_before>#include "Pixel.h"

#define PIXEL WalrusRPG::Graphics::Pixel

PIXEL::Pixel(std::uint16_t color) : value(color)
{
}

PIXEL::Pixel(Pixel &pix) : value((std::uint8_t) pix)
{
}

PIXEL::Pixel(std::uint8_t red, std::uint8_t green, std::uint8_t blue)
    : b(blue >> 3), g(green >> 2), r(red >> 3)
{
}

PIXEL::operator std::uint16_t() const
{
    return value;
}

PIXEL &PIXEL::operator=(unsigned value)
{
    this->value = value;
    return *this;
}

#define CONST_COLOR(color, r, g, b) \
    const WalrusRPG::Graphics::Pixel WalrusRPG::Graphics::color(r, g, b)
CONST_COLOR(Black, 0, 0, 0);
CONST_COLOR(White, 255, 255, 255);
CONST_COLOR(Red, 255, 0, 0);
CONST_COLOR(Green, 0, 255, 0);
CONST_COLOR(Blue, 0, 0, 255);
#undef CONST_COLOR
<commit_msg>Fixed pixel copy constructor<commit_after>#include "Pixel.h"

#define PIXEL WalrusRPG::Graphics::Pixel

PIXEL::Pixel(std::uint16_t color) : value(color)
{
}

PIXEL::Pixel(Pixel &pix) : value(pix.value)
{
}

PIXEL::Pixel(std::uint8_t red, std::uint8_t green, std::uint8_t blue)
    : b(blue >> 3), g(green >> 2), r(red >> 3)
{
}

PIXEL::operator std::uint16_t() const
{
    return value;
}

PIXEL &PIXEL::operator=(unsigned value)
{
    this->value = value;
    return *this;
}

#define CONST_COLOR(color, r, g, b) \
    const WalrusRPG::Graphics::Pixel WalrusRPG::Graphics::color(r, g, b)
CONST_COLOR(Black, 0, 0, 0);
CONST_COLOR(White, 255, 255, 255);
CONST_COLOR(Red, 255, 0, 0);
CONST_COLOR(Green, 0, 255, 0);
CONST_COLOR(Blue, 0, 0, 255);
#undef CONST_COLOR
<|endoftext|>


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

#include "google/cloud/internal/curl_handle_factory.h"
#include <benchmark/benchmark.h>

namespace google {
namespace cloud {
namespace rest_internal {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
namespace {

class PoolFixture : public ::benchmark::Fixture {
 public:
  PoolFixture() : pool_(128) {}

  CurlHandleFactory& pool() { return pool_; }

 private:
  PooledCurlHandleFactory pool_;
};

bool CreateAndCleanup(CurlHandleFactory& factory) {
  auto h = factory.CreateHandle();
  auto m = factory.CreateMultiHandle();
  auto const success = h && m;
  factory.CleanupMultiHandle(std::move(m), HandleDisposition::kKeep);
  factory.CleanupHandle(std::move(h), HandleDisposition::kKeep);
  return success;
}

BENCHMARK_DEFINE_F(PoolFixture, Burst)(benchmark::State& state) {
  for (auto _ : state) {
    if (!CreateAndCleanup(pool())) {
      state.SkipWithError("error creating handles");
      break;
    }
  }
}
BENCHMARK_REGISTER_F(PoolFixture, Burst)->ThreadRange(1, 1 << 8)->UseRealTime();

BENCHMARK_DEFINE_F(PoolFixture, Linear)(benchmark::State& state) {
  for (auto _ : state) {
    for (auto i = 0; i != state.range(0); ++i) {
      if (!CreateAndCleanup(pool())) {
        state.SkipWithError("error creating handles");
        break;
      }
    }
  }
  state.SetComplexityN(state.range(0));
}
BENCHMARK_REGISTER_F(PoolFixture, Linear)
    ->RangeMultiplier(2)
    ->Ranges({{1, 1 << 10}})
    ->Complexity(benchmark::oN);

}  // namespace
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
}  // namespace rest_internal
}  // namespace cloud
}  // namespace google
<commit_msg>doc(rest): record baseline for HandleFactory benchmark (#9578)<commit_after>// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "google/cloud/internal/curl_handle_factory.h"
#include <benchmark/benchmark.h>

namespace google {
namespace cloud {
namespace rest_internal {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
namespace {

class PoolFixture : public ::benchmark::Fixture {
 public:
  PoolFixture() : pool_(128) {}

  CurlHandleFactory& pool() { return pool_; }

 private:
  PooledCurlHandleFactory pool_;
};

bool CreateAndCleanup(CurlHandleFactory& factory) {
  auto h = factory.CreateHandle();
  auto m = factory.CreateMultiHandle();
  auto const success = h && m;
  factory.CleanupMultiHandle(std::move(m), HandleDisposition::kKeep);
  factory.CleanupHandle(std::move(h), HandleDisposition::kKeep);
  return success;
}

// clang-format off
// Run on (96 X 2000 MHz CPU s)
// CPU Caches:
//  L1 Data 32 KiB (x48)
//  L1 Instruction 32 KiB (x48)
//  L2 Unified 1024 KiB (x48)
//  L3 Unified 39424 KiB (x2)
// Load Average: 15.12, 5.10, 1.98
//----------------------------------------------------------------------------------
// Benchmark                                        Time             CPU Iterations
//----------------------------------------------------------------------------------
// PoolFixture/Burst/real_time/threads:1          611 ns          611 ns 1138757
// PoolFixture/Burst/real_time/threads:2          753 ns         1503 ns 931064
// PoolFixture/Burst/real_time/threads:4          912 ns         3460 ns 775028
// PoolFixture/Burst/real_time/threads:8          977 ns         6946 ns 719024
// PoolFixture/Burst/real_time/threads:16        1038 ns        14855 ns 645392
// PoolFixture/Burst/real_time/threads:32        1280 ns        38140 ns 570144
// PoolFixture/Burst/real_time/threads:64        1665 ns       101765 ns 510976
// PoolFixture/Burst/real_time/threads:128       1846 ns       172375 ns 388736
// PoolFixture/Burst/real_time/threads:256       1859 ns       180947 ns 377600
// clang-format on
BENCHMARK_DEFINE_F(PoolFixture, Burst)(benchmark::State& state) {
  for (auto _ : state) {
    if (!CreateAndCleanup(pool())) {
      state.SkipWithError("error creating handles");
      break;
    }
  }
}
BENCHMARK_REGISTER_F(PoolFixture, Burst)->ThreadRange(1, 1 << 8)->UseRealTime();

// clang-format off
// Run on (96 X 2000 MHz CPU s)
// CPU Caches:
//  L1 Data 32 KiB (x48)
//  L1 Instruction 32 KiB (x48)
//  L2 Unified 1024 KiB (x48)
//  L3 Unified 39424 KiB (x2)
// Load Average: 10.79, 7.87, 3.39
//------------------------------------------------------------------
// Benchmark                        Time             CPU   Iterations
//------------------------------------------------------------------
// PoolFixture/Linear/1           628 ns          628 ns      1098609
// PoolFixture/Linear/2          1255 ns         1255 ns       553833
// PoolFixture/Linear/4          2491 ns         2490 ns       278630
// PoolFixture/Linear/8          4967 ns         4967 ns       140583
// PoolFixture/Linear/16         9935 ns         9935 ns        70534
// PoolFixture/Linear/32        19896 ns        19892 ns        35236
// PoolFixture/Linear/64        39706 ns        39700 ns        17636
// PoolFixture/Linear/128       79433 ns        79428 ns         8816
// PoolFixture/Linear/256      159164 ns       159102 ns         4392
// PoolFixture/Linear/512      318709 ns       318687 ns         2202
// PoolFixture/Linear/1024     638671 ns       638514 ns         1098
// PoolFixture/Linear_BigO     623.33 N        623.20 N
// PoolFixture/Linear_RMS           0 %             0 %
// clang-format on
BENCHMARK_DEFINE_F(PoolFixture, Linear)(benchmark::State& state) {
  for (auto _ : state) {
    for (auto i = 0; i != state.range(0); ++i) {
      if (!CreateAndCleanup(pool())) {
        state.SkipWithError("error creating handles");
        break;
      }
    }
  }
  state.SetComplexityN(state.range(0));
}
BENCHMARK_REGISTER_F(PoolFixture, Linear)
    ->RangeMultiplier(2)
    ->Ranges({{1, 1 << 10}})
    ->Complexity(benchmark::oN);

}  // namespace
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
}  // namespace rest_internal
}  // namespace cloud
}  // namespace google
<|endoftext|>