<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: dbexception.hxx,v $
 *
 *  $Revision: 1.18 $
 *
 *  last change: $Author: ihi $ $Date: 2007-11-20 19:14:36 $
 *
 *  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 _DBHELPER_DBEXCEPTION_HXX_
#define _DBHELPER_DBEXCEPTION_HXX_

#ifndef _COM_SUN_STAR_SDBC_SQLEXCEPTION_HPP_
#include <com/sun/star/sdbc/SQLException.hpp>
#endif

namespace com
{
    namespace sun
    {
        namespace star
        {
            namespace sdb
            {
                class SQLContext;
                struct SQLErrorEvent;
            }
            namespace sdbc
            {
                class SQLWarning;
            }
        }
    }
}
//.........................................................................
namespace dbtools
{
//.........................................................................

//----------------------------------------------------------------------------------
/** standard SQLStates to be used with an SQLException

    Extend this list whenever you need a new state ...

    @see http://msdn.microsoft.com/library/default.asp?url=/library/en-us/odbc/htm/odbcodbc_error_codes.asp
*/
enum StandardSQLState
{
    SQL_WRONG_PARAMETER_NUMBER,     // 07001
    SQL_INVALID_DESCRIPTOR_INDEX,   // 07009
    SQL_UNABLE_TO_CONNECT,          // 08001
    SQL_NUMERIC_OUT_OF_RANGE,       // 22003
    SQL_INVALID_DATE_TIME,          // 22007
    SQL_INVALID_CURSOR_STATE,       // 24000
    SQL_TABLE_OR_VIEW_EXISTS,       // 42S01
    SQL_TABLE_OR_VIEW_NOT_FOUND,    // 42S02
    SQL_INDEX_ESISTS,               // 42S11
    SQL_INDEX_NOT_FOUND,            // 42S12
    SQL_COLUMN_EXISTS,              // 42S21
    SQL_COLUMN_NOT_FOUND,           // 42S22
    SQL_GENERAL_ERROR,              // HY000
    SQL_OPERATION_CANCELED,         // HY008
    SQL_FUNCTION_SEQUENCE_ERROR,    // HY010
    SQL_INVALID_CURSOR_POSITION,    // HY109
    SQL_INVALID_BOOKMARK_VALUE,     // HY111
    SQL_FEATURE_NOT_IMPLEMENTED,    // HYC00
    SQL_FUNCTION_NOT_SUPPORTED,     // IM001
    SQL_CONNECTION_DOES_NOT_EXIST,  // 08003

    SQL_CYCLIC_SUB_QUERIES,         // OB001

    SQL_ERROR_UNSPECIFIED = SAL_MAX_ENUM    // special value indicating that an SQLState is not to be specified
};

//==============================================================================
//= Special exception if cancel is pressed in DBA UI
//==============================================================================
enum OOoBaseErrorCode
{
    ParameterInteractionCancelled = 1
};

//==============================================================================
//= SQLExceptionInfo - encapsulating the type info of an SQLException-derived class
//==============================================================================

class SQLExceptionInfo
{
public:
    enum TYPE { SQL_EXCEPTION, SQL_WARNING, SQL_CONTEXT, UNDEFINED };

private:
    ::com::sun::star::uno::Any  m_aContent;
    TYPE            m_eType;    // redundant (could be derived from m_aContent.getValueType())

public:
    SQLExceptionInfo();
    SQLExceptionInfo(const ::com::sun::star::sdbc::SQLException& _rError);
    SQLExceptionInfo(const ::com::sun::star::sdbc::SQLWarning& _rError);
    SQLExceptionInfo(const ::com::sun::star::sdb::SQLContext& _rError);

    /** convenience constructor

    If your error processing relies on SQLExceptions, and SQLExceptionInfos, you still may
    need to display an error which consists of a simple message string only.
    In those cases, you can use this constructor, which behaves as if you would have used
    an SQLException containing exactly the given error message.
    */
    SQLExceptionInfo( const ::rtl::OUString& _rSimpleErrorMessage );

    SQLExceptionInfo(const SQLExceptionInfo& _rCopySource);

    SQLExceptionInfo(const ::com::sun::star::sdb::SQLErrorEvent& _rError);
            // use for events got via XSQLErrorListener::errorOccured
    SQLExceptionInfo(const ::com::sun::star::uno::Any& _rError);
            // use with the Reason member of an SQLErrorEvent or with NextElement of an SQLException

    /** prepends a plain error message to the chain of exceptions
        @param  _rSimpleErrorMessage
            the error message to prepend
        @param  _pAsciiSQLState
            the SQLState of the to-be-constructed SQLException, or NULL if this should be defaulted to HY000
        @param  _nErrorCode
            the ErrorCode of the to-be-constructed SQLException
    */
    void    prepend( const ::rtl::OUString& _rErrorMessage, const sal_Char* _pAsciiSQLState = NULL, const sal_Int32 _nErrorCode = 0 );

    /** appends a plain message to the chain of exceptions
        @param  _eType
            the type of exception to append. Must be SQL_EXCEPTION, SQL_WARNING, SQL_CONTEXT, for all other
            values, the behavior is undefined.
        @param  _rErrorMessage
            the message to append
        @param  _pAsciiSQLState
            the SQLState of the exception to append
        @param  _nErrorCode
            the error code of the exception to append
    */
    void    append( TYPE _eType, const ::rtl::OUString& _rErrorMessage, const sal_Char* _pAsciiSQLState = NULL, const sal_Int32 _nErrorCode = 0 );

    /** throws (properly typed) the exception contained in the object
        @precond
            isValid() returns <TRUE/>
        @throws SQLException
        @throws RuntimeException
            if the instance does not contain an SQLException
    */
    void    doThrow();

    const SQLExceptionInfo& operator=(const ::com::sun::star::sdbc::SQLException& _rError);
    const SQLExceptionInfo& operator=(const ::com::sun::star::sdbc::SQLWarning& _rError);
    const SQLExceptionInfo& operator=(const ::com::sun::star::sdb::SQLContext& _rError);
    const SQLExceptionInfo& operator=(const ::com::sun::star::sdb::SQLErrorEvent& _rErrorEvent);
    const SQLExceptionInfo& operator=(const ::com::sun::star::uno::Any& _rCaughtSQLException);

    sal_Bool    isKindOf(TYPE _eType) const;
        // not just a simple comparisation ! e.g. getType() == SQL_CONTEXT implies isKindOf(SQL_EXCEPTION) == sal_True !
    sal_Bool    isValid() const { return m_eType != UNDEFINED; }
    TYPE        getType() const { return m_eType; }

    operator const ::com::sun::star::sdbc::SQLException*    () const;
    operator const ::com::sun::star::sdbc::SQLWarning*      () const;
    operator const ::com::sun::star::sdb::SQLContext*       () const;

    const ::com::sun::star::uno::Any& get() const { return m_aContent; }

protected:
    void implDetermineType();
};

//==============================================================================
//= SQLExceptionIteratorHelper - iterating through an SQLException chain
//==============================================================================

class SQLExceptionIteratorHelper
{
protected:
    const ::com::sun::star::sdbc::SQLException* m_pCurrent;
    SQLExceptionInfo::TYPE                      m_eCurrentType;

public:
    /** constructs an iterator instance from an SQLException

        @param _rChainStart
            the start of the exception chain to iterate. Must live as long as the iterator
            instances lives, at least.
    */
    SQLExceptionIteratorHelper( const ::com::sun::star::sdbc::SQLException& _rChainStart );

    /** constructs an iterator instance from an SQLWarning

        @param _rChainStart
            the start of the exception chain to iterate. Must live as long as the iterator
            instances lives, at least.
    */
    SQLExceptionIteratorHelper( const ::com::sun::star::sdbc::SQLWarning& _rChainStart );

    /** constructs an iterator instance from an SQLContext

        @param _rChainStart
            the start of the exception chain to iterate. Must live as long as the iterator
            instances lives, at least.
    */
    SQLExceptionIteratorHelper( const ::com::sun::star::sdb::SQLContext& _rChainStart );

    /** constructs an iterator instance from an SQLExceptionInfo

        @param _rErrorInfo
            the start of the exception chain to iterate. Must live as long as the iterator
            instances lives, at least.
    */
    SQLExceptionIteratorHelper( const SQLExceptionInfo& _rErrorInfo );

    /** determines whether there are more elements in the exception chain
    */
    sal_Bool                                    hasMoreElements() const { return ( m_pCurrent != NULL ); }

    /** returns the type of the current element in the exception chain
    */
    SQLExceptionInfo::TYPE                      currentType() const { return m_eCurrentType; }

    /** retrieves the current element in the chain, or <NULL/> if the chain has been completely
        traveled.
    */
    const ::com::sun::star::sdbc::SQLException* current() const { return m_pCurrent; }

    /** retrieves the current element in the chain, or <NULL/> if the chain has been completely
        traveled.

        In opposite to the second <member>current</member>, this version allows typed access to
        the respective SQLException.
    */
    void                                        current( SQLExceptionInfo& _out_rInfo ) const;

    /** proceeds to the next element in the chain

        @return the current element in the chain, as <b>before</em> the chain move.
    */
    const ::com::sun::star::sdbc::SQLException* next();

    /** proceeds to the next element in the chain

        In opposite to the second <member>current</member>, this version allows typed access to
        the respective SQLException.
    */
    void                                        next( SQLExceptionInfo& _out_rInfo );
};

//==================================================================================
//= StandardExceptions
//==================================================================================
//----------------------------------------------------------------------------------
/** returns a standard error string for a given SQLState

    @param _eState
        describes the state whose description is to retrieve. Must not be SQL_ERROR_UNSPECIFIED.
    @raises RuntimeException
        in case of an internal error
*/
::rtl::OUString getStandardSQLState( StandardSQLState _eState );

//----------------------------------------------------------------------------------
/** returns a standard ASCII string for a given SQLState

    @param _eState
        describes the state whose description is to retrieve. Must not be SQL_ERROR_UNSPECIFIED.
    @return
        a non-<NULL/> pointer to an ASCII character string denoting the requested SQLState
    @raises RuntimeException
        in case of an internal error
*/
const sal_Char* getStandardSQLStateAscii( StandardSQLState _eState );

//----------------------------------------------------------------------------------
void throwFunctionNotSupportedException(
        const ::rtl::OUString& _rMsg,
        const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _Context,
        const ::com::sun::star::uno::Any& _Next = ::com::sun::star::uno::Any()
    )
    throw ( ::com::sun::star::sdbc::SQLException );

//----------------------------------------------------------------------------------
/** throws an exception with SQL state IM001, saying that a certain function is not supported
*/
void throwFunctionNotSupportedException(
        const sal_Char* _pAsciiFunctionName,
        const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxContext,
        const ::com::sun::star::uno::Any* _pNextException = NULL
    )
    throw ( ::com::sun::star::sdbc::SQLException );

//----------------------------------------------------------------------------------
/** throws a function sequence (HY010) exception
*/
void throwFunctionSequenceException(
        const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _Context,
        const ::com::sun::star::uno::Any& _Next = ::com::sun::star::uno::Any()
    )
    throw ( ::com::sun::star::sdbc::SQLException );

//----------------------------------------------------------------------------------
/** throw a invalid index sqlexception
*/
void throwInvalidIndexException(
        const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _Context,
        const ::com::sun::star::uno::Any& _Next = ::com::sun::star::uno::Any()
    )
    throw ( ::com::sun::star::sdbc::SQLException );

//----------------------------------------------------------------------------------
/** throw a generic SQLException, i.e. one with an SQLState of HY000, an ErrorCode of 0 and no NextException
*/
void throwGenericSQLException(
        const ::rtl::OUString& _rMsg,
        const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxSource
    )
    throw (::com::sun::star::sdbc::SQLException);

//----------------------------------------------------------------------------------
/** throw a generic SQLException, i.e. one with an SQLState of HY000, an ErrorCode of 0 and no NextException
*/
void throwGenericSQLException(
        const ::rtl::OUString& _rMsg,
        const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxSource,
        const ::com::sun::star::uno::Any& _rNextException
    )
    throw (::com::sun::star::sdbc::SQLException);

//----------------------------------------------------------------------------------
/** throw a SQLException with SQLState HYC00 (Optional feature not implemented)
    @param _pAsciiFeatureName
        an ASCII description of the feature which is not implemented. It's recommended that the feature
        name is built from the name of the interface plus its method, for instance "XParameters::updateBinaryStream"
    @param _rxContext
        the context of the exception
    @param _pNextException
        the next exception to chain into the thrown exception, if any
*/
void throwFeatureNotImplementedException(
        const sal_Char* _pAsciiFeatureName,
        const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxContext,
        const ::com::sun::star::uno::Any* _pNextException = NULL
    )
    throw (::com::sun::star::sdbc::SQLException);

//----------------------------------------------------------------------------------
/** throws an SQLException
*/
void throwSQLException(
        const sal_Char* _pAsciiMessage,
        const sal_Char* _pAsciiState,
        const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxContext,
        const sal_Int32 _nErrorCode = 0,
        const ::com::sun::star::uno::Any* _pNextException = NULL
    )
    throw (::com::sun::star::sdbc::SQLException);

//----------------------------------------------------------------------------------
/** throws an SQLException
*/
void throwSQLException(
        const sal_Char* _pAsciiMessage,
        StandardSQLState _eSQLState,
        const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxContext,
        const sal_Int32 _nErrorCode = 0,
        const ::com::sun::star::uno::Any* _pNextException = NULL
    )
    throw (::com::sun::star::sdbc::SQLException);

//----------------------------------------------------------------------------------
/** throws an SQLException
*/
void throwSQLException(
        const ::rtl::OUString& _rMessage,
        StandardSQLState _eSQLState,
        const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxContext,
        const sal_Int32 _nErrorCode = 0,
        const ::com::sun::star::uno::Any* _pNextException = NULL
    )
    throw (::com::sun::star::sdbc::SQLException);

//.........................................................................
}   // namespace dbtools
//.........................................................................

#endif // _DBHELPER_DBEXCEPTION_HXX_

<commit_msg>INTEGRATION: CWS dba24c (1.17.98); FILE MERGED 2007/09/18 20:04:51 fs 1.17.98.1: during #i81095#: outsourced the CYCLIC_SUB_QUERIES error to the new css.sdb.ErrorCondition<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: dbexception.hxx,v $
 *
 *  $Revision: 1.19 $
 *
 *  last change: $Author: ihi $ $Date: 2007-11-21 14:56:48 $
 *
 *  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 _DBHELPER_DBEXCEPTION_HXX_
#define _DBHELPER_DBEXCEPTION_HXX_

#ifndef _COM_SUN_STAR_SDBC_SQLEXCEPTION_HPP_
#include <com/sun/star/sdbc/SQLException.hpp>
#endif

namespace com
{
    namespace sun
    {
        namespace star
        {
            namespace sdb
            {
                class SQLContext;
                struct SQLErrorEvent;
            }
            namespace sdbc
            {
                class SQLWarning;
            }
        }
    }
}
//.........................................................................
namespace dbtools
{
//.........................................................................

//----------------------------------------------------------------------------------
/** standard SQLStates to be used with an SQLException

    Extend this list whenever you need a new state ...

    @see http://msdn.microsoft.com/library/default.asp?url=/library/en-us/odbc/htm/odbcodbc_error_codes.asp
*/
enum StandardSQLState
{
    SQL_WRONG_PARAMETER_NUMBER,     // 07001
    SQL_INVALID_DESCRIPTOR_INDEX,   // 07009
    SQL_UNABLE_TO_CONNECT,          // 08001
    SQL_NUMERIC_OUT_OF_RANGE,       // 22003
    SQL_INVALID_DATE_TIME,          // 22007
    SQL_INVALID_CURSOR_STATE,       // 24000
    SQL_TABLE_OR_VIEW_EXISTS,       // 42S01
    SQL_TABLE_OR_VIEW_NOT_FOUND,    // 42S02
    SQL_INDEX_ESISTS,               // 42S11
    SQL_INDEX_NOT_FOUND,            // 42S12
    SQL_COLUMN_EXISTS,              // 42S21
    SQL_COLUMN_NOT_FOUND,           // 42S22
    SQL_GENERAL_ERROR,              // HY000
    SQL_OPERATION_CANCELED,         // HY008
    SQL_FUNCTION_SEQUENCE_ERROR,    // HY010
    SQL_INVALID_CURSOR_POSITION,    // HY109
    SQL_INVALID_BOOKMARK_VALUE,     // HY111
    SQL_FEATURE_NOT_IMPLEMENTED,    // HYC00
    SQL_FUNCTION_NOT_SUPPORTED,     // IM001
    SQL_CONNECTION_DOES_NOT_EXIST,  // 08003

    SQL_ERROR_UNSPECIFIED = SAL_MAX_ENUM    // special value indicating that an SQLState is not to be specified
};

//==============================================================================
//= Special exception if cancel is pressed in DBA UI
//==============================================================================
enum OOoBaseErrorCode
{
    ParameterInteractionCancelled = 1
};

//==============================================================================
//= SQLExceptionInfo - encapsulating the type info of an SQLException-derived class
//==============================================================================

class SQLExceptionInfo
{
public:
    enum TYPE { SQL_EXCEPTION, SQL_WARNING, SQL_CONTEXT, UNDEFINED };

private:
    ::com::sun::star::uno::Any  m_aContent;
    TYPE            m_eType;    // redundant (could be derived from m_aContent.getValueType())

public:
    SQLExceptionInfo();
    SQLExceptionInfo(const ::com::sun::star::sdbc::SQLException& _rError);
    SQLExceptionInfo(const ::com::sun::star::sdbc::SQLWarning& _rError);
    SQLExceptionInfo(const ::com::sun::star::sdb::SQLContext& _rError);

    /** convenience constructor

    If your error processing relies on SQLExceptions, and SQLExceptionInfos, you still may
    need to display an error which consists of a simple message string only.
    In those cases, you can use this constructor, which behaves as if you would have used
    an SQLException containing exactly the given error message.
    */
    SQLExceptionInfo( const ::rtl::OUString& _rSimpleErrorMessage );

    SQLExceptionInfo(const SQLExceptionInfo& _rCopySource);

    SQLExceptionInfo(const ::com::sun::star::sdb::SQLErrorEvent& _rError);
            // use for events got via XSQLErrorListener::errorOccured
    SQLExceptionInfo(const ::com::sun::star::uno::Any& _rError);
            // use with the Reason member of an SQLErrorEvent or with NextElement of an SQLException

    /** prepends a plain error message to the chain of exceptions
        @param  _rSimpleErrorMessage
            the error message to prepend
        @param  _pAsciiSQLState
            the SQLState of the to-be-constructed SQLException, or NULL if this should be defaulted to HY000
        @param  _nErrorCode
            the ErrorCode of the to-be-constructed SQLException
    */
    void    prepend( const ::rtl::OUString& _rErrorMessage, const sal_Char* _pAsciiSQLState = NULL, const sal_Int32 _nErrorCode = 0 );

    /** appends a plain message to the chain of exceptions
        @param  _eType
            the type of exception to append. Must be SQL_EXCEPTION, SQL_WARNING, SQL_CONTEXT, for all other
            values, the behavior is undefined.
        @param  _rErrorMessage
            the message to append
        @param  _pAsciiSQLState
            the SQLState of the exception to append
        @param  _nErrorCode
            the error code of the exception to append
    */
    void    append( TYPE _eType, const ::rtl::OUString& _rErrorMessage, const sal_Char* _pAsciiSQLState = NULL, const sal_Int32 _nErrorCode = 0 );

    /** throws (properly typed) the exception contained in the object
        @precond
            isValid() returns <TRUE/>
        @throws SQLException
        @throws RuntimeException
            if the instance does not contain an SQLException
    */
    void    doThrow();

    const SQLExceptionInfo& operator=(const ::com::sun::star::sdbc::SQLException& _rError);
    const SQLExceptionInfo& operator=(const ::com::sun::star::sdbc::SQLWarning& _rError);
    const SQLExceptionInfo& operator=(const ::com::sun::star::sdb::SQLContext& _rError);
    const SQLExceptionInfo& operator=(const ::com::sun::star::sdb::SQLErrorEvent& _rErrorEvent);
    const SQLExceptionInfo& operator=(const ::com::sun::star::uno::Any& _rCaughtSQLException);

    sal_Bool    isKindOf(TYPE _eType) const;
        // not just a simple comparisation ! e.g. getType() == SQL_CONTEXT implies isKindOf(SQL_EXCEPTION) == sal_True !
    sal_Bool    isValid() const { return m_eType != UNDEFINED; }
    TYPE        getType() const { return m_eType; }

    operator const ::com::sun::star::sdbc::SQLException*    () const;
    operator const ::com::sun::star::sdbc::SQLWarning*      () const;
    operator const ::com::sun::star::sdb::SQLContext*       () const;

    const ::com::sun::star::uno::Any& get() const { return m_aContent; }

protected:
    void implDetermineType();
};

//==============================================================================
//= SQLExceptionIteratorHelper - iterating through an SQLException chain
//==============================================================================

class SQLExceptionIteratorHelper
{
protected:
    const ::com::sun::star::sdbc::SQLException* m_pCurrent;
    SQLExceptionInfo::TYPE                      m_eCurrentType;

public:
    /** constructs an iterator instance from an SQLException

        @param _rChainStart
            the start of the exception chain to iterate. Must live as long as the iterator
            instances lives, at least.
    */
    SQLExceptionIteratorHelper( const ::com::sun::star::sdbc::SQLException& _rChainStart );

    /** constructs an iterator instance from an SQLWarning

        @param _rChainStart
            the start of the exception chain to iterate. Must live as long as the iterator
            instances lives, at least.
    */
    SQLExceptionIteratorHelper( const ::com::sun::star::sdbc::SQLWarning& _rChainStart );

    /** constructs an iterator instance from an SQLContext

        @param _rChainStart
            the start of the exception chain to iterate. Must live as long as the iterator
            instances lives, at least.
    */
    SQLExceptionIteratorHelper( const ::com::sun::star::sdb::SQLContext& _rChainStart );

    /** constructs an iterator instance from an SQLExceptionInfo

        @param _rErrorInfo
            the start of the exception chain to iterate. Must live as long as the iterator
            instances lives, at least.
    */
    SQLExceptionIteratorHelper( const SQLExceptionInfo& _rErrorInfo );

    /** determines whether there are more elements in the exception chain
    */
    sal_Bool                                    hasMoreElements() const { return ( m_pCurrent != NULL ); }

    /** returns the type of the current element in the exception chain
    */
    SQLExceptionInfo::TYPE                      currentType() const { return m_eCurrentType; }

    /** retrieves the current element in the chain, or <NULL/> if the chain has been completely
        traveled.
    */
    const ::com::sun::star::sdbc::SQLException* current() const { return m_pCurrent; }

    /** retrieves the current element in the chain, or <NULL/> if the chain has been completely
        traveled.

        In opposite to the second <member>current</member>, this version allows typed access to
        the respective SQLException.
    */
    void                                        current( SQLExceptionInfo& _out_rInfo ) const;

    /** proceeds to the next element in the chain

        @return the current element in the chain, as <b>before</em> the chain move.
    */
    const ::com::sun::star::sdbc::SQLException* next();

    /** proceeds to the next element in the chain

        In opposite to the second <member>current</member>, this version allows typed access to
        the respective SQLException.
    */
    void                                        next( SQLExceptionInfo& _out_rInfo );
};

//==================================================================================
//= StandardExceptions
//==================================================================================
//----------------------------------------------------------------------------------
/** returns a standard error string for a given SQLState

    @param _eState
        describes the state whose description is to retrieve. Must not be SQL_ERROR_UNSPECIFIED.
    @raises RuntimeException
        in case of an internal error
*/
::rtl::OUString getStandardSQLState( StandardSQLState _eState );

//----------------------------------------------------------------------------------
/** returns a standard ASCII string for a given SQLState

    @param _eState
        describes the state whose description is to retrieve. Must not be SQL_ERROR_UNSPECIFIED.
    @return
        a non-<NULL/> pointer to an ASCII character string denoting the requested SQLState
    @raises RuntimeException
        in case of an internal error
*/
const sal_Char* getStandardSQLStateAscii( StandardSQLState _eState );

//----------------------------------------------------------------------------------
void throwFunctionNotSupportedException(
        const ::rtl::OUString& _rMsg,
        const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _Context,
        const ::com::sun::star::uno::Any& _Next = ::com::sun::star::uno::Any()
    )
    throw ( ::com::sun::star::sdbc::SQLException );

//----------------------------------------------------------------------------------
/** throws an exception with SQL state IM001, saying that a certain function is not supported
*/
void throwFunctionNotSupportedException(
        const sal_Char* _pAsciiFunctionName,
        const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxContext,
        const ::com::sun::star::uno::Any* _pNextException = NULL
    )
    throw ( ::com::sun::star::sdbc::SQLException );

//----------------------------------------------------------------------------------
/** throws a function sequence (HY010) exception
*/
void throwFunctionSequenceException(
        const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _Context,
        const ::com::sun::star::uno::Any& _Next = ::com::sun::star::uno::Any()
    )
    throw ( ::com::sun::star::sdbc::SQLException );

//----------------------------------------------------------------------------------
/** throw a invalid index sqlexception
*/
void throwInvalidIndexException(
        const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _Context,
        const ::com::sun::star::uno::Any& _Next = ::com::sun::star::uno::Any()
    )
    throw ( ::com::sun::star::sdbc::SQLException );

//----------------------------------------------------------------------------------
/** throw a generic SQLException, i.e. one with an SQLState of HY000, an ErrorCode of 0 and no NextException
*/
void throwGenericSQLException(
        const ::rtl::OUString& _rMsg,
        const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxSource
    )
    throw (::com::sun::star::sdbc::SQLException);

//----------------------------------------------------------------------------------
/** throw a generic SQLException, i.e. one with an SQLState of HY000, an ErrorCode of 0 and no NextException
*/
void throwGenericSQLException(
        const ::rtl::OUString& _rMsg,
        const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxSource,
        const ::com::sun::star::uno::Any& _rNextException
    )
    throw (::com::sun::star::sdbc::SQLException);

//----------------------------------------------------------------------------------
/** throw a SQLException with SQLState HYC00 (Optional feature not implemented)
    @param _pAsciiFeatureName
        an ASCII description of the feature which is not implemented. It's recommended that the feature
        name is built from the name of the interface plus its method, for instance "XParameters::updateBinaryStream"
    @param _rxContext
        the context of the exception
    @param _pNextException
        the next exception to chain into the thrown exception, if any
*/
void throwFeatureNotImplementedException(
        const sal_Char* _pAsciiFeatureName,
        const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxContext,
        const ::com::sun::star::uno::Any* _pNextException = NULL
    )
    throw (::com::sun::star::sdbc::SQLException);

//----------------------------------------------------------------------------------
/** throws an SQLException
*/
void throwSQLException(
        const sal_Char* _pAsciiMessage,
        const sal_Char* _pAsciiState,
        const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxContext,
        const sal_Int32 _nErrorCode = 0,
        const ::com::sun::star::uno::Any* _pNextException = NULL
    )
    throw (::com::sun::star::sdbc::SQLException);

//----------------------------------------------------------------------------------
/** throws an SQLException
*/
void throwSQLException(
        const sal_Char* _pAsciiMessage,
        StandardSQLState _eSQLState,
        const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxContext,
        const sal_Int32 _nErrorCode = 0,
        const ::com::sun::star::uno::Any* _pNextException = NULL
    )
    throw (::com::sun::star::sdbc::SQLException);

//----------------------------------------------------------------------------------
/** throws an SQLException
*/
void throwSQLException(
        const ::rtl::OUString& _rMessage,
        StandardSQLState _eSQLState,
        const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxContext,
        const sal_Int32 _nErrorCode = 0,
        const ::com::sun::star::uno::Any* _pNextException = NULL
    )
    throw (::com::sun::star::sdbc::SQLException);

//.........................................................................
}   // namespace dbtools
//.........................................................................

#endif // _DBHELPER_DBEXCEPTION_HXX_

<|endoftext|>


<commit_before>/**
 * \file
 * \brief ThreadSleepForTestCase class implementation
 *
 * \author Copyright (C) 2014-2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
 *
 * \par License
 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
 * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * \date 2015-07-17
 */

#include "ThreadSleepForTestCase.hpp"

#include "priorityTestPhases.hpp"
#include "SequenceAsserter.hpp"

#include "distortos/StaticThread.hpp"
#include "distortos/ThisThread.hpp"

#include "distortos/architecture/InterruptMaskingLock.hpp"

namespace distortos
{

namespace test
{

namespace
{

/*---------------------------------------------------------------------------------------------------------------------+
| local constants
+---------------------------------------------------------------------------------------------------------------------*/

/// size of stack for test thread, bytes
constexpr size_t testThreadStackSize {384};

/*---------------------------------------------------------------------------------------------------------------------+
| local functions' declarations
+---------------------------------------------------------------------------------------------------------------------*/

void thread(uint8_t sleepFor, SequenceAsserter& sequenceAsserter, unsigned int sequencePoint,
		const TickClock::time_point& sleepStart, TickClock::duration& durationDeviation, int& sharedRet);

/*---------------------------------------------------------------------------------------------------------------------+
| local types
+---------------------------------------------------------------------------------------------------------------------*/

/// type of test thread
using TestThread = decltype(makeStaticThread<testThreadStackSize>({}, thread, std::declval<uint8_t>(),
		std::ref(std::declval<SequenceAsserter&>()), std::declval<unsigned int>(),
		std::cref(std::declval<const TickClock::time_point&>()), std::ref(std::declval<TickClock::duration&>()),
		std::ref(std::declval<int&>())));

/*---------------------------------------------------------------------------------------------------------------------+
| local functions
+---------------------------------------------------------------------------------------------------------------------*/

/**
 * \brief Test thread.
 *
 * Sleeps for requested amount of time and marks the sequence point in SequenceAsserter, also storing the deviation of
 * duration actually slept.
 *
 * \param [in] sleepFor is the number of ticks the thread will sleep before marking sequence point
 * \param [in] sequenceAsserter is a reference to SequenceAsserter shared object
 * \param [in] sequencePoint is the sequence point of this instance
 * \param [in] sleepStart is a reference to variable with time point of sleep's start - it is used for deviation of
 * sleep duration calculation
 * \param [out] durationDeviation is a reference to variable for storing deviation of sleep duration
 * \param [out] sharedRet is a reference to variable for storing return value of ThisThread::sleepFor()
 */

void thread(const uint8_t sleepFor, SequenceAsserter& sequenceAsserter, const unsigned int sequencePoint,
		const TickClock::time_point& sleepStart, TickClock::duration& durationDeviation, int& sharedRet)
{
	const auto sleepForDuration = TickClock::duration{sleepFor};

	sharedRet = ThisThread::sleepFor(sleepForDuration);

	const auto durationSlept = TickClock::now() - sleepStart;
	sequenceAsserter.sequencePoint(sequencePoint);
	durationDeviation = durationSlept - sleepForDuration;
}

/**
 * \brief Builder of TestThread objects.
 *
 * This test uses "priority" field of test parameters as a "reversed" amount of time to sleep.
 *
 * \param [in] threadParameters is a reference to ThreadParameters object
 * \param [in] sequenceAsserter is a reference to SequenceAsserter shared object
 * \param [in] sleepStart is a reference to variable with time point of sleep's start - it is used for deviation of
 * sleep duration calculation
 * \param [out] durationDeviation is a reference to variable for storing deviation of sleep duration
 * \param [out] sharedRet is a reference to variable for storing return value of ThisThread::sleepFor()
 *
 * \return constructed TestThread object
 */

TestThread makeTestThread(const ThreadParameters& threadParameters, SequenceAsserter& sequenceAsserter,
		const TickClock::time_point& sleepStart, TickClock::duration& durationDeviation, int& sharedRet)
{
	return makeStaticThread<testThreadStackSize>(UINT8_MAX, thread,
			static_cast<uint8_t>(UINT8_MAX - threadParameters.first), std::ref(sequenceAsserter),
			static_cast<unsigned int>(threadParameters.second), std::cref(sleepStart), std::ref(durationDeviation),
			std::ref(sharedRet));
}

}	// namespace

/*---------------------------------------------------------------------------------------------------------------------+
| private functions
+---------------------------------------------------------------------------------------------------------------------*/

bool ThreadSleepForTestCase::run_() const
{
	for (const auto& phase : priorityTestPhases)
	{
		SequenceAsserter sequenceAsserter;
		std::array<TickClock::duration, totalThreads> durationDeviations {{}};
		std::array<int, totalThreads> sharedRets {{}};
		TickClock::time_point sleepStart;

		std::array<TestThread, totalThreads> threads
		{{
				makeTestThread(phase.first[phase.second[0]], sequenceAsserter, sleepStart, durationDeviations[0],
						sharedRets[0]),
				makeTestThread(phase.first[phase.second[1]], sequenceAsserter, sleepStart, durationDeviations[1],
						sharedRets[1]),
				makeTestThread(phase.first[phase.second[2]], sequenceAsserter, sleepStart, durationDeviations[2],
						sharedRets[2]),
				makeTestThread(phase.first[phase.second[3]], sequenceAsserter, sleepStart, durationDeviations[3],
						sharedRets[3]),
				makeTestThread(phase.first[phase.second[4]], sequenceAsserter, sleepStart, durationDeviations[4],
						sharedRets[4]),
				makeTestThread(phase.first[phase.second[5]], sequenceAsserter, sleepStart, durationDeviations[5],
						sharedRets[5]),
				makeTestThread(phase.first[phase.second[6]], sequenceAsserter, sleepStart, durationDeviations[6],
						sharedRets[6]),
				makeTestThread(phase.first[phase.second[7]], sequenceAsserter, sleepStart, durationDeviations[7],
						sharedRets[7]),
				makeTestThread(phase.first[phase.second[8]], sequenceAsserter, sleepStart, durationDeviations[8],
						sharedRets[8]),
				makeTestThread(phase.first[phase.second[9]], sequenceAsserter, sleepStart, durationDeviations[9],
						sharedRets[9]),
		}};

		{
			architecture::InterruptMaskingLock interruptMaskingLock;

			// wait for beginning of next tick - test threads should be started in the same tick
			ThisThread::sleepFor({});
			sleepStart = TickClock::now();

			for (auto& thread : threads)
				thread.start();
		}

		for (auto& thread : threads)
			thread.join();

		if (sequenceAsserter.assertSequence(totalThreads) == false)
			return false;

		// sleepFor() always sleeps one tick longer
		for (const auto& durationDeviation : durationDeviations)
			if (durationDeviation != TickClock::duration{1})
				return false;

		for (const auto& sharedRet : sharedRets)
			if (sharedRet != 0)
				return false;
	}

	return true;
}

}	// namespace test

}	// namespace distortos
<commit_msg>test: check state of sleeping threads in ThreadSleepForTestCase<commit_after>/**
 * \file
 * \brief ThreadSleepForTestCase class implementation
 *
 * \author Copyright (C) 2014-2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
 *
 * \par License
 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
 * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * \date 2015-12-02
 */

#include "ThreadSleepForTestCase.hpp"

#include "priorityTestPhases.hpp"
#include "SequenceAsserter.hpp"

#include "distortos/StaticThread.hpp"
#include "distortos/ThisThread.hpp"

#include "distortos/architecture/InterruptMaskingLock.hpp"

namespace distortos
{

namespace test
{

namespace
{

/*---------------------------------------------------------------------------------------------------------------------+
| local constants
+---------------------------------------------------------------------------------------------------------------------*/

/// size of stack for test thread, bytes
constexpr size_t testThreadStackSize {384};

/*---------------------------------------------------------------------------------------------------------------------+
| local functions' declarations
+---------------------------------------------------------------------------------------------------------------------*/

void thread(uint8_t sleepFor, SequenceAsserter& sequenceAsserter, unsigned int sequencePoint,
		const TickClock::time_point& sleepStart, TickClock::duration& durationDeviation, int& sharedRet);

/*---------------------------------------------------------------------------------------------------------------------+
| local types
+---------------------------------------------------------------------------------------------------------------------*/

/// type of test thread
using TestThread = decltype(makeStaticThread<testThreadStackSize>({}, thread, std::declval<uint8_t>(),
		std::ref(std::declval<SequenceAsserter&>()), std::declval<unsigned int>(),
		std::cref(std::declval<const TickClock::time_point&>()), std::ref(std::declval<TickClock::duration&>()),
		std::ref(std::declval<int&>())));

/*---------------------------------------------------------------------------------------------------------------------+
| local functions
+---------------------------------------------------------------------------------------------------------------------*/

/**
 * \brief Test thread.
 *
 * Sleeps for requested amount of time and marks the sequence point in SequenceAsserter, also storing the deviation of
 * duration actually slept.
 *
 * \param [in] sleepFor is the number of ticks the thread will sleep before marking sequence point
 * \param [in] sequenceAsserter is a reference to SequenceAsserter shared object
 * \param [in] sequencePoint is the sequence point of this instance
 * \param [in] sleepStart is a reference to variable with time point of sleep's start - it is used for deviation of
 * sleep duration calculation
 * \param [out] durationDeviation is a reference to variable for storing deviation of sleep duration
 * \param [out] sharedRet is a reference to variable for storing return value of ThisThread::sleepFor()
 */

void thread(const uint8_t sleepFor, SequenceAsserter& sequenceAsserter, const unsigned int sequencePoint,
		const TickClock::time_point& sleepStart, TickClock::duration& durationDeviation, int& sharedRet)
{
	const auto sleepForDuration = TickClock::duration{sleepFor};

	sharedRet = ThisThread::sleepFor(sleepForDuration);

	const auto durationSlept = TickClock::now() - sleepStart;
	sequenceAsserter.sequencePoint(sequencePoint);
	durationDeviation = durationSlept - sleepForDuration;
}

/**
 * \brief Builder of TestThread objects.
 *
 * This test uses "priority" field of test parameters as a "reversed" amount of time to sleep.
 *
 * \param [in] threadParameters is a reference to ThreadParameters object
 * \param [in] sequenceAsserter is a reference to SequenceAsserter shared object
 * \param [in] sleepStart is a reference to variable with time point of sleep's start - it is used for deviation of
 * sleep duration calculation
 * \param [out] durationDeviation is a reference to variable for storing deviation of sleep duration
 * \param [out] sharedRet is a reference to variable for storing return value of ThisThread::sleepFor()
 *
 * \return constructed TestThread object
 */

TestThread makeTestThread(const ThreadParameters& threadParameters, SequenceAsserter& sequenceAsserter,
		const TickClock::time_point& sleepStart, TickClock::duration& durationDeviation, int& sharedRet)
{
	return makeStaticThread<testThreadStackSize>(UINT8_MAX, thread,
			static_cast<uint8_t>(UINT8_MAX - threadParameters.first), std::ref(sequenceAsserter),
			static_cast<unsigned int>(threadParameters.second), std::cref(sleepStart), std::ref(durationDeviation),
			std::ref(sharedRet));
}

}	// namespace

/*---------------------------------------------------------------------------------------------------------------------+
| private functions
+---------------------------------------------------------------------------------------------------------------------*/

bool ThreadSleepForTestCase::run_() const
{
	for (const auto& phase : priorityTestPhases)
	{
		SequenceAsserter sequenceAsserter;
		std::array<TickClock::duration, totalThreads> durationDeviations {{}};
		std::array<int, totalThreads> sharedRets {{}};
		TickClock::time_point sleepStart;

		std::array<TestThread, totalThreads> threads
		{{
				makeTestThread(phase.first[phase.second[0]], sequenceAsserter, sleepStart, durationDeviations[0],
						sharedRets[0]),
				makeTestThread(phase.first[phase.second[1]], sequenceAsserter, sleepStart, durationDeviations[1],
						sharedRets[1]),
				makeTestThread(phase.first[phase.second[2]], sequenceAsserter, sleepStart, durationDeviations[2],
						sharedRets[2]),
				makeTestThread(phase.first[phase.second[3]], sequenceAsserter, sleepStart, durationDeviations[3],
						sharedRets[3]),
				makeTestThread(phase.first[phase.second[4]], sequenceAsserter, sleepStart, durationDeviations[4],
						sharedRets[4]),
				makeTestThread(phase.first[phase.second[5]], sequenceAsserter, sleepStart, durationDeviations[5],
						sharedRets[5]),
				makeTestThread(phase.first[phase.second[6]], sequenceAsserter, sleepStart, durationDeviations[6],
						sharedRets[6]),
				makeTestThread(phase.first[phase.second[7]], sequenceAsserter, sleepStart, durationDeviations[7],
						sharedRets[7]),
				makeTestThread(phase.first[phase.second[8]], sequenceAsserter, sleepStart, durationDeviations[8],
						sharedRets[8]),
				makeTestThread(phase.first[phase.second[9]], sequenceAsserter, sleepStart, durationDeviations[9],
						sharedRets[9]),
		}};

		{
			architecture::InterruptMaskingLock interruptMaskingLock;

			// wait for beginning of next tick - test threads should be started in the same tick
			ThisThread::sleepFor({});
			sleepStart = TickClock::now();

			for (auto& thread : threads)
				thread.start();
		}

		bool invalidState {};
		for (const auto& thread : threads)
			if (thread.getState() != ThreadState::Sleeping)
				invalidState = true;

		for (auto& thread : threads)
			thread.join();

		if (invalidState != false)
			return false;

		if (sequenceAsserter.assertSequence(totalThreads) == false)
			return false;

		// sleepFor() always sleeps one tick longer
		for (const auto& durationDeviation : durationDeviations)
			if (durationDeviation != TickClock::duration{1})
				return false;

		for (const auto& sharedRet : sharedRets)
			if (sharedRet != 0)
				return false;
	}

	return true;
}

}	// namespace test

}	// namespace distortos
<|endoftext|>


<commit_before>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-

Copyright 2016 Raffaello D. Di Napoli

This file is part of Abaclade.

Abaclade 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 3 of the
License, or (at your option) any later version.

Abaclade 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 Abaclade. If
not, see <http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------------------------------*/

#include <abaclade.hxx>
#include <abaclade/text/parsers/dynamic.hxx>
#include <abaclade/testing/test_case.hxx>

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

namespace abc { namespace test {

ABC_TESTING_TEST_CASE_FUNC(
   text_parsers_dynamic_one_char,
   "abc::text::parsers::dynamic – one-character pattern"
) {
   ABC_TRACE_FUNC(this);

   text::parsers::dynamic dp;
   auto ps = dp.create_state();
   ps->set_code_point('a');
   dp.set_initial_state(ps);

   ABC_TESTING_ASSERT_FALSE(dp.run(ABC_SL("")));
   ABC_TESTING_ASSERT_TRUE(dp.run(ABC_SL("a")));
   ABC_TESTING_ASSERT_TRUE(dp.run(ABC_SL("aa")));
   ABC_TESTING_ASSERT_FALSE(dp.run(ABC_SL("b")));
   ABC_TESTING_ASSERT_TRUE(dp.run(ABC_SL("ba")));
}

ABC_TESTING_TEST_CASE_FUNC(
   text_parsers_dynamic_begin,
   "abc::text::parsers::dynamic – begin pattern (“^”)"
) {
   ABC_TRACE_FUNC(this);

   text::parsers::dynamic dp;
   auto ps = dp.create_state();
   ps->set_begin();
   dp.set_initial_state(ps);

   ABC_TESTING_ASSERT_TRUE(dp.run(ABC_SL("")));
   ABC_TESTING_ASSERT_TRUE(dp.run(ABC_SL("a")));
}

ABC_TESTING_TEST_CASE_FUNC(
   text_parsers_dynamic_begin_anchored,
   "abc::text::parsers::dynamic – begin-anchored pattern (“^a”)"
) {
   ABC_TRACE_FUNC(this);

   text::parsers::dynamic dp;
   auto psA = dp.create_state();
   psA->set_code_point('a');
   auto psBegin = dp.create_state();
   psBegin->set_begin();
   psBegin->set_next(psA);
   dp.set_initial_state(psBegin);

   ABC_TESTING_ASSERT_FALSE(dp.run(ABC_SL("")));
   ABC_TESTING_ASSERT_TRUE(dp.run(ABC_SL("a")));
   ABC_TESTING_ASSERT_TRUE(dp.run(ABC_SL("aa")));
   ABC_TESTING_ASSERT_TRUE(dp.run(ABC_SL("ab")));
   ABC_TESTING_ASSERT_FALSE(dp.run(ABC_SL("b")));
   ABC_TESTING_ASSERT_FALSE(dp.run(ABC_SL("ba")));
}

ABC_TESTING_TEST_CASE_FUNC(
   text_parsers_dynamic_end,
   "abc::text::parsers::dynamic – end pattern (“$”)"
) {
   ABC_TRACE_FUNC(this);

   text::parsers::dynamic dp;
   auto ps = dp.create_state();
   ps->set_end();
   dp.set_initial_state(ps);

   ABC_TESTING_ASSERT_TRUE(dp.run(ABC_SL("")));
   ABC_TESTING_ASSERT_TRUE(dp.run(ABC_SL("a")));
}

ABC_TESTING_TEST_CASE_FUNC(
   text_parsers_dynamic_end_anchored,
   "abc::text::parsers::dynamic – end-anchored pattern (“a$”)"
) {
   ABC_TRACE_FUNC(this);

   text::parsers::dynamic dp;
   auto psEnd = dp.create_state();
   psEnd->set_end();
   auto psA = dp.create_state();
   psA->set_code_point('a');
   psA->set_next(psEnd);
   dp.set_initial_state(psA);

   ABC_TESTING_ASSERT_FALSE(dp.run(ABC_SL("")));
   ABC_TESTING_ASSERT_TRUE(dp.run(ABC_SL("a")));
   ABC_TESTING_ASSERT_TRUE(dp.run(ABC_SL("aa")));
   ABC_TESTING_ASSERT_FALSE(dp.run(ABC_SL("ab")));
   ABC_TESTING_ASSERT_FALSE(dp.run(ABC_SL("b")));
   ABC_TESTING_ASSERT_TRUE(dp.run(ABC_SL("ba")));
}

ABC_TESTING_TEST_CASE_FUNC(
   text_parsers_dynamic_two_char,
   "abc::text::parsers::dynamic – two-character pattern"
) {
   ABC_TRACE_FUNC(this);

   text::parsers::dynamic dp;
   auto psB = dp.create_state();
   psB->set_code_point('b');
   auto psA = dp.create_state();
   psA->set_code_point('a');
   psA->set_next(psB);
   dp.set_initial_state(psA);

   ABC_TESTING_ASSERT_FALSE(dp.run(ABC_SL("")));
   ABC_TESTING_ASSERT_FALSE(dp.run(ABC_SL("a")));
   ABC_TESTING_ASSERT_FALSE(dp.run(ABC_SL("aa")));
   ABC_TESTING_ASSERT_FALSE(dp.run(ABC_SL("b")));
   ABC_TESTING_ASSERT_TRUE(dp.run(ABC_SL("ab")));
   ABC_TESTING_ASSERT_TRUE(dp.run(ABC_SL("bab")));
   ABC_TESTING_ASSERT_TRUE(dp.run(ABC_SL("aab")));
}

}} //namespace abc::test
<commit_msg>Add a few more test assertions<commit_after>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-

Copyright 2016 Raffaello D. Di Napoli

This file is part of Abaclade.

Abaclade 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 3 of the
License, or (at your option) any later version.

Abaclade 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 Abaclade. If
not, see <http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------------------------------*/

#include <abaclade.hxx>
#include <abaclade/text/parsers/dynamic.hxx>
#include <abaclade/testing/test_case.hxx>

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

namespace abc { namespace test {

ABC_TESTING_TEST_CASE_FUNC(
   text_parsers_dynamic_one_char,
   "abc::text::parsers::dynamic – one-character pattern “a”"
) {
   ABC_TRACE_FUNC(this);

   text::parsers::dynamic dp;
   auto ps = dp.create_state();
   ps->set_code_point('a');
   dp.set_initial_state(ps);

   ABC_TESTING_ASSERT_FALSE(dp.run(ABC_SL("")));
   ABC_TESTING_ASSERT_TRUE(dp.run(ABC_SL("a")));
   ABC_TESTING_ASSERT_TRUE(dp.run(ABC_SL("aa")));
   ABC_TESTING_ASSERT_FALSE(dp.run(ABC_SL("b")));
   ABC_TESTING_ASSERT_TRUE(dp.run(ABC_SL("ba")));
   ABC_TESTING_ASSERT_TRUE(dp.run(ABC_SL("ab")));
}

ABC_TESTING_TEST_CASE_FUNC(
   text_parsers_dynamic_begin,
   "abc::text::parsers::dynamic – begin pattern “^”"
) {
   ABC_TRACE_FUNC(this);

   text::parsers::dynamic dp;
   auto ps = dp.create_state();
   ps->set_begin();
   dp.set_initial_state(ps);

   ABC_TESTING_ASSERT_TRUE(dp.run(ABC_SL("")));
   ABC_TESTING_ASSERT_TRUE(dp.run(ABC_SL("a")));
}

ABC_TESTING_TEST_CASE_FUNC(
   text_parsers_dynamic_begin_anchored,
   "abc::text::parsers::dynamic – begin-anchored pattern “^a”"
) {
   ABC_TRACE_FUNC(this);

   text::parsers::dynamic dp;
   auto psA = dp.create_state();
   psA->set_code_point('a');
   auto psBegin = dp.create_state();
   psBegin->set_begin();
   psBegin->set_next(psA);
   dp.set_initial_state(psBegin);

   ABC_TESTING_ASSERT_FALSE(dp.run(ABC_SL("")));
   ABC_TESTING_ASSERT_TRUE(dp.run(ABC_SL("a")));
   ABC_TESTING_ASSERT_TRUE(dp.run(ABC_SL("aa")));
   ABC_TESTING_ASSERT_TRUE(dp.run(ABC_SL("ab")));
   ABC_TESTING_ASSERT_FALSE(dp.run(ABC_SL("b")));
   ABC_TESTING_ASSERT_FALSE(dp.run(ABC_SL("ba")));
}

ABC_TESTING_TEST_CASE_FUNC(
   text_parsers_dynamic_end,
   "abc::text::parsers::dynamic – end pattern “$”"
) {
   ABC_TRACE_FUNC(this);

   text::parsers::dynamic dp;
   auto ps = dp.create_state();
   ps->set_end();
   dp.set_initial_state(ps);

   ABC_TESTING_ASSERT_TRUE(dp.run(ABC_SL("")));
   ABC_TESTING_ASSERT_TRUE(dp.run(ABC_SL("a")));
}

ABC_TESTING_TEST_CASE_FUNC(
   text_parsers_dynamic_end_anchored,
   "abc::text::parsers::dynamic – end-anchored pattern “a$”"
) {
   ABC_TRACE_FUNC(this);

   text::parsers::dynamic dp;
   auto psEnd = dp.create_state();
   psEnd->set_end();
   auto psA = dp.create_state();
   psA->set_code_point('a');
   psA->set_next(psEnd);
   dp.set_initial_state(psA);

   ABC_TESTING_ASSERT_FALSE(dp.run(ABC_SL("")));
   ABC_TESTING_ASSERT_TRUE(dp.run(ABC_SL("a")));
   ABC_TESTING_ASSERT_TRUE(dp.run(ABC_SL("aa")));
   ABC_TESTING_ASSERT_FALSE(dp.run(ABC_SL("ab")));
   ABC_TESTING_ASSERT_FALSE(dp.run(ABC_SL("b")));
   ABC_TESTING_ASSERT_TRUE(dp.run(ABC_SL("ba")));
}

ABC_TESTING_TEST_CASE_FUNC(
   text_parsers_dynamic_two_char,
   "abc::text::parsers::dynamic – two-character pattern “ab”"
) {
   ABC_TRACE_FUNC(this);

   text::parsers::dynamic dp;
   auto psB = dp.create_state();
   psB->set_code_point('b');
   auto psA = dp.create_state();
   psA->set_code_point('a');
   psA->set_next(psB);
   dp.set_initial_state(psA);

   ABC_TESTING_ASSERT_FALSE(dp.run(ABC_SL("")));
   ABC_TESTING_ASSERT_FALSE(dp.run(ABC_SL("a")));
   ABC_TESTING_ASSERT_FALSE(dp.run(ABC_SL("aa")));
   ABC_TESTING_ASSERT_FALSE(dp.run(ABC_SL("b")));
   ABC_TESTING_ASSERT_TRUE(dp.run(ABC_SL("ab")));
   ABC_TESTING_ASSERT_TRUE(dp.run(ABC_SL("bab")));
   ABC_TESTING_ASSERT_TRUE(dp.run(ABC_SL("aab")));
   ABC_TESTING_ASSERT_TRUE(dp.run(ABC_SL("aaba")));
}

}} //namespace abc::test
<|endoftext|>


<commit_before>#include <cstdlib>
#include <algorithm>
#include <iostream>

#include <tightdb.hpp>

#include "../util/timer.hpp"
#include "../util/random.hpp"
#include "../util/benchmark_results.hpp"

using namespace std;
using namespace tightdb;

namespace {

TIGHTDB_TABLE_1(IntTable,
                i, Int)

inline int_fast64_t read(IntTable& table, const vector<size_t> order)
{
    int_fast64_t dummy = 0;
    size_t n = order.size();
    for (size_t i = 0; i != n; ++i)
        dummy += table[order[i]].i;
    return dummy;
}

inline void write(IntTable& table, const vector<size_t> order)
{
    size_t n = order.size();
    for (size_t i = 0; i != n; ++i)
        table[order[i]].i = 125;
}

inline void insert(IntTable& table, const vector<size_t> order)
{
    size_t n = order.size();
    for (size_t i = 0; i != n; ++i)
        table.insert(order[i], 127);
}

inline void erase(IntTable& table, const vector<size_t> order)
{
    size_t n = order.size();
    for (size_t i = 0; i != n; ++i)
        table.remove(order[i]);
}

} // anonymous namepsace

int main()
{
    const size_t target_size = 1100*1000L;
    const int num_tables = 50;
    cout << "Number of tables: " << num_tables << endl;
    cout << "Elements per table: " << target_size << endl;

    vector<size_t> rising_order;
    vector<size_t> falling_order;
    vector<size_t> random_order;
    vector<size_t> random_insert_order;
    vector<size_t> random_erase_order;
    for (size_t i = 0; i != target_size; ++i) {
        rising_order.push_back(i);
        falling_order.push_back(target_size-1-i);
        random_order.push_back(i);
        random_insert_order.push_back(rand() % (i+1));
        random_erase_order.push_back(rand() % (target_size-i));
    }
    Random random;
    random.shuffle(random_order.begin(), random_order.end());

    IntTable tables_1[num_tables], tables_2[num_tables];

    int_fast64_t dummy = 0;

    int max_lead_text_size = 26;
    BenchmarkResults results(max_lead_text_size);

    Timer timer_total(Timer::type_UserTime);
    Timer timer(Timer::type_UserTime);
    {
        timer.reset();
        for (int i = 0; i != num_tables; ++i)
            insert(tables_1[i], rising_order);
        results.submit(timer, "insert_end_compact", "Insert at end (compact)");
        timer.reset();
        for (int i = 0; i != num_tables; ++i)
            dummy += read(tables_1[i], rising_order);
        results.submit(timer, "read_seq_compact", "Sequential read (compact)");
        timer.reset();
        for (int i = 0; i != num_tables; ++i)
            dummy += read(tables_1[i], random_order);
        results.submit(timer, "read_ran_compact", "Random read (compact)");
        timer.reset();
        for (int i = 0; i != num_tables; ++i)
            write(tables_1[i], rising_order);
        results.submit(timer, "write_seq_compact", "Sequential write (compact)");
        timer.reset();
        for (int i = 0; i != num_tables; ++i)
            write(tables_1[i], random_order);
        results.submit(timer, "write_ran_compact", "Random write (compact)");
        timer.reset();
        for (int i = 0; i != num_tables; ++i)
            erase(tables_1[i], falling_order);
        results.submit(timer, "erase_end_compact", "Erase from end (compact)");
    }
    {
        timer.reset();
        for (int i = 0; i != num_tables; ++i)
            insert(tables_2[i], random_insert_order);
        results.submit(timer, "insert_ran_general", "Random insert (general)");
        timer.reset();
        for (int i = 0; i != num_tables; ++i)
            dummy += read(tables_2[0], rising_order);
        results.submit(timer, "read_seq_general", "Sequential read (general)");
        timer.reset();
        for (int i = 0; i != num_tables; ++i)
            dummy += read(tables_2[0], random_order);
        results.submit(timer, "read_ran_general", "Random read (general)");
        timer.reset();
        for (int i = 0; i != num_tables; ++i)
            write(tables_2[i], rising_order);
        results.submit(timer, "write_seq_general", "Sequential write (general)");
        timer.reset();
        for (int i = 0; i != num_tables; ++i)
            write(tables_2[i], random_order);
        results.submit(timer, "write_ran_general", "Random write (general)");
        timer.reset();
        for (int i = 0; i != num_tables; ++i)
            erase(tables_2[i], random_erase_order);
        results.submit(timer, "erase_ran_general", "Random erase (general)");
    }

    results.submit(timer_total, "total_time", "Total time");

    cout << "dummy = "<<dummy<<" (to avoid over-optimization)"<<endl;
}
<commit_msg>Fix benchmark-insert-get-set<commit_after>#include <cstdlib>
#include <algorithm>
#include <iostream>

#include <tightdb.hpp>

#include "../util/timer.hpp"
#include "../util/random.hpp"
#include "../util/benchmark_results.hpp"

using namespace std;
using namespace tightdb;
using namespace tightdb::test_util;

namespace {

TIGHTDB_TABLE_1(IntTable,
                i, Int)

inline int_fast64_t read(IntTable& table, const vector<size_t> order)
{
    int_fast64_t dummy = 0;
    size_t n = order.size();
    for (size_t i = 0; i != n; ++i)
        dummy += table[order[i]].i;
    return dummy;
}

inline void write(IntTable& table, const vector<size_t> order)
{
    size_t n = order.size();
    for (size_t i = 0; i != n; ++i)
        table[order[i]].i = 125;
}

inline void insert(IntTable& table, const vector<size_t> order)
{
    size_t n = order.size();
    for (size_t i = 0; i != n; ++i)
        table.insert(order[i], 127);
}

inline void erase(IntTable& table, const vector<size_t> order)
{
    size_t n = order.size();
    for (size_t i = 0; i != n; ++i)
        table.remove(order[i]);
}

} // anonymous namepsace

int main()
{
    const size_t target_size = 1100*1000L;
    const int num_tables = 50;
    cout << "Number of tables: " << num_tables << endl;
    cout << "Elements per table: " << target_size << endl;

    vector<size_t> rising_order;
    vector<size_t> falling_order;
    vector<size_t> random_order;
    vector<size_t> random_insert_order;
    vector<size_t> random_erase_order;
    for (size_t i = 0; i != target_size; ++i) {
        rising_order.push_back(i);
        falling_order.push_back(target_size-1-i);
        random_order.push_back(i);
        random_insert_order.push_back(rand() % (i+1));
        random_erase_order.push_back(rand() % (target_size-i));
    }
    Random random;
    random.shuffle(random_order.begin(), random_order.end());

    IntTable tables_1[num_tables], tables_2[num_tables];

    int_fast64_t dummy = 0;

    int max_lead_text_size = 26;
    BenchmarkResults results(max_lead_text_size);

    Timer timer_total(Timer::type_UserTime);
    Timer timer(Timer::type_UserTime);
    {
        timer.reset();
        for (int i = 0; i != num_tables; ++i)
            insert(tables_1[i], rising_order);
        results.submit(timer, "insert_end_compact", "Insert at end (compact)");
        timer.reset();
        for (int i = 0; i != num_tables; ++i)
            dummy += read(tables_1[i], rising_order);
        results.submit(timer, "read_seq_compact", "Sequential read (compact)");
        timer.reset();
        for (int i = 0; i != num_tables; ++i)
            dummy += read(tables_1[i], random_order);
        results.submit(timer, "read_ran_compact", "Random read (compact)");
        timer.reset();
        for (int i = 0; i != num_tables; ++i)
            write(tables_1[i], rising_order);
        results.submit(timer, "write_seq_compact", "Sequential write (compact)");
        timer.reset();
        for (int i = 0; i != num_tables; ++i)
            write(tables_1[i], random_order);
        results.submit(timer, "write_ran_compact", "Random write (compact)");
        timer.reset();
        for (int i = 0; i != num_tables; ++i)
            erase(tables_1[i], falling_order);
        results.submit(timer, "erase_end_compact", "Erase from end (compact)");
    }
    {
        timer.reset();
        for (int i = 0; i != num_tables; ++i)
            insert(tables_2[i], random_insert_order);
        results.submit(timer, "insert_ran_general", "Random insert (general)");
        timer.reset();
        for (int i = 0; i != num_tables; ++i)
            dummy += read(tables_2[0], rising_order);
        results.submit(timer, "read_seq_general", "Sequential read (general)");
        timer.reset();
        for (int i = 0; i != num_tables; ++i)
            dummy += read(tables_2[0], random_order);
        results.submit(timer, "read_ran_general", "Random read (general)");
        timer.reset();
        for (int i = 0; i != num_tables; ++i)
            write(tables_2[i], rising_order);
        results.submit(timer, "write_seq_general", "Sequential write (general)");
        timer.reset();
        for (int i = 0; i != num_tables; ++i)
            write(tables_2[i], random_order);
        results.submit(timer, "write_ran_general", "Random write (general)");
        timer.reset();
        for (int i = 0; i != num_tables; ++i)
            erase(tables_2[i], random_erase_order);
        results.submit(timer, "erase_ran_general", "Random erase (general)");
    }

    results.submit(timer_total, "total_time", "Total time");

    cout << "dummy = "<<dummy<<" (to avoid over-optimization)"<<endl;
}
<|endoftext|>


<commit_before>#include "error.hpp"
#include "Node.hpp"

#include <boost/algorithm/string/join.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/exception/diagnostic_information.hpp>

namespace configure {

	std::string error_string()
	{ return error_string(std::current_exception()); }

	static std::string what(std::exception_ptr const& e)
	{
		try { std::rethrow_exception(e); }
		catch (std::exception const& err) { return err.what(); }
		catch (...) { return "Error:"; }
		std::abort();
	}

	std::string error_string(std::exception_ptr const& e, unsigned int indent)
	{
		using boost::get_error_info;
		std::string padding(' ', indent);
		std::string res = padding + what(e) + "\n";
		try { std::rethrow_exception(e); }
		catch (boost::exception const& e) {
			if (auto ptr = get_error_info<error::path>(e))
				res += padding + "  Path: " + ptr->string() + "\n";
			if (auto ptr = get_error_info<error::lua_function>(e))
				res += padding + "  Lua function: " + *ptr + "\n";
			if (auto ptr = get_error_info<error::node>(e))
				res += padding + "  Node: " + (*ptr)->string() + "\n";
			if (auto ptr = get_error_info<error::lua_traceback>(e))
			{
				res += padding + "  Lua traceback:\n";
				for (auto const& frame: *ptr)
				{
					if (frame.builtin &&frame.name.empty())
						continue;
					res += padding + "    ";
					if (frame.builtin)
						res += "{builtin}: ";
					else
						res += frame.source.string() + ":" +
							std::to_string(frame.current_line) + ": ";

					res += "in ";
					if (!frame.kind.empty())
						res += frame.kind + " ";
					if (frame.kind != "method")
						res += "function ";
					if (!frame.name.empty())
						res += frame.name + "() ";
					if (!frame.builtin)
						res += "defined at " + frame.source.filename().string() + ":" +
							std::to_string(frame.first_function_line);
					res += "\n";
				}
			}
			if (auto ptr = get_error_info<error::command>(e))
				res += padding + "  Command: " + boost::join(*ptr, " ");
			if (auto ptr = get_error_info<error::nested>(e))
				res += padding + "  Initial error: " + error_string(*ptr, indent + 2);
		}
		catch (...) {}
		return boost::trim_right_copy(res);
	}

}
<commit_msg>Fix indent string in error formatter.<commit_after>#include "error.hpp"
#include "Node.hpp"

#include <boost/algorithm/string/join.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/exception/diagnostic_information.hpp>

namespace configure {

	std::string error_string()
	{ return error_string(std::current_exception()); }

	static std::string what(std::exception_ptr const& e)
	{
		try { std::rethrow_exception(e); }
		catch (std::exception const& err) { return err.what(); }
		catch (...) { return "Error:"; }
		std::abort();
	}

	std::string error_string(std::exception_ptr const& e, unsigned int indent)
	{
		using boost::get_error_info;
		std::string padding(indent, ' ');
		std::string res = padding + what(e) + "\n";
		try { std::rethrow_exception(e); }
		catch (boost::exception const& e) {
			if (auto ptr = get_error_info<error::path>(e))
				res += padding + "  Path: " + ptr->string() + "\n";
			if (auto ptr = get_error_info<error::lua_function>(e))
				res += padding + "  Lua function: " + *ptr + "\n";
			if (auto ptr = get_error_info<error::node>(e))
				res += padding + "  Node: " + (*ptr)->string() + "\n";
			if (auto ptr = get_error_info<error::lua_traceback>(e))
			{
				res += padding + "  Lua traceback:\n";
				for (auto const& frame: *ptr)
				{
					if (frame.builtin &&frame.name.empty())
						continue;
					res += padding + "    ";
					if (frame.builtin)
						res += "{builtin}: ";
					else
						res += frame.source.string() + ":" +
							std::to_string(frame.current_line) + ": ";

					res += "in ";
					if (!frame.kind.empty())
						res += frame.kind + " ";
					if (frame.kind != "method")
						res += "function ";
					if (!frame.name.empty())
						res += frame.name + "() ";
					if (!frame.builtin)
						res += "defined at " + frame.source.filename().string() + ":" +
							std::to_string(frame.first_function_line);
					res += "\n";
				}
			}
			if (auto ptr = get_error_info<error::command>(e))
				res += padding + "  Command: " + boost::join(*ptr, " ");
			if (auto ptr = get_error_info<error::nested>(e))
				res += padding + "  Initial error: " + error_string(*ptr, indent + 2);
		}
		catch (...) {}
		return boost::trim_right_copy(res);
	}

}
<|endoftext|>


<commit_before>/// \file urbi/ustarter.hxx

// This file is part of UObject Component Architecture
// Copyright (c) 2007, 2008 Gostai S.A.S.
//
// Permission to use, copy, modify, and redistribute this software for
// non-commercial use is hereby granted.
//
// This software is provided "as is" without warranty of any kind,
// either expressed or implied, including but not limited to the
// implied warranties of fitness for a particular purpose.
//
// For more information, comments, bug reports: http://www.urbiforge.com

#ifndef URBI_STARTER_HXX
# define URBI_STARTER_HXX

# include <algorithm>
# include <string>

# include <urbi/fwd.hh>
# include <urbi/ustarter.hh>

namespace urbi
{

  /*------------------.
  | baseURBIStarter.  |
  `------------------*/

  inline
  baseURBIStarter::baseURBIStarter(const std::string& name, bool local)
    : name(name)
    , local(local)
  {}

  inline
  baseURBIStarter::~baseURBIStarter()
  {}

  /*--------------.
  | URBIStarter.  |
  `--------------*/
  template <class T>
  inline
  URBIStarter<T>::URBIStarter(const std::string& name, UStartlist& slist, bool local)
    : baseURBIStarter(name, local)
    , slist_(slist)
  {
    slist_.push_back(this);
  }

  template <class T>
  inline
  URBIStarter<T>::~URBIStarter()
  {
    clean();
  }

  template <class T>
  inline
  void
  URBIStarter<T>::clean()
  {
    delete getUObject();
    for (UStartlist::iterator i = slist_.begin();
	 i != slist_.end();
	 ++i)
      if (*i == this)
      {
	slist_.erase(i);
	break;
      }
  }

  template <class T>
  inline
  void
  URBIStarter<T>::copy(const std::string& objname)
  {
    URBIStarter<T>* ustarter = new URBIStarter<T>(objname, slist_, local);
    ustarter->init(objname);
    UObject* uso = ustarter->object;
    getUObject()->members.push_back(uso);
    uso->derived = true;
    uso->classname = getUObject()->classname;
    if (uso->autogroup)
      uso->addAutoGroup();
  }

  /// Access to the object from the outside.
  template <class T>
  inline
  UObject*
  URBIStarter<T>::getUObject()
  {
    return object;
  }

  template <class T>
  inline
  void
  URBIStarter<T>::init(const std::string& objname)
  {
    std::string fullname = objname;
    urbi::UAbstractClient* cli = (UAbstractClient*)getDefaultClient ();
    if (local && cli)
    {
      fullname += "_" + getClientConnectionID (cli);
      name = fullname;
    }
    object = new T(fullname);
  }

    /*---------------------.
    | baseURBIStarterHub.  |
    `---------------------*/

  inline
  baseURBIStarterHub::baseURBIStarterHub(const std::string& name)
    : name(name)
  {}

  inline
  baseURBIStarterHub::~baseURBIStarterHub()
  {}

    /*-----------------.
    | URBIStarterHub.  |
    `-----------------*/

  template <class T>
  inline
  URBIStarterHub<T>::URBIStarterHub(const std::string& name,
                                    UStartlistHub& slist)
    : baseURBIStarterHub(name)
    , slist_(slist)
  {
    slist_.push_back(this);
  }

  template <class T>
  inline
  URBIStarterHub<T>::~URBIStarterHub()
  {
    /* noone can kill a hub*/
  }

  template <class T>
  inline
  void
  URBIStarterHub<T>::init(const std::string& objname)
  {
    object = new T(objname);
  }

  /// Access to the object from the outside.
  template <class T>
  inline
  UObjectHub*
  URBIStarterHub<T>::getUObjectHub()
  {
    return object;
  }

} // end namespace urbi

#endif // !URBI_STARTER_HXX
<commit_msg>Formatting changes.<commit_after>/// \file urbi/ustarter.hxx

// This file is part of UObject Component Architecture
// Copyright (c) 2007, 2008 Gostai S.A.S.
//
// Permission to use, copy, modify, and redistribute this software for
// non-commercial use is hereby granted.
//
// This software is provided "as is" without warranty of any kind,
// either expressed or implied, including but not limited to the
// implied warranties of fitness for a particular purpose.
//
// For more information, comments, bug reports: http://www.urbiforge.com

#ifndef URBI_STARTER_HXX
# define URBI_STARTER_HXX

# include <algorithm>
# include <string>

# include <urbi/fwd.hh>
# include <urbi/ustarter.hh>

namespace urbi
{

  /*------------------.
  | baseURBIStarter.  |
  `------------------*/

  inline
  baseURBIStarter::baseURBIStarter(const std::string& name, bool local)
    : name(name)
    , local(local)
  {}

  inline
  baseURBIStarter::~baseURBIStarter()
  {}

  /*--------------.
  | URBIStarter.  |
  `--------------*/
  template <class T>
  inline
  URBIStarter<T>::URBIStarter(const std::string& name,
                              UStartlist& slist, bool local)
    : baseURBIStarter(name, local)
    , slist_(slist)
  {
    slist_.push_back(this);
  }

  template <class T>
  inline
  URBIStarter<T>::~URBIStarter()
  {
    clean();
  }

  template <class T>
  inline
  void
  URBIStarter<T>::clean()
  {
    delete getUObject();
    for (UStartlist::iterator i = slist_.begin();
	 i != slist_.end();
	 ++i)
      if (*i == this)
      {
	slist_.erase(i);
	break;
      }
  }

  template <class T>
  inline
  void
  URBIStarter<T>::copy(const std::string& objname)
  {
    URBIStarter<T>* ustarter = new URBIStarter<T>(objname, slist_, local);
    ustarter->init(objname);
    UObject* uso = ustarter->object;
    getUObject()->members.push_back(uso);
    uso->derived = true;
    uso->classname = getUObject()->classname;
    if (uso->autogroup)
      uso->addAutoGroup();
  }

  /// Access to the object from the outside.
  template <class T>
  inline
  UObject*
  URBIStarter<T>::getUObject()
  {
    return object;
  }

  template <class T>
  inline
  void
  URBIStarter<T>::init(const std::string& objname)
  {
    std::string fullname = objname;
    urbi::UAbstractClient* cli = (UAbstractClient*)getDefaultClient ();
    if (local && cli)
    {
      fullname += "_" + getClientConnectionID (cli);
      name = fullname;
    }
    object = new T(fullname);
  }

    /*---------------------.
    | baseURBIStarterHub.  |
    `---------------------*/

  inline
  baseURBIStarterHub::baseURBIStarterHub(const std::string& name)
    : name(name)
  {}

  inline
  baseURBIStarterHub::~baseURBIStarterHub()
  {}

    /*-----------------.
    | URBIStarterHub.  |
    `-----------------*/

  template <class T>
  inline
  URBIStarterHub<T>::URBIStarterHub(const std::string& name,
                                    UStartlistHub& slist)
    : baseURBIStarterHub(name)
    , slist_(slist)
  {
    slist_.push_back(this);
  }

  template <class T>
  inline
  URBIStarterHub<T>::~URBIStarterHub()
  {
    /* noone can kill a hub*/
  }

  template <class T>
  inline
  void
  URBIStarterHub<T>::init(const std::string& objname)
  {
    object = new T(objname);
  }

  /// Access to the object from the outside.
  template <class T>
  inline
  UObjectHub*
  URBIStarterHub<T>::getUObjectHub()
  {
    return object;
  }

} // end namespace urbi

#endif // !URBI_STARTER_HXX
<|endoftext|>


<commit_before>/*******************************************************************************
 *  Code contributed to the webinos project
 *
 * 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.
 *
 * Copyright 2012 Torsec -Computer and network security group-
 * Politecnico di Torino
 *
 ******************************************************************************/

#include "Obligation.h"

Obligation::Obligation(TiXmlElement* obligation){

	// TriggerSet Tag
	if(obligation->FirstChild("TriggersSet")){
		triggersset = new TriggersSet((TiXmlElement*)obligation->FirstChild("TriggersSet"));
	}
	else
		triggersset = NULL;

	// Action Tag
	if(obligation->FirstChild("ActionDeletePersonalData")){
		action["actionID"] = "ActionDeletePersonalData";
	}
	else if(obligation->FirstChild("ActionAnonymizePersonalData")){
		action["actionID"] = "ActionAnonymizePersonalData";
	}
	else if(obligation->FirstChild("ActionNotifyDataSubject")){
		action["actionID"] = "ActionNotifyDataSubject";
		action["Media"] = ((TiXmlElement*)obligation->FirstChild("ActionNotifyDataSubject"))->Attribute("Media");
		action["Address"] = ((TiXmlElement*)obligation->FirstChild("ActionNotifyDataSubject"))->Attribute("Address");
	}
	else if(obligation->FirstChild("ActionLog")){
		action["actionID"] = "ActionLog";
	}
	else if(obligation->FirstChild("ActionSecureLog")){
		action["actionID"] = "ActionSecureLog";
	}
}

Obligation::~Obligation(){
}

bool Obligation::evaluate(Request * req){

	if (action.empty() == true)
		return true;

	// TODO evaluate if DELETE is satisfied
	// TODO evaluate if ANONYMIZE is satisfied
	// TODO evaluate if NOTIFY is satisfied (check media and address parameters too)
	// TODO evaluate if LOG is satisfied (by LOG or SECURELOG)
	// TODO evaluate if SECURELOG is satisfied

	// TODO if not satisfied return false

	return triggersset->evaluate(req);
}
<commit_msg>Bugfixing in actions parsing<commit_after>/*******************************************************************************
 *  Code contributed to the webinos project
 *
 * 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.
 *
 * Copyright 2012 Torsec -Computer and network security group-
 * Politecnico di Torino
 *
 ******************************************************************************/

#include "Obligation.h"

Obligation::Obligation(TiXmlElement* obligation){

	TiXmlElement* child;

	// TriggerSet Tag
	if(obligation->FirstChild("TriggersSet")){
		triggersset = new TriggersSet((TiXmlElement*)obligation->FirstChild("TriggersSet"));
	}
	else
		triggersset = NULL;

	// Action Tag
	if(obligation->FirstChild("ActionDeletePersonalData")){
		action["actionID"] = "ActionDeletePersonalData";
	}
	else if(obligation->FirstChild("ActionAnonymizePersonalData")){
		action["actionID"] = "ActionAnonymizePersonalData";
	}
	else if(child = (TiXmlElement*)obligation->FirstChild("ActionNotifyDataSubject")){
		action["actionID"] = "ActionNotifyDataSubject";
		action["Media"] = child->FirstChild("Media")->GetText();
		action["Address"] = child->FirstChild("Address")->GetText();
	}
	else if(obligation->FirstChild("ActionLog")){
		action["actionID"] = "ActionLog";
	}
	else if(obligation->FirstChild("ActionSecureLog")){
		action["actionID"] = "ActionSecureLog";
	}
}

Obligation::~Obligation(){
}

bool Obligation::evaluate(Request * req){

	if (action.empty() == true)
		return true;

	// TODO evaluate if DELETE is satisfied
	// TODO evaluate if ANONYMIZE is satisfied
	// TODO evaluate if NOTIFY is satisfied (check media and address parameters too)
	// TODO evaluate if LOG is satisfied (by LOG or SECURELOG)
	// TODO evaluate if SECURELOG is satisfied

	// TODO if not satisfied return false

	return triggersset->evaluate(req);
}
<|endoftext|>


<commit_before>// Copyright (c) 2020 by Robert Bosch GmbH. 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.

#pragma once

#include <atomic>
#include <chrono>
#include <functional>
#include <memory>
#include <thread>

#include <iceoryx_posh/iceoryx_posh_types.hpp>
#include <iceoryx_posh/popo/subscriber.hpp>
#include <iceoryx_posh/runtime/posh_runtime.hpp>

#include "ioxdds/dds/data_writer.hpp"
#include "ioxdds/dds/dds_configs.hpp"
#include "ioxdds/dds/dds_types.hpp"
#include "ioxdds/gateway/dds_gateway_generic.hpp"
#include "ioxdds/gateway/channel.hpp"

namespace iox
{
namespace dds
{
///
/// @brief A Gateway to support internode communication between iceoryx nodes in a DDS network.
///
/// Forwards data published in a local posh runtime to an attached DDS network.
///
template <typename channel_t = iox::dds::Channel<iox::popo::Subscriber, iox::dds::data_writer_t>>
class Iceoryx2DDSGateway : public iox::dds::DDSGatewayGeneric<channel_t>
{
  public:
    Iceoryx2DDSGateway() noexcept;
    void discover(const iox::capro::CaproMessage& msg) noexcept;
    void forward() noexcept;
};

} // dds
} // iox

#include "ioxdds/internal/gateway/iox_to_dds.inl"
<commit_msg>iox-#65 Rename module to iceoryx_dds.<commit_after><|endoftext|>


<commit_before>//  (C) Copyright Gennadiy Rozental 2011-2014.
//  Distributed under the Boost Software License, Version 1.0.
//  (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)

//  See http://www.boost.org/libs/test for the library home page.
//
//!@file
//!@brief Random generator
// ***************************************************************************

#ifndef BOOST_TEST_DATA_MONOMORPHIC_GENERATORS_RANDOM_HPP_101512GER
#define BOOST_TEST_DATA_MONOMORPHIC_GENERATORS_RANDOM_HPP_101512GER

// Boost.Test
#include <boost/test/data/config.hpp>

#if (!defined(BOOST_NO_CXX11_HDR_RANDOM) && !defined(BOOST_NO_CXX11_RVALUE_REFERENCES)) || defined(BOOST_TEST_DOXYGEN_DOC__)

#include <boost/test/data/monomorphic/generate.hpp>
#include <boost/test/data/monomorphic/generators/keywords.hpp>

// STL
#include <random>

#include <boost/test/detail/suppress_warnings.hpp>

//____________________________________________________________________________//

namespace boost {
namespace unit_test {
namespace data {

namespace {
nfp::keyword<struct seed_t>         seed;
nfp::keyword<struct distrbution_t>  distribution;
nfp::keyword<struct engine_t>       engine;
} // local namespace

namespace monomorphic {

namespace ds_detail {
template<typename SampleType>
struct default_distribution {
    typedef typename mpl::if_<std::is_integral<SampleType>,
                              std::uniform_int_distribution<SampleType>,
                              std::uniform_real_distribution<SampleType> >::type type;
};

} // namespace ds_detail

// ************************************************************************** //
// **************                   random_t                   ************** //
// ************************************************************************** //

template<typename SampleType        = double,
         typename DistributionType  = typename ds_detail::default_distribution<SampleType>::type,
         typename EngineType        = std::default_random_engine>
class random_t {
public:
    typedef SampleType          data_type;
    typedef DistributionType    distr_type;
    typedef EngineType          engine_type;

    random_t()
    : m_distribution()
    , m_engine( std::random_device()() )
    {}
    explicit random_t( distr_type&& d )
    : m_distribution( std::forward<distr_type>(d) )
    , m_engine( std::random_device()() ){}
    random_t( engine_type&& e, distr_type&& d )
    : m_distribution( std::forward<distr_type>(d) )
    , m_engine( std::forward<engine_type>(e) ){}

    // Generator interface
    data::size_t        capacity() const    { return BOOST_TEST_DS_INFINITE_SIZE; }
    SampleType          next()
    {
        return m_distribution( m_engine );
    }
    template<typename SeedType>
    void seed( SeedType&& seed )            { m_engine.seed( std::forward<SeedType>( seed ) ); }

private:
    // Data members
    DistributionType    m_distribution;
    EngineType          m_engine;
};

//____________________________________________________________________________//

} // namespace monomorphic

//! @brief Returns an infinite sequence of random (real) numbers.
//!
//! The generator uses the default distribution, which is uniform in [0, 1).
//!
//! @param begin Generates random numbers in the given interval: the generator uses the default distribution, which is uniform (in [begin, end) for real numbers, and in
//! [begin, end] for integers).
//! @param end
//!
//! @param params parameter of the random distribution that can be set:
//!   - distribution
//!   - seed
//!   - random number generator engine
inline monomorphic::generated_by<monomorphic::random_t<>>
random()
{
    return monomorphic::generated_by<monomorphic::random_t<>>( monomorphic::random_t<>() );
}

//____________________________________________________________________________//

/*!
 * @overload boost::unit_test::data::random()
 */
template<typename SampleType>
inline monomorphic::generated_by<monomorphic::random_t<SampleType>>
random( SampleType begin, SampleType end )
{
    typedef monomorphic::random_t<SampleType> Gen;
    typedef typename Gen::distr_type distr_type;
    return monomorphic::generated_by<Gen>( Gen( distr_type(begin,end) ) );
}

//____________________________________________________________________________//

namespace ds_detail {
template<typename Params>
struct random_gen_type {
    typedef typename nfp::param_type<Params,decltype(distribution),std::uniform_real_distribution<>>::type distr_type;
    typedef typename nfp::param_type<Params,decltype(engine),std::default_random_engine>::type engine_type;
    typedef typename distr_type::result_type sample_type;

    typedef monomorphic::random_t<sample_type,distr_type,engine_type> type;
};

}

/*!
 * @overload boost::unit_test::data::random()
 */
template<typename Params>
inline monomorphic::generated_by<typename ds_detail::random_gen_type<Params>::type>
random( Params const& params )
{
    typedef typename ds_detail::random_gen_type<Params>::type Gen;
    typedef typename Gen::distr_type distr_type;
    typedef typename Gen::engine_type engine_type;

    std::random_device rd;
    engine_type E;
//    engine_type E( rd );
    if( params.has(engine) )
        E = params[engine];

    distr_type D;
    if( params.has(distribution) )
        D = params[distribution];

    Gen G( std::move(E), std::move(D) );

    if( params.has(seed) )
        G.seed( params[seed] );

    return monomorphic::generated_by<Gen>( std::move(G) );
}

} // namespace data
} // namespace unit_test
} // namespace boost

#include <boost/test/detail/enable_warnings.hpp>

#endif // (!defined(BOOST_NO_CXX11_HDR_RANDOM) && !defined(BOOST_NO_CXX11_RVALUE_REFERENCES)) || defined(BOOST_TEST_DOXYGEN_DOC__)

#endif // BOOST_TEST_DATA_MONOMORPHIC_GENERATORS_RANDOM_HPP_101512GER
<commit_msg>Trying to work out the deficiencies of dox+quickbook<commit_after>//  (C) Copyright Gennadiy Rozental 2011-2014.
//  Distributed under the Boost Software License, Version 1.0.
//  (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)

//  See http://www.boost.org/libs/test for the library home page.
//
//!@file
//!@brief Random generator
// ***************************************************************************

#ifndef BOOST_TEST_DATA_MONOMORPHIC_GENERATORS_RANDOM_HPP_101512GER
#define BOOST_TEST_DATA_MONOMORPHIC_GENERATORS_RANDOM_HPP_101512GER

// Boost.Test
#include <boost/test/data/config.hpp>

#if (!defined(BOOST_NO_CXX11_HDR_RANDOM) && !defined(BOOST_NO_CXX11_RVALUE_REFERENCES)) || defined(BOOST_TEST_DOXYGEN_DOC__)

#include <boost/test/data/monomorphic/generate.hpp>
#include <boost/test/data/monomorphic/generators/keywords.hpp>

// STL
#include <random>

#include <boost/test/detail/suppress_warnings.hpp>

//____________________________________________________________________________//

namespace boost {
namespace unit_test {
namespace data {

namespace {
nfp::keyword<struct seed_t>         seed;
nfp::keyword<struct distrbution_t>  distribution;
nfp::keyword<struct engine_t>       engine;
} // local namespace

namespace monomorphic {

namespace ds_detail {
template<typename SampleType>
struct default_distribution {
    typedef typename mpl::if_<std::is_integral<SampleType>,
                              std::uniform_int_distribution<SampleType>,
                              std::uniform_real_distribution<SampleType> >::type type;
};

} // namespace ds_detail

// ************************************************************************** //
// **************                   random_t                   ************** //
// ************************************************************************** //

template<typename SampleType        = double,
         typename DistributionType  = typename ds_detail::default_distribution<SampleType>::type,
         typename EngineType        = std::default_random_engine>
class random_t {
public:
    typedef SampleType          data_type;
    typedef DistributionType    distr_type;
    typedef EngineType          engine_type;

    random_t()
    : m_distribution()
    , m_engine( std::random_device()() )
    {}
    explicit random_t( distr_type&& d )
    : m_distribution( std::forward<distr_type>(d) )
    , m_engine( std::random_device()() ){}
    random_t( engine_type&& e, distr_type&& d )
    : m_distribution( std::forward<distr_type>(d) )
    , m_engine( std::forward<engine_type>(e) ){}

    // Generator interface
    data::size_t        capacity() const    { return BOOST_TEST_DS_INFINITE_SIZE; }
    SampleType          next()
    {
        return m_distribution( m_engine );
    }
    template<typename SeedType>
    void seed( SeedType&& seed )            { m_engine.seed( std::forward<SeedType>( seed ) ); }

private:
    // Data members
    DistributionType    m_distribution;
    EngineType          m_engine;
};

//____________________________________________________________________________//

} // namespace monomorphic

//! @brief Returns an infinite sequence of random numbers.
//!
//! * <tt>auto d = random();</tt> The generator uses the default distribution, which is uniform in [0, 1).
//! * <tt>auto d = random(begin, end);</tt> Generates random numbers in the given interval: the generator uses the default distribution, which is uniform (in [begin, end) for real numbers, and in
//!   [begin, end] for integers).
//! * <tt>auto d = random(param);</tt> Generates random numbers using the settings inside the parameter @c param :
//!   - distribution
//!   - seed
//!   - random number generator engine
inline monomorphic::generated_by<monomorphic::random_t<>>
random()
{
    return monomorphic::generated_by<monomorphic::random_t<>>( monomorphic::random_t<>() );
}

//____________________________________________________________________________//

/*!
 * @overload boost::unit_test::data::random()
 */
template<typename SampleType>
inline monomorphic::generated_by<monomorphic::random_t<SampleType>>
random( SampleType begin, SampleType end )
{
    typedef monomorphic::random_t<SampleType> Gen;
    typedef typename Gen::distr_type distr_type;
    return monomorphic::generated_by<Gen>( Gen( distr_type(begin,end) ) );
}

//____________________________________________________________________________//

namespace ds_detail {
template<typename Params>
struct random_gen_type {
    typedef typename nfp::param_type<Params,decltype(distribution),std::uniform_real_distribution<>>::type distr_type;
    typedef typename nfp::param_type<Params,decltype(engine),std::default_random_engine>::type engine_type;
    typedef typename distr_type::result_type sample_type;

    typedef monomorphic::random_t<sample_type,distr_type,engine_type> type;
};

}

/*!
 * @overload boost::unit_test::data::random()
 */
template<typename Params>
inline monomorphic::generated_by<typename ds_detail::random_gen_type<Params>::type>
random( Params const& params )
{
    typedef typename ds_detail::random_gen_type<Params>::type Gen;
    typedef typename Gen::distr_type distr_type;
    typedef typename Gen::engine_type engine_type;

    std::random_device rd;
    engine_type E;
//    engine_type E( rd );
    if( params.has(engine) )
        E = params[engine];

    distr_type D;
    if( params.has(distribution) )
        D = params[distribution];

    Gen G( std::move(E), std::move(D) );

    if( params.has(seed) )
        G.seed( params[seed] );

    return monomorphic::generated_by<Gen>( std::move(G) );
}

} // namespace data
} // namespace unit_test
} // namespace boost

#include <boost/test/detail/enable_warnings.hpp>

#endif // (!defined(BOOST_NO_CXX11_HDR_RANDOM) && !defined(BOOST_NO_CXX11_RVALUE_REFERENCES)) || defined(BOOST_TEST_DOXYGEN_DOC__)

#endif // BOOST_TEST_DATA_MONOMORPHIC_GENERATORS_RANDOM_HPP_101512GER
<|endoftext|>