<commit_before>/*************************************************************************
 *
 *  $RCSfile: component_context.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: dbo $ $Date: 2001-06-01 11:47:46 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifdef _DEBUG
#include <stdio.h>
#endif

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

#ifndef _CPPUHELPER_IMPLBASE1_HXX
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _CPPUHELPER_COMPBASE1_HXX
#include <cppuhelper/compbase1.hxx>
#endif
#ifndef _CPPUHELPER_COMPONENT_CONTEXT_HXX
#include <cppuhelper/component_context.hxx>
#endif

#include <com/sun/star/lang/XMultiComponentFactory.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/registry/XSimpleRegistry.hpp>

#include <hash_map>

using namespace ::osl;
using namespace ::rtl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star;

namespace cppu
{

//==================================================================================================
class Disposer_Impl
    : public WeakImplHelper1< lang::XEventListener >
{
    Reference< lang::XComponent > m_xTarget;

public:
    inline Disposer_Impl( Reference< lang::XComponent > const & xTarget )
        SAL_THROW( () )
        : m_xTarget( xTarget )
        { OSL_ASSERT( m_xTarget.is() ); }

    virtual void SAL_CALL disposing( lang::EventObject const & rSource )
        throw (RuntimeException);
};
//__________________________________________________________________________________________________
void Disposer_Impl::disposing( lang::EventObject const & rSource )
    throw (RuntimeException)
{
    m_xTarget->dispose();
    m_xTarget.clear();
}

//==================================================================================================
struct MutexHolder
{
    Mutex m_mutex;
};
//==================================================================================================
class ComponentContext
    : public MutexHolder
    , public WeakComponentImplHelper1< XComponentContext >
{
    Reference< XComponentContext > m_xDelegate;

    struct ContextEntry
    {
        bool bLateInitService;
        Any value;

        inline ContextEntry( bool bLateInitService_, Any const & value_ )
            : bLateInitService( bLateInitService_ )
            , value( value_ )
            {}
    };
    typedef ::std::hash_map< OUString, ContextEntry *, OUStringHash > t_map;
    t_map m_map;

    Reference< lang::XMultiComponentFactory > m_xSMgr;
    // denotes if service manager has to be disposed by this context,
    // else it was retieved from a delegate which itself has to dispose it
    bool m_bDisposeSMgr;

protected:
    virtual void SAL_CALL disposing();

public:
    ComponentContext(
        ContextEntry_Init const * pEntries, sal_Int32 nEntries,
        Reference< XComponentContext > const & xDelegate )
        SAL_THROW( () );
    ComponentContext(
        ContextEntry_Init const * pEntries, sal_Int32 nEntries,
        Reference< registry::XSimpleRegistry > const & xRegistry )
        SAL_THROW( () );
    virtual ~ComponentContext();

    // XComponentContext
    virtual Any SAL_CALL getValueByName( OUString const & rName )
        throw (RuntimeException);
    virtual Reference< lang::XMultiComponentFactory > SAL_CALL getServiceManager()
        throw (RuntimeException);
};
//__________________________________________________________________________________________________
Any ComponentContext::getValueByName( OUString const & rName )
    throw (RuntimeException)
{
    /** map is anytime untouched, if an uninit value will be inited, synch is done on mutex.
     */

    t_map::const_iterator const iFind( m_map.find( rName ) );
    if (iFind != m_map.end())
    {
        ContextEntry * pEntry = iFind->second;

        if (pEntry->bLateInitService)
        {
            try
            {
                Reference< XInterface > xInstance;

                Reference< lang::XSingleComponentFactory > xFac;
                if (pEntry->value >>= xFac) // try via factory
                {
                    xInstance = xFac->createInstanceWithContext( this );
                }
                else // optionally service name
                {
                    OUString aServiceName;
                    if ((pEntry->value >>= aServiceName) && aServiceName.getLength())
                    {
                        if (m_xSMgr.is())
                        {
                            xInstance = m_xSMgr->createInstanceWithContext( aServiceName, this );
                        }
#ifdef _DEBUG
                        else
                        {
                            ::fprintf( stderr, "### no service manager given for instanciating singletons!\n" );
                        }
#endif
                    }
                }

                if (xInstance.is())
                {
                    ClearableMutexGuard aGuard( m_mutex );
                    if (! pEntry->bLateInitService) // inited in the meantime?
                    {
                        aGuard.clear();
                        // service has entered the context in the meantime
                        // => try to dispose this one
                        Reference< lang::XComponent > xComp( xInstance, UNO_QUERY );
                        if (xComp.is())
                        {
                            xComp->dispose();
                        }
                    }
                    else
                    {
                        pEntry->value.setValue( &xInstance, ::getCppuType( &xInstance ) );
                        pEntry->bLateInitService = false;
                    }

                    return pEntry->value;
                }
                else
                {
                    OString aStr( OUStringToOString( rName, RTL_TEXTENCODING_ASCII_US ) );
                    OSL_TRACE( "### cannot raise singleton: $s\n", aStr.getStr() );
                }
            }
            catch (Exception & rExc)
            {
#ifdef _DEBUG
                OString aStr( OUStringToOString( rName, RTL_TEXTENCODING_ASCII_US ) );
                OString aStr2( OUStringToOString( rExc.Message, RTL_TEXTENCODING_ASCII_US ) );
                ::fprintf( stderr, "### exception occured raising singleton %s: %s\n", aStr.getStr(), aStr2.getStr() );
#endif
            }
        }
        else
        {
            return pEntry->value;
        }

        return Any(); // error occured
    }

    if (m_xDelegate.is())
    {
        return m_xDelegate->getValueByName( rName );
    }

    return Any();
}
//__________________________________________________________________________________________________
Reference< lang::XMultiComponentFactory > ComponentContext::getServiceManager()
    throw (RuntimeException)
{
    return m_xSMgr;
}
//__________________________________________________________________________________________________
ComponentContext::~ComponentContext()
{
#ifdef DEBUG
    ::fprintf( stderr, "> destructed context %p\n", this );
#endif
}
//__________________________________________________________________________________________________
void ComponentContext::disposing()
{
#ifdef DEBUG
    ::fprintf( stderr, "> disposing context %p\n", this );
#endif

    // dispose all context objects
    t_map::const_iterator iPos( m_map.begin() );
    for ( ; iPos != m_map.end(); ++iPos )
    {
        ContextEntry * pEntry = iPos->second;
        Reference< lang::XComponent > xComp;

        if (pEntry->bLateInitService)
        {
            // may be in late init
            MutexGuard aGuard( m_mutex );
            pEntry->value >>= xComp;
        }
        else
        {
            pEntry->value >>= xComp;
        }

        if (xComp.is())
        {
            xComp->dispose();
        }
    }

    // dispose service manager
    if (m_bDisposeSMgr)
    {
        Reference< lang::XComponent > xComp( m_xSMgr, UNO_QUERY );
        if (xComp.is())
        {
            xComp->dispose();
        }
    }

    // everything is disposed, hopefully nobody accesses the context anymore...
    for ( iPos = m_map.begin(); iPos != m_map.end(); ++iPos )
    {
        delete iPos->second;
    }
    m_map.clear();
}
//__________________________________________________________________________________________________
ComponentContext::ComponentContext(
    ContextEntry_Init const * pEntries, sal_Int32 nEntries,
    Reference< XComponentContext > const & xDelegate )
    SAL_THROW( () )
    : WeakComponentImplHelper1< XComponentContext >( m_mutex )
    , m_xDelegate( xDelegate )
{
    while (nEntries--)
    {
        ContextEntry_Init const & rEntry = pEntries[ nEntries ];

        if (rEntry.name.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM("com.sun.star.lang.ServiceManager") ))
        {
            if (rEntry.value >>= m_xSMgr)
                continue;
        }
        m_map[ rEntry.name ] = new ContextEntry( rEntry.bLateInitService, rEntry.value );
    }

    if (m_xDelegate.is())
    {
        Reference< lang::XComponent > xComp( m_xDelegate, UNO_QUERY );
        OSL_ENSURE( xComp.is(), "### component context should export lang::XComponent!" );
        if (xComp.is())
        {
            xComp->addEventListener( new Disposer_Impl( this ) );
        }
        if (m_xSMgr.is())
        {
            m_bDisposeSMgr = true;
        }
        else
        {
            m_bDisposeSMgr = false;
            m_xSMgr = m_xDelegate->getServiceManager();
        }
    }
}
//__________________________________________________________________________________________________
ComponentContext::ComponentContext(
    ContextEntry_Init const * pEntries, sal_Int32 nEntries,
    Reference< registry::XSimpleRegistry > const & xRegistry )
    SAL_THROW( () )
    : WeakComponentImplHelper1< XComponentContext >( m_mutex )
{
    // inited values
    while (nEntries--)
    {
        ContextEntry_Init const & rEntry = pEntries[ nEntries ];

        if (rEntry.name.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM("com.sun.star.lang.ServiceManager") ))
        {
            if (rEntry.value >>= m_xSMgr)
                continue;
        }
        m_map[ rEntry.name ] = new ContextEntry( rEntry.bLateInitService, rEntry.value );
    }

    // late init singleton services
    if (xRegistry.is())
    {
        Reference< registry::XRegistryKey > xKey( xRegistry->getRootKey() );
        if (xKey.is())
        {
            xKey = xKey->openKey( OUString( RTL_CONSTASCII_USTRINGPARAM("/SINGLETONS") ) );
            if (xKey.is())
            {
                Sequence< Reference< registry::XRegistryKey > > keys( xKey->openKeys() );
                Reference< registry::XRegistryKey > const * pKeys = keys.getConstArray();
                for ( sal_Int32 nPos = keys.getLength(); nPos--; )
                {
                    try
                    {
                        Reference< registry::XRegistryKey > const & xKey = pKeys[ nPos ];
                        m_map[ xKey->getKeyName().copy( sizeof("/SINGLETONS") /* -\0 +'/' */ ) ] =
                            new ContextEntry( true, makeAny( xKey->getStringValue() ) );
                    }
                    catch (Exception & rExc)
                    {
#ifdef _DEBUG
                        OString aStr( OUStringToOString( xKey->getKeyName().copy( 11 ), RTL_TEXTENCODING_ASCII_US ) );
                        OString aStr2( OUStringToOString( rExc.Message, RTL_TEXTENCODING_ASCII_US ) );
                        ::fprintf( stderr, "### failed reading singleton [%s] service name from registry: %s\n", aStr.getStr(), aStr2.getStr() );
#endif
                    }
                }
            }
        }
    }
}

//==================================================================================================
Reference< XComponentContext > SAL_CALL createInitialComponentContext(
    ContextEntry_Init const * pEntries, sal_Int32 nEntries,
    Reference< registry::XSimpleRegistry > const & xRegistry )
    SAL_THROW( () )
{
    return new ComponentContext( pEntries, nEntries, xRegistry );
}

//##################################################################################################
Reference< XComponentContext > SAL_CALL createComponentContext(
    ContextEntry_Init const * pEntries, sal_Int32 nEntries,
    Reference< XComponentContext > const & xDelegate )
    SAL_THROW( () )
{
    if (nEntries > 0)
    {
        return new ComponentContext( pEntries, nEntries, xDelegate );
    }
    else
    {
        return xDelegate;
    }
}

}
<commit_msg>#87233# fixed disposing sequence: context entries, smgr, tdmgr<commit_after>/*************************************************************************
 *
 *  $RCSfile: component_context.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: dbo $ $Date: 2001-06-07 11:55:14 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifdef _DEBUG
#include <stdio.h>
#endif

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

#ifndef _CPPUHELPER_IMPLBASE1_HXX
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _CPPUHELPER_COMPBASE1_HXX
#include <cppuhelper/compbase1.hxx>
#endif
#ifndef _CPPUHELPER_COMPONENT_CONTEXT_HXX
#include <cppuhelper/component_context.hxx>
#endif

#include <com/sun/star/lang/XMultiComponentFactory.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/registry/XSimpleRegistry.hpp>

#include <hash_map>

#define SMGR_NAME "com.sun.star.lang.ServiceManager"
#define TDMGR_NAME "com.sun.star.reflection.TypeDescriptionManager"

using namespace ::osl;
using namespace ::rtl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star;

namespace cppu
{

//==================================================================================================
class Disposer_Impl
    : public WeakImplHelper1< lang::XEventListener >
{
    Reference< lang::XComponent > m_xTarget;

public:
    inline Disposer_Impl( Reference< lang::XComponent > const & xTarget )
        SAL_THROW( () )
        : m_xTarget( xTarget )
        { OSL_ASSERT( m_xTarget.is() ); }

    virtual void SAL_CALL disposing( lang::EventObject const & rSource )
        throw (RuntimeException);
};
//__________________________________________________________________________________________________
void Disposer_Impl::disposing( lang::EventObject const & rSource )
    throw (RuntimeException)
{
    m_xTarget->dispose();
    m_xTarget.clear();
}

//==================================================================================================
struct MutexHolder
{
    Mutex m_mutex;
};
//==================================================================================================
class ComponentContext
    : public MutexHolder
    , public WeakComponentImplHelper1< XComponentContext >
{
    Reference< XComponentContext > m_xDelegate;

    struct ContextEntry
    {
        bool bLateInitService;
        Any value;

        inline ContextEntry( bool bLateInitService_, Any const & value_ )
            : bLateInitService( bLateInitService_ )
            , value( value_ )
            {}
    };
    typedef ::std::hash_map< OUString, ContextEntry *, OUStringHash > t_map;
    t_map m_map;

    Reference< lang::XMultiComponentFactory > m_xSMgr;
    // denotes if service manager has to be disposed by this context,
    // else it was retieved from a delegate which itself has to dispose it
    bool m_bDisposeSMgr;

protected:
    virtual void SAL_CALL disposing();

public:
    ComponentContext(
        ContextEntry_Init const * pEntries, sal_Int32 nEntries,
        Reference< XComponentContext > const & xDelegate )
        SAL_THROW( () );
    ComponentContext(
        ContextEntry_Init const * pEntries, sal_Int32 nEntries,
        Reference< registry::XSimpleRegistry > const & xRegistry )
        SAL_THROW( () );
    virtual ~ComponentContext();

    // XComponentContext
    virtual Any SAL_CALL getValueByName( OUString const & rName )
        throw (RuntimeException);
    virtual Reference< lang::XMultiComponentFactory > SAL_CALL getServiceManager()
        throw (RuntimeException);
};
//__________________________________________________________________________________________________
Any ComponentContext::getValueByName( OUString const & rName )
    throw (RuntimeException)
{
    /** map is anytime untouched, if an uninit value will be inited, synch is done on mutex.
     */

    t_map::const_iterator const iFind( m_map.find( rName ) );
    if (iFind != m_map.end())
    {
        ContextEntry * pEntry = iFind->second;

        if (pEntry->bLateInitService)
        {
            try
            {
                Reference< XInterface > xInstance;

                Reference< lang::XSingleComponentFactory > xFac;
                if (pEntry->value >>= xFac) // try via factory
                {
                    xInstance = xFac->createInstanceWithContext( this );
                }
                else // optionally service name
                {
                    OUString aServiceName;
                    if ((pEntry->value >>= aServiceName) && aServiceName.getLength())
                    {
                        if (m_xSMgr.is())
                        {
                            xInstance = m_xSMgr->createInstanceWithContext( aServiceName, this );
                        }
#ifdef _DEBUG
                        else
                        {
                            ::fprintf( stderr, "### no service manager given for instanciating singletons!\n" );
                        }
#endif
                    }
                }

                if (xInstance.is())
                {
                    ClearableMutexGuard aGuard( m_mutex );
                    if (pEntry->bLateInitService)
                    {
                        pEntry->value.setValue( &xInstance, ::getCppuType( &xInstance ) );
                        pEntry->bLateInitService = false;
                    }
                    else // inited in the meantime
                    {
                        aGuard.clear();
                        // service has entered the context in the meantime
                        // => try to dispose this object
                        Reference< lang::XComponent > xComp( xInstance, UNO_QUERY );
                        if (xComp.is())
                        {
                            xComp->dispose();
                        }
                    }

                    return pEntry->value;
                }
                else
                {
                    OString aStr( OUStringToOString( rName, RTL_TEXTENCODING_ASCII_US ) );
                    OSL_TRACE( "### cannot raise singleton: $s\n", aStr.getStr() );
                }
            }
            catch (Exception & rExc)
            {
#ifdef _DEBUG
                OString aStr( OUStringToOString( rName, RTL_TEXTENCODING_ASCII_US ) );
                OString aStr2( OUStringToOString( rExc.Message, RTL_TEXTENCODING_ASCII_US ) );
                ::fprintf( stderr, "### exception occured raising singleton %s: %s\n", aStr.getStr(), aStr2.getStr() );
#endif
            }
        }
        else
        {
            return pEntry->value;
        }

        return Any(); // error occured
    }
    else if (m_xDelegate.is())
    {
        return m_xDelegate->getValueByName( rName );
    }

    return Any();
}
//__________________________________________________________________________________________________
Reference< lang::XMultiComponentFactory > ComponentContext::getServiceManager()
    throw (RuntimeException)
{
    return m_xSMgr;
}
//__________________________________________________________________________________________________
ComponentContext::~ComponentContext()
{
#ifdef DEBUG
    ::fprintf( stderr, "> destructed context %p\n", this );
#endif
}
//__________________________________________________________________________________________________
void ComponentContext::disposing()
{
#ifdef DEBUG
    ::fprintf( stderr, "> disposing context %p\n", this );
#endif

    Reference< lang::XComponent > xTDMgr; // to be disposed separately

    // first dispose all context objects
    t_map::const_iterator iPos( m_map.begin() );
    for ( ; iPos != m_map.end(); ++iPos )
    {
        ContextEntry * pEntry = iPos->second;

        // service manager disposed separately
        if (!m_xSMgr.is() || !iPos->first.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM(SMGR_NAME) ))
        {
            Reference< lang::XComponent > xComp;

            if (pEntry->bLateInitService)
            {
                // may be in late init
                MutexGuard aGuard( m_mutex );
                pEntry->value >>= xComp;
            }
            else
            {
                pEntry->value >>= xComp;
            }

            if (xComp.is())
            {
                if (iPos->first.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM(TDMGR_NAME) ))
                {
                    // disposed separately
                    xTDMgr = xComp;
                }
                else
                {
                    xComp->dispose();
                }
            }
        }
    }

    // second dispose service manager
    if (m_bDisposeSMgr)
    {
        Reference< lang::XComponent > xComp( m_xSMgr, UNO_QUERY );
        if (xComp.is())
        {
            xComp->dispose();
        }
    }

    // last dispose of tdmgr: revoke callback from cppu runtime
    if (xTDMgr.is())
    {
        xTDMgr->dispose();
    }

    // everything is disposed, hopefully nobody accesses the context anymore...
    for ( iPos = m_map.begin(); iPos != m_map.end(); ++iPos )
    {
        delete iPos->second;
    }

    m_map.clear();
}
//__________________________________________________________________________________________________
ComponentContext::ComponentContext(
    ContextEntry_Init const * pEntries, sal_Int32 nEntries,
    Reference< XComponentContext > const & xDelegate )
    SAL_THROW( () )
    : WeakComponentImplHelper1< XComponentContext >( m_mutex )
    , m_xDelegate( xDelegate )
{
    while (nEntries--)
    {
        ContextEntry_Init const & rEntry = pEntries[ nEntries ];

        if (rEntry.name.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM(SMGR_NAME) ))
        {
            rEntry.value >>= m_xSMgr;
        }
        m_map[ rEntry.name ] = new ContextEntry( rEntry.bLateInitService, rEntry.value );
    }

    if (m_xDelegate.is())
    {
        Reference< lang::XComponent > xComp( m_xDelegate, UNO_QUERY );
        OSL_ENSURE( xComp.is(), "### component context should export lang::XComponent!" );
        if (xComp.is())
        {
            xComp->addEventListener( new Disposer_Impl( this ) );
        }
        if (m_xSMgr.is())
        {
            m_bDisposeSMgr = true;
        }
        else
        {
            m_bDisposeSMgr = false;
            m_xSMgr = m_xDelegate->getServiceManager();
        }
    }
}
//__________________________________________________________________________________________________
ComponentContext::ComponentContext(
    ContextEntry_Init const * pEntries, sal_Int32 nEntries,
    Reference< registry::XSimpleRegistry > const & xRegistry )
    SAL_THROW( () )
    : WeakComponentImplHelper1< XComponentContext >( m_mutex )
{
    // inited values
    while (nEntries--)
    {
        ContextEntry_Init const & rEntry = pEntries[ nEntries ];

        if (rEntry.name.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM("com.sun.star.lang.ServiceManager") ))
        {
            if (rEntry.value >>= m_xSMgr)
                continue;
        }
        m_map[ rEntry.name ] = new ContextEntry( rEntry.bLateInitService, rEntry.value );
    }

    // late init singleton services
    if (xRegistry.is())
    {
        Reference< registry::XRegistryKey > xKey( xRegistry->getRootKey() );
        if (xKey.is())
        {
            xKey = xKey->openKey( OUString( RTL_CONSTASCII_USTRINGPARAM("/SINGLETONS") ) );
            if (xKey.is())
            {
                Sequence< Reference< registry::XRegistryKey > > keys( xKey->openKeys() );
                Reference< registry::XRegistryKey > const * pKeys = keys.getConstArray();
                for ( sal_Int32 nPos = keys.getLength(); nPos--; )
                {
                    try
                    {
                        Reference< registry::XRegistryKey > const & xKey = pKeys[ nPos ];
                        m_map[ xKey->getKeyName().copy( sizeof("/SINGLETONS") /* -\0 +'/' */ ) ] =
                            new ContextEntry( true, makeAny( xKey->getStringValue() ) );
                    }
                    catch (Exception & rExc)
                    {
#ifdef _DEBUG
                        OString aStr( OUStringToOString( xKey->getKeyName().copy( 11 ), RTL_TEXTENCODING_ASCII_US ) );
                        OString aStr2( OUStringToOString( rExc.Message, RTL_TEXTENCODING_ASCII_US ) );
                        ::fprintf( stderr, "### failed reading singleton [%s] service name from registry: %s\n", aStr.getStr(), aStr2.getStr() );
#endif
                    }
                }
            }
        }
    }
}

//==================================================================================================
Reference< XComponentContext > SAL_CALL createInitialComponentContext(
    ContextEntry_Init const * pEntries, sal_Int32 nEntries,
    Reference< registry::XSimpleRegistry > const & xRegistry )
    SAL_THROW( () )
{
    return new ComponentContext( pEntries, nEntries, xRegistry );
}

//##################################################################################################
Reference< XComponentContext > SAL_CALL createComponentContext(
    ContextEntry_Init const * pEntries, sal_Int32 nEntries,
    Reference< XComponentContext > const & xDelegate )
    SAL_THROW( () )
{
    if (nEntries > 0)
    {
        return new ComponentContext( pEntries, nEntries, xDelegate );
    }
    else
    {
        return xDelegate;
    }
}

}
<|endoftext|>


<commit_before>
// Copyright (c) 2013-2015 niXman (i dotty nixman doggy gmail dotty com)
// All rights reserved.
//
// This file is part of YAL(https://github.com/niXman/yal) project.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   Redistributions of source code must retain the above copyright notice, this
//   list of conditions and the following disclaimer.
//
//   Redistributions in binary form must reproduce the above copyright notice, this
//   list of conditions and the following disclaimer in the documentation and/or
//   other materials provided with the distribution.
//
//   Neither the name of the {organization} nor the names of its
//   contributors may be used to endorse or promote products derived from
//   this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include <iostream>
#include <thread>

#include <yal/yal.hpp>

/***************************************************************************/

int main() {
	static const char *s1name = "test1/test1/test1.log";
	static const char *s2name = "test2.log";
	static const char *s3name = "test3/test3";
	static const char *s4name = "test4";
	static const char *s5name = "test5";

	try {
		YAL_SESSION_CREATE(test1, s1name, 1024*1024, yal::sec_res |yal::flush_each_record);
		YAL_SESSION_CREATE(test2, s2name, 1024*1024, yal::usec_res|yal::compress);
		YAL_SESSION_CREATE(test3, s3name, 1024*1024, yal::nsec_res|yal::unbuffered);
		YAL_SESSION_CREATE(test4, s4name, 1024*1024, yal::nsec_res|yal::compress);
//		YAL_SESSION_TO_TERM(test1, true, "term1");

		for ( auto idx = 0ul, idx2 = 0ul; idx < 1024ul*10ul; idx+=2, idx2+=3 ) {
			YAL_LOG_INFO	(test1, "%1% -> %2% -> %1%", idx, idx+1);
			YAL_LOG_DEBUG	(test1, "%1% -> %2% -> %1%", idx, idx+1);
			YAL_LOG_WARNING(test1, "%1% -> %2% -> %1%", idx, idx+1);
			YAL_LOG_ERROR	(test1, "%1% -> %2% -> %1%", idx, idx+1);

			YAL_LOG_INFO	(test2, "%016d -> %016d", idx, idx);
			YAL_LOG_DEBUG	(test2, "%016d -> %016d", idx, idx);
			YAL_LOG_WARNING(test2, "%016d -> %016d", idx, idx);
			YAL_LOG_ERROR	(test2, "%016d -> %016d", idx, idx);

			YAL_LOG_INFO	(test3, "%016d -> %016d", idx, idx);
			YAL_LOG_DEBUG	(test3, "%016d -> %016d", idx, idx);
			YAL_LOG_WARNING(test3, "%016d -> %016d", idx, idx);
			YAL_LOG_ERROR	(test3, "%016d -> %016d", idx, idx);

			YAL_LOG_INFO	(test4, "%016d -> %016d", idx, idx);
			YAL_LOG_DEBUG	(test4, "%016d -> %016d", idx, idx);
			YAL_LOG_WARNING(test4, "%016d -> %016d", idx, idx);
			YAL_LOG_ERROR	(test4, "%016d -> %016d", idx, idx);

			YAL_GLOBAL_LOG_INFO		("%016d -> %016d", idx2, idx2);
			YAL_GLOBAL_LOG_DEBUG		("%016d -> %016d", idx2, idx2);
			YAL_GLOBAL_LOG_WARNING	("%016d -> %016d", idx2, idx2);
			YAL_GLOBAL_LOG_ERROR		("%016d -> %016d", idx2, idx2);
		}
		YAL_FLUSH();

		YAL_SESSION_GET2(ts1, s1name);
		YAL_ASSERT_TERM(std::cerr, ts1);
		YAL_SESSION_GET2(ts2, s2name);
		YAL_ASSERT_TERM(std::cerr, ts2);
		YAL_SESSION_GET2(ts3, s3name);
		YAL_ASSERT_TERM(std::cerr, ts3);
		YAL_SESSION_GET2(ts4, s4name);
		YAL_ASSERT_TERM(std::cerr, ts4);
		YAL_SESSION_GET2(ts5, s5name);
		YAL_ASSERT_TERM(std::cerr, !ts5);

		YAL_ASSERT_TERM(std::cerr,  YAL_SESSION_EXISTS(s1name));
		YAL_ASSERT_TERM(std::cerr,  YAL_SESSION_EXISTS(s2name));
		YAL_ASSERT_TERM(std::cerr,  YAL_SESSION_EXISTS(s3name));
		YAL_ASSERT_TERM(std::cerr,  YAL_SESSION_EXISTS(s4name));
		YAL_ASSERT_TERM(std::cerr, !YAL_SESSION_EXISTS(s5name));

		YAL_SESSION_CREATE(test5, s5name, 1024*10, yal::flush_each_record);
		YAL_SESSION_TO_TERM(test5, true, "test5 term");
		YAL_TEST_LESS		(test5, 0, 1);
		YAL_TEST_LESS		(test5, 1, 1); // test fail
		YAL_TEST_LESSEQ	(test5, 1, 1);
		YAL_TEST_LESSEQ	(test5, 2, 1); // test fail
		YAL_TEST_EQ			(test5, 1, 1);
		YAL_TEST_EQ			(test5, 2, 1); // test fail
		YAL_TEST_NEQ		(test5, 0, 1);
		YAL_TEST_NEQ		(test5, 1, 1); // test fail
		YAL_TEST_GR			(test5, 1, 0);
		YAL_TEST_GR			(test5, 1, 1); // test fail
		YAL_TEST_GREQ		(test5, 1, 0);
		YAL_TEST_GREQ		(test5, 1, 2); // test fail
		YAL_TEST_ZERO		(test5, 0);
		YAL_TEST_ZERO		(test5, 1); // test fail
		YAL_TEST_NOTZERO	(test5, 1);
		YAL_TEST_NOTZERO	(test5, 0); // test fail
		YAL_TEST_NULL		(test5, nullptr);
		YAL_TEST_NULL		(test5, "cstring"); // test fail
		YAL_TEST_NOTNULL	(test5, "cstring");
		YAL_TEST_NOTNULL	(test5, nullptr); // test fail

#if 0
		YAL_ASSERT_LOG(test5, true);
		YAL_ASSERT_LOG(test5, false); // test fail
		YAL_ASSERT_LOG(test5, true);
		YAL_ASSERT_LOG(test5, false); // test fail

		YAL_ASSERT_TERM(std::cerr, true);
		YAL_ASSERT_TERM(std::cerr, false); // test fail
		YAL_ASSERT_TERM(std::cerr, true);
		YAL_ASSERT_TERM(std::cerr, false); // test fail
#endif

		YAL_MAKE_TIMEPOINT(tp1, "tp1 description");
		std::this_thread::sleep_for(std::chrono::nanoseconds(3333333333));
		YAL_PRINT_TIMEPOINT(test5, tp1);

		YAL_TRY(scope_flag0) {
			throw std::runtime_error("std::exception message");
		} YAL_CATCH(test5, scope_flag0, "catch0 message");

		YAL_TRY(scope_flag1) {
			throw 1;
		} YAL_CATCH(test5, scope_flag1, "catch1 message");

	} catch(const std::exception &ex) {
		std::cout << "[std::exception]: " << ex.what() << std::endl;
		return EXIT_FAILURE;
	} catch(...) {
		std::cout << "[unexpected exception]" << std::endl;
		return EXIT_FAILURE;
	}

	std::cout << "EXIT_SUCCESS" << std::endl;
	return EXIT_SUCCESS;
}

/***************************************************************************/
<commit_msg>fix for previous commit<commit_after>
// Copyright (c) 2013-2015 niXman (i dotty nixman doggy gmail dotty com)
// All rights reserved.
//
// This file is part of YAL(https://github.com/niXman/yal) project.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   Redistributions of source code must retain the above copyright notice, this
//   list of conditions and the following disclaimer.
//
//   Redistributions in binary form must reproduce the above copyright notice, this
//   list of conditions and the following disclaimer in the documentation and/or
//   other materials provided with the distribution.
//
//   Neither the name of the {organization} nor the names of its
//   contributors may be used to endorse or promote products derived from
//   this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include <iostream>
#include <thread>

#include <yal/yal.hpp>

/***************************************************************************/

int main() {
	static const char *s1name = "test1/test1/test1.log";
	static const char *s2name = "test2.log";
	static const char *s3name = "test3/test3";
	static const char *s4name = "test4";
	static const char *s5name = "test5";

	try {
		YAL_SESSION_CREATE(test1, s1name, 1024*1024, yal::sec_res |yal::flush_each_record);
		YAL_SESSION_CREATE(test2, s2name, 1024*1024, yal::usec_res|yal::compress);
		YAL_SESSION_CREATE(test3, s3name, 1024*1024, yal::nsec_res|yal::unbuffered);
		YAL_SESSION_CREATE(test4, s4name, 1024*1024, yal::nsec_res|yal::compress);
//		YAL_SESSION_TO_TERM(test1, true, "term1");

		for ( auto idx = 0ul, idx2 = 0ul; idx < 1024ul*10ul; idx+=2, idx2+=3 ) {
			YAL_LOG_INFO	(test1, "%1% -> %2% -> %1%", idx, idx+1);
			YAL_LOG_DEBUG	(test1, "%1% -> %2% -> %1%", idx, idx+1);
			YAL_LOG_WARNING(test1, "%1% -> %2% -> %1%", idx, idx+1);
			YAL_LOG_ERROR	(test1, "%1% -> %2% -> %1%", idx, idx+1);

			YAL_LOG_INFO	(test2, "%016d -> %016d", idx, idx);
			YAL_LOG_DEBUG	(test2, "%016d -> %016d", idx, idx);
			YAL_LOG_WARNING(test2, "%016d -> %016d", idx, idx);
			YAL_LOG_ERROR	(test2, "%016d -> %016d", idx, idx);

			YAL_LOG_INFO	(test3, "%016d -> %016d", idx, idx);
			YAL_LOG_DEBUG	(test3, "%016d -> %016d", idx, idx);
			YAL_LOG_WARNING(test3, "%016d -> %016d", idx, idx);
			YAL_LOG_ERROR	(test3, "%016d -> %016d", idx, idx);

			YAL_LOG_INFO	(test4, "%016d -> %016d", idx, idx);
			YAL_LOG_DEBUG	(test4, "%016d -> %016d", idx, idx);
			YAL_LOG_WARNING(test4, "%016d -> %016d", idx, idx);
			YAL_LOG_ERROR	(test4, "%016d -> %016d", idx, idx);

			YAL_GLOBAL_LOG_INFO		("%016d -> %016d", idx2, idx2);
			YAL_GLOBAL_LOG_DEBUG		("%016d -> %016d", idx2, idx2);
			YAL_GLOBAL_LOG_WARNING	("%016d -> %016d", idx2, idx2);
			YAL_GLOBAL_LOG_ERROR		("%016d -> %016d", idx2, idx2);
		}
		YAL_FLUSH();

		YAL_SESSION_GET2(ts1, s1name);
		YAL_ASSERT_TERM(std::cerr, ts1);
		YAL_SESSION_GET2(ts2, s2name);
		YAL_ASSERT_TERM(std::cerr, ts2);
		YAL_SESSION_GET2(ts3, s3name);
		YAL_ASSERT_TERM(std::cerr, ts3);
		YAL_SESSION_GET2(ts4, s4name);
		YAL_ASSERT_TERM(std::cerr, ts4);
		YAL_SESSION_GET2(ts5, s5name);
		YAL_ASSERT_TERM(std::cerr, !ts5);

		YAL_ASSERT_TERM(std::cerr,  YAL_SESSION_EXISTS(s1name));
		YAL_ASSERT_TERM(std::cerr,  YAL_SESSION_EXISTS(s2name));
		YAL_ASSERT_TERM(std::cerr,  YAL_SESSION_EXISTS(s3name));
		YAL_ASSERT_TERM(std::cerr,  YAL_SESSION_EXISTS(s4name));
		YAL_ASSERT_TERM(std::cerr, !YAL_SESSION_EXISTS(s5name));

		YAL_SESSION_CREATE(test5, s5name, 1024*10, yal::usec_res|yal::flush_each_record);
		YAL_SESSION_TO_TERM(test5, true, "test5 term");
		YAL_TEST_LESS		(test5, 0, 1);
		YAL_TEST_LESS		(test5, 1, 1); // test fail
		YAL_TEST_LESSEQ	(test5, 1, 1);
		YAL_TEST_LESSEQ	(test5, 2, 1); // test fail
		YAL_TEST_EQ			(test5, 1, 1);
		YAL_TEST_EQ			(test5, 2, 1); // test fail
		YAL_TEST_NEQ		(test5, 0, 1);
		YAL_TEST_NEQ		(test5, 1, 1); // test fail
		YAL_TEST_GR			(test5, 1, 0);
		YAL_TEST_GR			(test5, 1, 1); // test fail
		YAL_TEST_GREQ		(test5, 1, 0);
		YAL_TEST_GREQ		(test5, 1, 2); // test fail
		YAL_TEST_ZERO		(test5, 0);
		YAL_TEST_ZERO		(test5, 1); // test fail
		YAL_TEST_NOTZERO	(test5, 1);
		YAL_TEST_NOTZERO	(test5, 0); // test fail
		YAL_TEST_NULL		(test5, nullptr);
		YAL_TEST_NULL		(test5, "cstring"); // test fail
		YAL_TEST_NOTNULL	(test5, "cstring");
		YAL_TEST_NOTNULL	(test5, nullptr); // test fail

#if 0
		YAL_ASSERT_LOG(test5, true);
		YAL_ASSERT_LOG(test5, false); // test fail
		YAL_ASSERT_LOG(test5, true);
		YAL_ASSERT_LOG(test5, false); // test fail

		YAL_ASSERT_TERM(std::cerr, true);
		YAL_ASSERT_TERM(std::cerr, false); // test fail
		YAL_ASSERT_TERM(std::cerr, true);
		YAL_ASSERT_TERM(std::cerr, false); // test fail
#endif

		YAL_MAKE_TIMEPOINT(tp1, "tp1 description");
		std::this_thread::sleep_for(std::chrono::nanoseconds(3333333333));
		YAL_PRINT_TIMEPOINT(test5, tp1);

		YAL_TRY(scope_flag0) {
			throw std::runtime_error("std::exception message");
		} YAL_CATCH(test5, scope_flag0, "catch0 message");

		YAL_TRY(scope_flag1) {
			throw 1;
		} YAL_CATCH(test5, scope_flag1, "catch1 message");

	} catch(const std::exception &ex) {
		std::cout << "[std::exception]: " << ex.what() << std::endl;
		return EXIT_FAILURE;
	} catch(...) {
		std::cout << "[unexpected exception]" << std::endl;
		return EXIT_FAILURE;
	}

	std::cout << "EXIT_SUCCESS" << std::endl;
	return EXIT_SUCCESS;
}

/***************************************************************************/
<|endoftext|>


<commit_before>/*******************************************************************************
*    ALMA - Atacama Large Millimiter Array
*    (c) Associated Universities Inc., 2002
*    (c) European Southern Observatory, 2002
*    Copyright by ESO (in the framework of the ALMA collaboration)
*    and Cosylab 2002, All rights reserved
*
*    This library is free software; you can redistribute it and/or
*    modify it under the terms of the GNU Lesser General Public
*    License as published by the Free Software Foundation; either
*    version 2.1 of the License, or (at your option) any later version.
*
*    This library is distributed in the hope that it will be useful,
*    but WITHOUT ANY WARRANTY; without even the implied warranty of
*    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
*    Lesser General Public License for more details.
*
*    You should have received a copy of the GNU Lesser General Public
*    License along with this library; if not, write to the Free Software
*    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
*
* "@(#) $Id: acsncORBHelperImpl.cpp,v 1.57 2006/09/01 02:20:54 cparedes Exp $"
*
* who       when      what
* --------  --------  ----------------------------------------------
* david  20/09/02  created
*/
//-----------------------------------------------------------------------------
#include "acsncORBHelper.h"
#include <acsutilPorts.h>
#include "acsncC.h"
#include <acscommonC.h>
//-----------------------------------------------------------------------------
 using namespace baci;
//-----------------------------------------------------------------------------
namespace nc {
//-----------------------------------------------------------------------------
ORBHelper::ORBHelper() :
    orb_mp(0),
    threadManager_mp(0)
{
    ACS_TRACE("ORBHelper::ORBHelper");
    threadManager_mp = new BACIThreadManager();
    init_ORB();
}
//-----------------------------------------------------------------------------
ORBHelper::ORBHelper(int argc, char *argv[]) :
    orb_mp(0),
    threadManager_mp(0)
{
    ACS_TRACE("ORBHelper::ORBHelper");
    threadManager_mp = new BACIThreadManager();
    init_ORB(argc, argv);
}
//-----------------------------------------------------------------------------
ORBHelper::~ORBHelper()
{
    ACS_TRACE("ORBHelper::~ORBHelper");

    try
	{
	if (orb_mp != 0)
	    {
	    orb_mp->shutdown(true);
	    orb_mp->destroy();
	    orb_mp=0;
	    }

	if (threadManager_mp != 0)
	    {
	    threadManager_mp->terminateAll();
	    delete threadManager_mp;
	    threadManager_mp=0;
	    }
	}
    catch(...)
	{
	ACS_SHORT_LOG((LM_ERROR, "ORBHelper::~ORBHelper destructor failed!"));
	}
}
//-----------------------------------------------------------------------------
void
ORBHelper::init_ORB()
    throw (CORBAProblemEx)
{
    ACS_TRACE("ORBHelper::init_ORB");

    //get IP
    ACE_CString nameService;

    //get NameService Reference
    nameService += acscommon::NAMING_SERVICE_NAME;
    nameService +="=corbaloc::";
    nameService += MACIHelper::getManagerHostname(1, NULL, NULL, NULL);
    nameService += ":";
    nameService += ACSPorts::getNamingServicePort().c_str();
    nameService += "/";
    nameService += acscommon::NAMING_SERVICE_NAME;

    // initialize ORB
    int argc = 5;
    const char* orbArgs[] = { "",
			      "-ORBInitRef",
			      nameService.c_str(),
			      "-ORBDottedDecimalAddresses",
                              "1"};

    init_ORB(argc,const_cast<char**>(orbArgs));
}
//-----------------------------------------------------------------------------
void
ORBHelper::init_ORB(int argc, char *argv[])
    throw (CORBAProblemEx)
{
    ACS_TRACE("ORBHelper::init_ORB");

    try
	{
	//initialize the ORB
	orb_mp = CORBA::ORB_init(argc, argv, "");
	//ensure it's a real reference
	if((orb_mp == 0)||(CORBA::is_nil(orb_mp) == true))
	    {
	    ACS_SHORT_LOG((LM_ERROR,"ORBHelper::init_ORB unable to create ORB!"));
	    CORBAProblemExImpl err = CORBAProblemExImpl(__FILE__,__LINE__,"nc::ORBHelper::init_ORB");
	    throw err.getCORBAProblemEx();
	    }

	//get the Root POA
	CORBA::Object_var poaObject = orb_mp->resolve_initial_references("RootPOA");
	//ensure it's a real reference
	if (CORBA::is_nil(poaObject.in()) == true)
	    {
	    ACS_SHORT_LOG((LM_ERROR,"ORBHelper::init_ORB unable to initialize RootPOA object!"));
	    CORBAProblemExImpl err = CORBAProblemExImpl(__FILE__,__LINE__,"nc::ORBHelper::init_ORB");
	    throw err.getCORBAProblemEx();
	    }
	//narrow the Root POA
	PortableServer::POA_var rootPOA = PortableServer::POA::_narrow(poaObject.in());
	if (rootPOA.in() == PortableServer::POA::_nil())
	    {
	    ACS_SHORT_LOG((LM_ERROR,"ORBHelper::init_ORB unable to narrow RootPOA object!"));
	    CORBAProblemExImpl err = CORBAProblemExImpl(__FILE__,__LINE__,"nc::ORBHelper::init_ORB");
	    throw err.getCORBAProblemEx();
	    }

	//get the POA manager
	PortableServer::POAManager_var poaManager = rootPOA->the_POAManager();
	//ensure it's a real reference
	if(poaManager.in()==PortableServer::POAManager::_nil())
	    {
	    ACS_SHORT_LOG((LM_ERROR,"ORBHelper::init_ORB unable to reference POAManager object!"));
	    CORBAProblemExImpl err = CORBAProblemExImpl(__FILE__,__LINE__,"nc::ORBHelper::init_ORB");
	    throw err.getCORBAProblemEx();
	    }

	//finally activate the POA manager to start processing incoming and
	//outgoing calls
	poaManager->activate();
	}
    catch(CORBAProblemExImpl)
	{
	ACS_SHORT_LOG((LM_TRACE,"ORBHelper::init_ORB encountered a nil pointer!"));
	//was thrown by ORBHelper code...OK to rethrow
	throw;
	}
    catch(...)
	{
	ACS_SHORT_LOG((LM_ERROR, "ORBHelper::init_ORB(...) unable to initialize the ORB!"));
	CORBAProblemExImpl err = CORBAProblemExImpl(__FILE__,__LINE__,"nc::ORBHelper::init_ORB");
	throw err.getCORBAProblemEx();
	}
}
//-----------------------------------------------------------------------------
void
ORBHelper::runOrb()
    throw(CouldntCreateThreadEx)
{
    ACS_TRACE("ORBHelper::runOrb");

    if(threadManager_mp == 0)
	{
	ACS_SHORT_LOG((LM_ERROR,"ORBHelper::runORB bad thread manager!"));
	CouldntCreateThreadExImpl err = CouldntCreateThreadExImpl(__FILE__,__LINE__,"nc::ORBHelper::runORB");
	throw err.getCouldntCreateThreadEx();
	}
    threadManager_mp->create("runOrbThread", (void *)ORBHelper::runOrbThread, static_cast<void *>(this));
    threadManager_mp->resume("runOrbThread");

    ACS_SHORT_LOG((LM_INFO,"ORBHelper::runORB the ORB is now running!"));
    return;
}
//-----------------------------------------------------------------------------
void*
ORBHelper::runOrbThread(void *this_p)
{
    ACS_TRACE("ORBHelper::runOrbThread");

    try
	{
	if (this_p == 0)
	    {
	    ACS_SHORT_LOG((LM_ERROR,"ORBHelper::runORBThread bad parameter passed!"));
	    return static_cast<void *>(0);
	    }

	BACIThreadParameter *baciParameter_p = static_cast<BACIThreadParameter *>(this_p);
	BACIThread *myself_p = baciParameter_p->getBACIThread();

	// Variables have to be passed explicitly
	ORBHelper *helper_p = static_cast<ORBHelper *>(const_cast<void *>(baciParameter_p->getParameter()));

	// Actually start the thread here
	if (BACIThread::InitThread != 0)
	    {
	    BACIThread::InitThread("runOrbThread");
	    }

	//this should cause only one execution of helper_p->orb_mp->run()
	bool execute=true;
	while((myself_p->check() == true) && (execute == true) )
	    {
	    if(myself_p->isSuspended() == false)
		{
		helper_p->orb_mp->run();
		ACS_SHORT_LOG((LM_INFO,"ORBHelper::runOrbThread the stand alone orb has stopped."));
		execute=false;
		}
	    //well this almost certainly will never be called but just be
	    //on the safe side of things
	    myself_p->sleep();
	    }

	if (BACIThread::DoneThread != 0)
	    {
	    BACIThread::DoneThread();
	    }

	delete baciParameter_p;
	myself_p->setStopped();
	}
    catch(...)
	{
	ACS_SHORT_LOG((LM_ERROR, "ORBHelper::runOrbThread failed!"));
	return static_cast<void *>(0);
	}
    return static_cast<void *>(0);
}
//-----------------------------------------------------------------------------
 };
/*___oOo___*/

<commit_msg>followed change in maci helper api<commit_after>/*******************************************************************************
*    ALMA - Atacama Large Millimiter Array
*    (c) Associated Universities Inc., 2002
*    (c) European Southern Observatory, 2002
*    Copyright by ESO (in the framework of the ALMA collaboration)
*    and Cosylab 2002, All rights reserved
*
*    This library is free software; you can redistribute it and/or
*    modify it under the terms of the GNU Lesser General Public
*    License as published by the Free Software Foundation; either
*    version 2.1 of the License, or (at your option) any later version.
*
*    This library is distributed in the hope that it will be useful,
*    but WITHOUT ANY WARRANTY; without even the implied warranty of
*    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
*    Lesser General Public License for more details.
*
*    You should have received a copy of the GNU Lesser General Public
*    License along with this library; if not, write to the Free Software
*    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
*
* "@(#) $Id: acsncORBHelperImpl.cpp,v 1.58 2007/09/09 08:01:42 hsommer Exp $"
*
* who       when      what
* --------  --------  ----------------------------------------------
* david  20/09/02  created
*/
//-----------------------------------------------------------------------------
#include "acsncORBHelper.h"
#include <acsutilPorts.h>
#include "acsncC.h"
#include <acscommonC.h>
//-----------------------------------------------------------------------------
 using namespace baci;
//-----------------------------------------------------------------------------
namespace nc {
//-----------------------------------------------------------------------------
ORBHelper::ORBHelper() :
    orb_mp(0),
    threadManager_mp(0)
{
    ACS_TRACE("ORBHelper::ORBHelper");
    threadManager_mp = new BACIThreadManager();
    init_ORB();
}
//-----------------------------------------------------------------------------
ORBHelper::ORBHelper(int argc, char *argv[]) :
    orb_mp(0),
    threadManager_mp(0)
{
    ACS_TRACE("ORBHelper::ORBHelper");
    threadManager_mp = new BACIThreadManager();
    init_ORB(argc, argv);
}
//-----------------------------------------------------------------------------
ORBHelper::~ORBHelper()
{
    ACS_TRACE("ORBHelper::~ORBHelper");

    try
	{
	if (orb_mp != 0)
	    {
	    orb_mp->shutdown(true);
	    orb_mp->destroy();
	    orb_mp=0;
	    }

	if (threadManager_mp != 0)
	    {
	    threadManager_mp->terminateAll();
	    delete threadManager_mp;
	    threadManager_mp=0;
	    }
	}
    catch(...)
	{
	ACS_SHORT_LOG((LM_ERROR, "ORBHelper::~ORBHelper destructor failed!"));
	}
}
//-----------------------------------------------------------------------------
void
ORBHelper::init_ORB()
    throw (CORBAProblemEx)
{
    ACS_TRACE("ORBHelper::init_ORB");

    //get IP
    ACE_CString nameService;

    //get NameService Reference
    nameService += acscommon::NAMING_SERVICE_NAME;
    nameService +="=corbaloc::";
    nameService += MACIHelper::getManagerHostname(1, NULL);
    nameService += ":";
    nameService += ACSPorts::getNamingServicePort().c_str();
    nameService += "/";
    nameService += acscommon::NAMING_SERVICE_NAME;

    // initialize ORB
    int argc = 5;
    const char* orbArgs[] = { "",
			      "-ORBInitRef",
			      nameService.c_str(),
			      "-ORBDottedDecimalAddresses",
                              "1"};

    init_ORB(argc,const_cast<char**>(orbArgs));
}
//-----------------------------------------------------------------------------
void
ORBHelper::init_ORB(int argc, char *argv[])
    throw (CORBAProblemEx)
{
    ACS_TRACE("ORBHelper::init_ORB");

    try
	{
	//initialize the ORB
	orb_mp = CORBA::ORB_init(argc, argv, "");
	//ensure it's a real reference
	if((orb_mp == 0)||(CORBA::is_nil(orb_mp) == true))
	    {
	    ACS_SHORT_LOG((LM_ERROR,"ORBHelper::init_ORB unable to create ORB!"));
	    CORBAProblemExImpl err = CORBAProblemExImpl(__FILE__,__LINE__,"nc::ORBHelper::init_ORB");
	    throw err.getCORBAProblemEx();
	    }

	//get the Root POA
	CORBA::Object_var poaObject = orb_mp->resolve_initial_references("RootPOA");
	//ensure it's a real reference
	if (CORBA::is_nil(poaObject.in()) == true)
	    {
	    ACS_SHORT_LOG((LM_ERROR,"ORBHelper::init_ORB unable to initialize RootPOA object!"));
	    CORBAProblemExImpl err = CORBAProblemExImpl(__FILE__,__LINE__,"nc::ORBHelper::init_ORB");
	    throw err.getCORBAProblemEx();
	    }
	//narrow the Root POA
	PortableServer::POA_var rootPOA = PortableServer::POA::_narrow(poaObject.in());
	if (rootPOA.in() == PortableServer::POA::_nil())
	    {
	    ACS_SHORT_LOG((LM_ERROR,"ORBHelper::init_ORB unable to narrow RootPOA object!"));
	    CORBAProblemExImpl err = CORBAProblemExImpl(__FILE__,__LINE__,"nc::ORBHelper::init_ORB");
	    throw err.getCORBAProblemEx();
	    }

	//get the POA manager
	PortableServer::POAManager_var poaManager = rootPOA->the_POAManager();
	//ensure it's a real reference
	if(poaManager.in()==PortableServer::POAManager::_nil())
	    {
	    ACS_SHORT_LOG((LM_ERROR,"ORBHelper::init_ORB unable to reference POAManager object!"));
	    CORBAProblemExImpl err = CORBAProblemExImpl(__FILE__,__LINE__,"nc::ORBHelper::init_ORB");
	    throw err.getCORBAProblemEx();
	    }

	//finally activate the POA manager to start processing incoming and
	//outgoing calls
	poaManager->activate();
	}
    catch(CORBAProblemExImpl)
	{
	ACS_SHORT_LOG((LM_TRACE,"ORBHelper::init_ORB encountered a nil pointer!"));
	//was thrown by ORBHelper code...OK to rethrow
	throw;
	}
    catch(...)
	{
	ACS_SHORT_LOG((LM_ERROR, "ORBHelper::init_ORB(...) unable to initialize the ORB!"));
	CORBAProblemExImpl err = CORBAProblemExImpl(__FILE__,__LINE__,"nc::ORBHelper::init_ORB");
	throw err.getCORBAProblemEx();
	}
}
//-----------------------------------------------------------------------------
void
ORBHelper::runOrb()
    throw(CouldntCreateThreadEx)
{
    ACS_TRACE("ORBHelper::runOrb");

    if(threadManager_mp == 0)
	{
	ACS_SHORT_LOG((LM_ERROR,"ORBHelper::runORB bad thread manager!"));
	CouldntCreateThreadExImpl err = CouldntCreateThreadExImpl(__FILE__,__LINE__,"nc::ORBHelper::runORB");
	throw err.getCouldntCreateThreadEx();
	}
    threadManager_mp->create("runOrbThread", (void *)ORBHelper::runOrbThread, static_cast<void *>(this));
    threadManager_mp->resume("runOrbThread");

    ACS_SHORT_LOG((LM_INFO,"ORBHelper::runORB the ORB is now running!"));
    return;
}
//-----------------------------------------------------------------------------
void*
ORBHelper::runOrbThread(void *this_p)
{
    ACS_TRACE("ORBHelper::runOrbThread");

    try
	{
	if (this_p == 0)
	    {
	    ACS_SHORT_LOG((LM_ERROR,"ORBHelper::runORBThread bad parameter passed!"));
	    return static_cast<void *>(0);
	    }

	BACIThreadParameter *baciParameter_p = static_cast<BACIThreadParameter *>(this_p);
	BACIThread *myself_p = baciParameter_p->getBACIThread();

	// Variables have to be passed explicitly
	ORBHelper *helper_p = static_cast<ORBHelper *>(const_cast<void *>(baciParameter_p->getParameter()));

	// Actually start the thread here
	if (BACIThread::InitThread != 0)
	    {
	    BACIThread::InitThread("runOrbThread");
	    }

	//this should cause only one execution of helper_p->orb_mp->run()
	bool execute=true;
	while((myself_p->check() == true) && (execute == true) )
	    {
	    if(myself_p->isSuspended() == false)
		{
		helper_p->orb_mp->run();
		ACS_SHORT_LOG((LM_INFO,"ORBHelper::runOrbThread the stand alone orb has stopped."));
		execute=false;
		}
	    //well this almost certainly will never be called but just be
	    //on the safe side of things
	    myself_p->sleep();
	    }

	if (BACIThread::DoneThread != 0)
	    {
	    BACIThread::DoneThread();
	    }

	delete baciParameter_p;
	myself_p->setStopped();
	}
    catch(...)
	{
	ACS_SHORT_LOG((LM_ERROR, "ORBHelper::runOrbThread failed!"));
	return static_cast<void *>(0);
	}
    return static_cast<void *>(0);
}
//-----------------------------------------------------------------------------
 };
/*___oOo___*/

<|endoftext|>


<commit_before>/*******************************************************************************
* ALMA - Atacama Large Millimiter Array
* (c) European Southern Observatory, 2011
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
*
* "@(#) $Id: bulkDataNTStream.cpp,v 1.19 2011/08/24 13:49:28 bjeram Exp $"
*
* who       when      what
* --------  --------  ----------------------------------------------
* bjeram  2011-04-19  created
*/
#include "bulkDataNTStream.h"
#include <iostream>
using namespace ACS_BD_Errors;
using namespace ACSErrTypeCommon;
using namespace ACS_DDS_Errors;

using namespace AcsBulkdata;

BulkDataNTStream::BulkDataNTStream(const char* name, const StreamConfiguration &cfg) :
	streamName_m(name), configuration_m(cfg), factory_m(0), participant_m(0)
{
	AUTO_TRACE(__PRETTY_FUNCTION__);

	try
	{
		createDDSFactory();
		createDDSParticipant(); //should be somewhere else in initialize or createStream
	}catch(const ACSErr::ACSbaseExImpl &e)
	{
		if (factory_m!=0)
			DDS::DomainParticipantFactory::finalize_instance();
		StreamCreateProblemExImpl ex (e, __FILE__, __LINE__, __PRETTY_FUNCTION__);
		ex.setStreamName(name);
		throw ex;
	}//try-catch
}//BulkDataNTStream

BulkDataNTStream::~BulkDataNTStream()
{
	AUTO_TRACE(__PRETTY_FUNCTION__);

	destroyDDSParticipant();
	DDS::DomainParticipantFactory::finalize_instance();
}//~BulkDataNTStream

void BulkDataNTStream::createDDSFactory()
{
	AUTO_TRACE(__PRETTY_FUNCTION__);
	DDS::ReturnCode_t ret;
	DDS::DomainParticipantFactoryQos factory_qos;

	factory_m = DDS::DomainParticipantFactory::get_instance();

	// needed by RTI only
	ret = factory_m->get_qos(factory_qos);
	if (ret!=DDS::RETCODE_OK)
	{
		DDSQoSSetProblemExImpl ex(__FILE__, __LINE__, __PRETTY_FUNCTION__);
		ex.setDDSTypeCode(ret);
		ex.setQoS("factory_m->get_qos");
		throw ex;
	}//if
	factory_qos.entity_factory.autoenable_created_entities = DDS_BOOLEAN_FALSE;
	if (configuration_m.urlProfileQoS.length()>0)
	{
		factory_qos.profile.url_profile.ensure_length(1,1);
		factory_qos.profile.url_profile[0] = DDS_String_dup(configuration_m.urlProfileQoS.c_str());
	}//if
	ret = factory_m->set_qos(factory_qos);
	if (ret!=DDS::RETCODE_OK)
	{
		DDSQoSSetProblemExImpl ex(__FILE__, __LINE__, __PRETTY_FUNCTION__);
		ex.setDDSTypeCode(ret);
		ex.setQoS("factory_m->set_qos");
		throw ex;
	}//if

	//RTI logging
	NDDSConfigLogger::get_instance()->set_verbosity_by_category(
			NDDS_CONFIG_LOG_CATEGORY_API,
			(NDDS_Config_LogVerbosity)(configuration_m.DDSLogVerbosity));
}//createDDSFactory

void BulkDataNTStream::createDDSParticipant()
{
	AUTO_TRACE(__PRETTY_FUNCTION__);
	DDS::ReturnCode_t ret;
	DDS::DomainParticipantQos participant_qos;
	int domainID=0; //TBD: where to get domain ID

	if (factory_m==NULL)
	{
		NullPointerExImpl ex(__FILE__, __LINE__, __PRETTY_FUNCTION__);
		ex.setVariable("factory_m");
		throw ex;
	}

	if (participant_m!=NULL)
	{
		printf("participant already created\n");
		return;
	}

	ret = factory_m->get_participant_qos_from_profile(participant_qos, configuration_m.libraryQos.c_str(), configuration_m.profileQos.c_str());
	if (ret!=DDS::RETCODE_OK)
	{
		DDSQoSSetProblemExImpl ex(__FILE__, __LINE__, __PRETTY_FUNCTION__);
		ex.setDDSTypeCode(ret);
		ex.setQoS("get_participant_qos_from_profile");
		throw ex;
	}//if

	participant_m =factory_m->create_participant(domainID, participant_qos, NULL, DDS::STATUS_MASK_NONE );
	if (participant_m==NULL)
	{
		DDSParticipantCreateProblemExImpl ex(__FILE__, __LINE__, __PRETTY_FUNCTION__);
		ex.setDomainID(domainID);
		throw ex;
	}

	ret = participant_m->enable();
}//createDDSParticipant

void BulkDataNTStream::destroyDDSParticipant()
{
	DDS::ReturnCode_t ret;
	AUTO_TRACE(__PRETTY_FUNCTION__);
	ret = factory_m->delete_participant(participant_m);
	if (ret != DDS_RETCODE_OK)
	{
		DDSParticipantDestroyProblemExImpl ex(__FILE__, __LINE__, __PRETTY_FUNCTION__);
		ex.log();
	}//if
}//destroyDDSParticipant
<commit_msg>setting also string_profile QoS<commit_after>/*******************************************************************************
* ALMA - Atacama Large Millimiter Array
* (c) European Southern Observatory, 2011
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
*
* "@(#) $Id: bulkDataNTStream.cpp,v 1.20 2011/09/14 09:35:25 bjeram Exp $"
*
* who       when      what
* --------  --------  ----------------------------------------------
* bjeram  2011-04-19  created
*/
#include "bulkDataNTStream.h"
#include <iostream>
using namespace ACS_BD_Errors;
using namespace ACSErrTypeCommon;
using namespace ACS_DDS_Errors;

using namespace AcsBulkdata;

BulkDataNTStream::BulkDataNTStream(const char* name, const StreamConfiguration &cfg) :
	streamName_m(name), configuration_m(cfg), factory_m(0), participant_m(0)
{
	AUTO_TRACE(__PRETTY_FUNCTION__);

	try
	{
		createDDSFactory();
		createDDSParticipant(); //should be somewhere else in initialize or createStream
	}catch(const ACSErr::ACSbaseExImpl &e)
	{
		if (factory_m!=0)
			DDS::DomainParticipantFactory::finalize_instance();
		StreamCreateProblemExImpl ex (e, __FILE__, __LINE__, __PRETTY_FUNCTION__);
		ex.setStreamName(name);
		throw ex;
	}//try-catch
}//BulkDataNTStream

BulkDataNTStream::~BulkDataNTStream()
{
	AUTO_TRACE(__PRETTY_FUNCTION__);

	destroyDDSParticipant();
	DDS::DomainParticipantFactory::finalize_instance();
}//~BulkDataNTStream

void BulkDataNTStream::createDDSFactory()
{
	AUTO_TRACE(__PRETTY_FUNCTION__);
	DDS::ReturnCode_t ret;
	DDS::DomainParticipantFactoryQos factory_qos;

	factory_m = DDS::DomainParticipantFactory::get_instance();

	// needed by RTI only
	ret = factory_m->get_qos(factory_qos);
	if (ret!=DDS::RETCODE_OK)
	{
		DDSQoSSetProblemExImpl ex(__FILE__, __LINE__, __PRETTY_FUNCTION__);
		ex.setDDSTypeCode(ret);
		ex.setQoS("factory_m->get_qos");
		throw ex;
	}//if
	factory_qos.entity_factory.autoenable_created_entities = DDS_BOOLEAN_FALSE;
	if (configuration_m.stringProfileQoS.length()>0)
	{
		factory_qos.profile.string_profile.ensure_length(1,1);
		factory_qos.profile.string_profile[0] = DDS_String_dup(configuration_m.stringProfileQoS.c_str());
	}//if

	if (configuration_m.urlProfileQoS.length()>0)
	{
		factory_qos.profile.url_profile.ensure_length(1,1);
		factory_qos.profile.url_profile[0] = DDS_String_dup(configuration_m.urlProfileQoS.c_str());
	}//if
	ret = factory_m->set_qos(factory_qos);
	if (ret!=DDS::RETCODE_OK)
	{
		DDSQoSSetProblemExImpl ex(__FILE__, __LINE__, __PRETTY_FUNCTION__);
		ex.setDDSTypeCode(ret);
		ex.setQoS("factory_m->set_qos");
		throw ex;
	}//if

	//RTI logging
	NDDSConfigLogger::get_instance()->set_verbosity_by_category(
			NDDS_CONFIG_LOG_CATEGORY_API,
			(NDDS_Config_LogVerbosity)(configuration_m.DDSLogVerbosity));
}//createDDSFactory

void BulkDataNTStream::createDDSParticipant()
{
	AUTO_TRACE(__PRETTY_FUNCTION__);
	DDS::ReturnCode_t ret;
	DDS::DomainParticipantQos participant_qos;
	int domainID=0; //TBD: where to get domain ID

	if (factory_m==NULL)
	{
		NullPointerExImpl ex(__FILE__, __LINE__, __PRETTY_FUNCTION__);
		ex.setVariable("factory_m");
		throw ex;
	}

	if (participant_m!=NULL)
	{
		printf("participant already created\n");
		return;
	}

	ret = factory_m->get_participant_qos_from_profile(participant_qos, configuration_m.libraryQos.c_str(), configuration_m.profileQos.c_str());
	if (ret!=DDS::RETCODE_OK)
	{
		DDSQoSSetProblemExImpl ex(__FILE__, __LINE__, __PRETTY_FUNCTION__);
		ex.setDDSTypeCode(ret);
		ex.setQoS("get_participant_qos_from_profile");
		throw ex;
	}//if

	participant_m =factory_m->create_participant(domainID, participant_qos, NULL, DDS::STATUS_MASK_NONE );
	if (participant_m==NULL)
	{
		DDSParticipantCreateProblemExImpl ex(__FILE__, __LINE__, __PRETTY_FUNCTION__);
		ex.setDomainID(domainID);
		throw ex;
	}

	ret = participant_m->enable();
}//createDDSParticipant

void BulkDataNTStream::destroyDDSParticipant()
{
	DDS::ReturnCode_t ret;
	AUTO_TRACE(__PRETTY_FUNCTION__);
	ret = factory_m->delete_participant(participant_m);
	if (ret != DDS_RETCODE_OK)
	{
		DDSParticipantDestroyProblemExImpl ex(__FILE__, __LINE__, __PRETTY_FUNCTION__);
		ex.log();
	}//if
}//destroyDDSParticipant
<|endoftext|>


<commit_before>#define SYS_CLOCK_GETTIME 263
#include "linux_clock.cpp"
<commit_msg>Fix a syscall number for 64-bit arm<commit_after>#ifdef BITS_64
#define SYS_CLOCK_GETTIME 113
#endif

#ifdef BITS_32
#define SYS_CLOCK_GETTIME 263
#endif

#include "linux_clock.cpp"
<|endoftext|>


<commit_before>#include "mitkDopplerToStrainRateFilter.h"
#include "mitkImageTimeSelector.h"
#include "mitkProperties.h"
#include "mitkPlaneGeometry.h"

#include <iostream>
#include <string>

void mitk::DopplerToStrainRateFilter::GenerateOutputInformation()
{
  mitk::Image::ConstPointer input = this->GetInput();
  mitk::Image::Pointer output = this->GetOutput();

  if ((output->IsInitialized()) && (this->GetMTime() <= m_TimeOfHeaderInitialization.GetMTime()))
    return;

  itkDebugMacro(<<"GenerateOutputInformation()");

  unsigned int i;
  unsigned int *tmpDimensions = new unsigned int[input->GetDimension()];

  for(i=0;i<input->GetDimension();++i)
    tmpDimensions[i]=input->GetDimension(i);

  //@todo maybe we should shift the following somehow in ImageToImageFilter
  output->Initialize(input->GetPixelType(),
    input->GetDimension(),
    tmpDimensions,
    input->GetNumberOfChannels());

  output->GetSlicedGeometry()->SetSpacing(input->GetSlicedGeometry()->GetSpacing());

  output->GetSlicedGeometry()->SetGeometry2D(mitk::Image::BuildStandardPlaneGeometry2D(output->GetSlicedGeometry(), tmpDimensions).GetPointer(), 0);
  output->GetSlicedGeometry()->SetEvenlySpaced();
  //set the timebounds - after SetGeometry2D, so that the already created PlaneGeometry will also receive this timebounds.
  output->GetSlicedGeometry()->SetTimeBoundsInMS(input->GetSlicedGeometry()->GetTimeBoundsInMS());

  output->SetPropertyList(input->GetPropertyList()->Clone());

  delete [] tmpDimensions;

  m_TimeOfHeaderInitialization.Modified();
}

void mitk::DopplerToStrainRateFilter::GenerateData()
{
  mitk::Image::ConstPointer input = this->GetInput();
  mitk::Image::Pointer output = this->GetOutput();

  mitk::Point3iProperty::Pointer pointProp;
  pointProp = dynamic_cast<mitk::Point3iProperty*>(input->GetProperty("ORIGIN").GetPointer());
  if (pointProp.IsNotNull() )
  {
    m_Origin = pointProp->GetValue();
  }

  std::cout << "compute Strain Rate Image .... " << std::endl;
  std::cout << "  origin.x=" << m_Origin.x << " origin.y=" << m_Origin.y << " origin.z=" << m_Origin.z << std::endl;
  std::cout << "  distance=" << m_Distance << std::endl;
  std::cout << "  NoStrainIntervall=" << m_NoStrainInterval << std::endl;

  const float *spacing = input->GetSlicedGeometry()->GetSpacing();
  //	std::cout << "   in: xres=" << spacing[0] << " yres=" << spacing[1] << " zres=" << spacing[2] << std::endl;

  mitk::ImageTimeSelector::Pointer timeSelector=mitk::ImageTimeSelector::New();
  timeSelector->SetInput(input);

  ipPicDescriptor* picStrainRate;
  picStrainRate = ipPicNew();
  picStrainRate->dim=3;
  picStrainRate->bpe  = output->GetPixelType().GetBpe();
  picStrainRate->type = output->GetPixelType().GetType();
  picStrainRate->n[0] = output->GetDimension(0);
  picStrainRate->n[1] = output->GetDimension(1);
  picStrainRate->n[2] = output->GetDimension(2);
  picStrainRate->data=malloc(_ipPicSize(picStrainRate));

  int xDim = picStrainRate->n[0];
  int yDim = picStrainRate->n[1];
  int zDim = picStrainRate->n[2];
  long slice_size = xDim*yDim;
  long vol_size = slice_size*zDim;

  ipPicDescriptor *picDoppler;

  int x,y,z,time;							// loop-counter
  int strainRate;						// the computed Strain Rate
  int v1,v2;								// velocity and Point p1 and p2

  float alpha;								// the beam-angle, angle betwen current point and beam-point
  float dx, dy;								// projection of this->distance to x- and y-axis
  float weightX, weightY;			// weigth-factors for x-velocity and y-velocity
  int dxFloor, dyFloor;				// floored dx, dy

  int x1, x2, x3, x4;					// a square, where the velocity v1 lies in
  int y1, y2, y3, y4;					// the points are used for interpolation
  int vTmp1, vTmp2;						// velocities used for interpolation
  int vTmp3, vTmp4;

  int minStrainRate=128, maxStrainRate=128;

  int n, nmax;
  int t, tmax;

  t = output->GetRequestedRegion().GetIndex(3);
  n = output->GetRequestedRegion().GetIndex(4);

  tmax = t + output->GetRequestedRegion().GetSize(3);
  nmax = n + output->GetRequestedRegion().GetSize(4);

  if (m_Distance<1) m_Distance=1;

  for(;n<nmax;++n)//output->GetNumberOfChannels();++n)
  {
    timeSelector->SetChannelNr(n);

    for(t=0;t<tmax;++t)
    {

      timeSelector->SetTimeNr(t);
      timeSelector->Update();

      _ipPicFreeTags(picStrainRate->info->tags_head);
      picStrainRate->info->tags_head = _ipPicCloneTags(timeSelector->GetOutput()->GetPic()->info->tags_head);

#define       WRITE_ANGLE_PIC
#ifdef WRITE_ANGLE_PIC
      ipPicDescriptor *anglePic;
      ipBool_t isAnglePicWritten = ipFalse;

      anglePic = ipPicNew();
      anglePic->type = ipPicInt;
      anglePic->bpe = 8;
      anglePic->dim = 2;
      anglePic->n[0] = xDim;
      anglePic->n[1] = yDim;
      anglePic->data = (ipInt1_t *)calloc(xDim*yDim,sizeof(ipInt1_t));
#endif

      picDoppler = timeSelector->GetOutput()->GetPic();

      for (z=0 ; z<zDim ; z++) {

        for (y=1; y<yDim; y++) {

          if (y<m_Origin.y) continue;  // cannot compute StrainRate above Transducer-Position

          for (x=0; x<xDim; x++) {

            if ((m_Origin.x - x)==0) {  // winkelhalbierende

              int yDistanceInUnits = (int)( m_Distance/spacing[1]);
              int yTmp = ( (y-yDistanceInUnits)<0 )  ? 0 : (y-yDistanceInUnits);
              v1 = ((ipUInt1_t *)picDoppler->data)[z*slice_size + yTmp*xDim + x] ;
              v2 = ((ipUInt1_t *)picDoppler->data)[z*slice_size + y*xDim + x] ;

            } else {

              // compute angle to transducer position
              // m_Origin is given in units, not in mm
              alpha = atan( (float) (m_Origin.x - x)  / (float) (m_Origin.y - y) );

              // m_Distance is given in mm
              dx = -sin(alpha) * m_Distance;
              dy = -cos(alpha) * m_Distance;

              // convert to units
              dx = dx/spacing[0];
              dy = dy/spacing[1];

              //#define WEIGTHED
#ifdef WEIGTHED
              weightX = dx - floor(dx);
              weightY = dy - floor(dy);

              dxFloor = (int) floor(dx);
              dyFloor = (int) floor(dy);

              x1 = x + dxFloor;					// lower left
              y1 = y + dyFloor;

              x2 = x + (dxFloor+1);			// lower right
              y2 = y + dyFloor;

              x3 = x + (dxFloor+1);			// upper right
              y3 = y + (dyFloor+1);

              x4 = x + dxFloor;					// upper left
              y4 = y + (dyFloor+1);

              vTmp1 = ((ipUInt1_t *)picDoppler->data)[z*slice_size + y1*xDim + x1];
              vTmp2 = ((ipUInt1_t *)picDoppler->data)[z*slice_size + y2*xDim + x2];
              vTmp3 = ((ipUInt1_t *)picDoppler->data)[z*slice_size + y3*xDim + x3];
              vTmp4 = ((ipUInt1_t *)picDoppler->data)[z*slice_size + y4*xDim + x4];

              v1 = (int) ((1-weightX)*(1-weightY)*vTmp1 + weightX*(1-weightY)*vTmp2 + weightX*weightY*vTmp3 + (1-weightX)*weightY*vTmp4);
              v2 = ((ipUInt1_t *)picDoppler->data)[z*slice_size + y*xDim + x] ;
#else
              x1 = (int)(x + dx);
              y1 = (int)(y + dy);
              if (y1<0) y1=0;

#endif
              v1 = ((ipUInt1_t *)picDoppler->data)[z*slice_size + y1*xDim + x1];
              v2 = ((ipUInt1_t *)picDoppler->data)[z*slice_size + y*xDim + x] ;
            }

            if (v1==128) {  // schaue in Gegenrichtung, falls keine SRI hier berechenbar
              x1 = (int)(x - dx);
              y1 = (int)(y - dy);
              if (y1>yDim) y1=yDim;
              //swap v1 and v2, otherwise StrainRate is calculate in false direction
              v1 = v2;
              v2 = ((ipUInt1_t *)picDoppler->data)[z*slice_size + y1*xDim + x1];
            }

            if ( 	(v1==0 ) || (v2==0)  ||	// wenn keine Geschwindigkeit vorhanden
              // oder wenn nur ganz kleine Geschwindigkeit vorhanden
              (v1>=(128-m_NoStrainInterval) && v1<=(128+m_NoStrainInterval)) ||
              (v2>=(128-m_NoStrainInterval) && v2<=(128+m_NoStrainInterval))) {

                strainRate = 128;  // this means no deformation
                // this is neccessay due to the Cyl2Cart filter

              } else {
                strainRate = (int)( (v1 - v2)/2 + 128 );
                if (strainRate==128) strainRate=129;
              }

              if (strainRate < minStrainRate && strainRate > 0 )
                minStrainRate = strainRate;

              if (strainRate > maxStrainRate)
                maxStrainRate = strainRate;

              if (strainRate<0 ) {
                //strainRate = -strainRate;
                std::cout << " error: neg. strainRate ... exit() " << std::endl;
                std::cout << " x=" << x << " y=" << y << " z=" << z << std::endl;
                std::cout << " v1=" << v1 << " v2=" << v2 << " dist=" << m_Distance << std::endl;
                std::cout << " sr=" << strainRate  << std::endl;
                exit(0);
              }

              ((ipUInt1_t *)picStrainRate->data)[t*vol_size + z*slice_size + y*xDim + x]=strainRate;

              // cout << "z: " << z << " y: " << y << " x: " << x << " strainrate: " << strainRate << endl;

#ifdef WRITE_ANGLE_PIC
              //						if (!isAnglePicWritten)
              //					((ipInt1_t *)anglePic->data)[y*xDim + x] = (int) ( (alpha/1.6)*128);
              if (!isAnglePicWritten)
                ((ipInt1_t *)anglePic->data)[y*xDim + x] = (int) ( dx);

#endif

          }  // x

        } // y

        //isAnglePicWritten = ipTrue;

      } // z

      //isStrainComputed = ipTrue;
      std::string filenameD;
      filenameD ="doppler.pic";
      ipPicPut(const_cast<char *>(filenameD.c_str()),picDoppler);

#define WRITE_STRAIN_PIC
#ifdef WRITE_STRAIN_PIC
      std::string filename;
      filename ="strain.pic";
      ipPicPut(const_cast<char *>(filename.c_str()),picStrainRate);
#endif

#ifdef WRITE_ANGLE_PIC
      std::string filename2;
      filename2="angle.pic";
      ipPicPut(const_cast<char *>(filename2.c_str()),anglePic);
#endif
      ((ipUInt1_t *)picStrainRate->data)[0]=0;
      ((ipUInt1_t *)picStrainRate->data)[1]=255;

      output->SetPicVolume(picStrainRate, t, n);
    }
  }
  std::cout << "Strain Rate Image computed.... " << std::endl;
  std::cout << "  minStrainRate: " << minStrainRate << std::endl;
  std::cout << "  maxStrainRate: " << maxStrainRate << std::endl;
}

mitk::DopplerToStrainRateFilter::DopplerToStrainRateFilter()
: m_Distance(10), m_NoStrainInterval(2)
{

  m_Origin.x = 0;
  m_Origin.y = 0;
  m_Origin.z = 0;

}

float mitk::DopplerToStrainRateFilter::GetLimit()
{	return (128/m_Distance);
}

mitk::DopplerToStrainRateFilter::~DopplerToStrainRateFilter()
{

}

void mitk::DopplerToStrainRateFilter::GenerateInputRequestedRegion()
{
  Superclass::GenerateInputRequestedRegion();

  mitk::ImageToImageFilter::InputImagePointer input =
    const_cast< mitk::ImageToImageFilter::InputImageType * > ( this->GetInput() );
  mitk::Image::Pointer output = this->GetOutput();

  Image::RegionType requestedRegion;
  requestedRegion = output->GetRequestedRegion();
  requestedRegion.SetIndex(0, 0);
  requestedRegion.SetIndex(1, 0);
  requestedRegion.SetIndex(2, 0);
  //requestedRegion.SetIndex(3, 0);
  //requestedRegion.SetIndex(4, 0);
  requestedRegion.SetSize(0, input->GetDimension(0));
  requestedRegion.SetSize(1, input->GetDimension(1));
  requestedRegion.SetSize(2, input->GetDimension(2));
  //requestedRegion.SetSize(3, output->GetDimension(3));
  //requestedRegion.SetSize(4, output->GetNumberOfChannels());

  input->SetRequestedRegion( & requestedRegion );
}
<commit_msg>smooth image before computing strain rate<commit_after>#include "mitkDopplerToStrainRateFilter.h"
#include "mitkImageTimeSelector.h"
#include "mitkProperties.h"
#include "mitkPlaneGeometry.h"

#include <iostream>
#include <string>
#include <ipFunc.h>

void mitk::DopplerToStrainRateFilter::GenerateOutputInformation()
{
  mitk::Image::ConstPointer input = this->GetInput();
  mitk::Image::Pointer output = this->GetOutput();

  if ((output->IsInitialized()) && (this->GetMTime() <= m_TimeOfHeaderInitialization.GetMTime()))
    return;

  itkDebugMacro(<<"GenerateOutputInformation()");

  unsigned int i;
  unsigned int *tmpDimensions = new unsigned int[input->GetDimension()];

  for(i=0;i<input->GetDimension();++i)
    tmpDimensions[i]=input->GetDimension(i);

  //@todo maybe we should shift the following somehow in ImageToImageFilter
  output->Initialize(input->GetPixelType(),
    input->GetDimension(),
    tmpDimensions,
    input->GetNumberOfChannels());

  output->GetSlicedGeometry()->SetSpacing(input->GetSlicedGeometry()->GetSpacing());

  output->GetSlicedGeometry()->SetGeometry2D(mitk::Image::BuildStandardPlaneGeometry2D(output->GetSlicedGeometry(), tmpDimensions).GetPointer(), 0);
  output->GetSlicedGeometry()->SetEvenlySpaced();
  //set the timebounds - after SetGeometry2D, so that the already created PlaneGeometry will also receive this timebounds.
  output->GetSlicedGeometry()->SetTimeBoundsInMS(input->GetSlicedGeometry()->GetTimeBoundsInMS());

  output->SetPropertyList(input->GetPropertyList()->Clone());

  delete [] tmpDimensions;

  m_TimeOfHeaderInitialization.Modified();
}

void mitk::DopplerToStrainRateFilter::GenerateData()
{
  mitk::Image::ConstPointer input = this->GetInput();
  mitk::Image::Pointer output = this->GetOutput();

  mitk::Point3iProperty::Pointer pointProp;
  pointProp = dynamic_cast<mitk::Point3iProperty*>(input->GetProperty("ORIGIN").GetPointer());
  if (pointProp.IsNotNull() )
  {
    m_Origin = pointProp->GetValue();
  }

  std::cout << "compute Strain Rate Image .... " << std::endl;
  std::cout << "  origin.x=" << m_Origin.x << " origin.y=" << m_Origin.y << " origin.z=" << m_Origin.z << std::endl;
  std::cout << "  distance=" << m_Distance << std::endl;
  std::cout << "  NoStrainIntervall=" << m_NoStrainInterval << std::endl;

  const float *spacing = input->GetSlicedGeometry()->GetSpacing();
  //	std::cout << "   in: xres=" << spacing[0] << " yres=" << spacing[1] << " zres=" << spacing[2] << std::endl;

  mitk::ImageTimeSelector::Pointer timeSelector=mitk::ImageTimeSelector::New();
  timeSelector->SetInput(input);

  ipPicDescriptor* picStrainRate;
  picStrainRate = ipPicNew();
  picStrainRate->dim=3;
  picStrainRate->bpe  = output->GetPixelType().GetBpe();
  picStrainRate->type = output->GetPixelType().GetType();
  picStrainRate->n[0] = output->GetDimension(0);
  picStrainRate->n[1] = output->GetDimension(1);
  picStrainRate->n[2] = output->GetDimension(2);
  picStrainRate->data=malloc(_ipPicSize(picStrainRate));

  int xDim = picStrainRate->n[0];
  int yDim = picStrainRate->n[1];
  int zDim = picStrainRate->n[2];
  long slice_size = xDim*yDim;
  long vol_size = slice_size*zDim;

  ipPicDescriptor *picDoppler;

  int x,y,z,time;							// loop-counter
  int strainRate;						// the computed Strain Rate
  int v1,v2;								// velocity and Point p1 and p2

  float alpha;								// the beam-angle, angle betwen current point and beam-point
  float dx, dy;								// projection of this->distance to x- and y-axis
  float weightX, weightY;			// weigth-factors for x-velocity and y-velocity
  int dxFloor, dyFloor;				// floored dx, dy

  int x1, x2, x3, x4;					// a square, where the velocity v1 lies in
  int y1, y2, y3, y4;					// the points are used for interpolation
  int vTmp1, vTmp2;						// velocities used for interpolation
  int vTmp3, vTmp4;

  int minStrainRate=128, maxStrainRate=128;

  int n, nmax;
  int t, tmax;

  t = output->GetRequestedRegion().GetIndex(3);
  n = output->GetRequestedRegion().GetIndex(4);
	std::cout << "t = " <<t << " n = " << n << std::endl;

  tmax = t + output->GetRequestedRegion().GetSize(3);
  nmax = n + output->GetRequestedRegion().GetSize(4);
	std::cout << "tmax = "<< tmax << " nmax = " << nmax << std::endl;

  if (m_Distance<1) m_Distance=1;

  for(;n<nmax;n++)//output->GetNumberOfChannels();++n)
  {
    timeSelector->SetChannelNr(n);
		std::cout << "computing chanel n = " << n << std::endl;

    for(t=0;t<tmax;t++)
    {
			std::cout << "computing time slot t = " << t << std::endl;
      timeSelector->SetTimeNr(t);
      timeSelector->Update();

      _ipPicFreeTags(picStrainRate->info->tags_head);
      picStrainRate->info->tags_head = _ipPicCloneTags(timeSelector->GetOutput()->GetPic()->info->tags_head);

//#define       WRITE_ANGLE_PIC
#ifdef WRITE_ANGLE_PIC
      ipPicDescriptor *anglePic;
      ipBool_t isAnglePicWritten = ipFalse;

      anglePic = ipPicNew();
      anglePic->type = ipPicInt;
      anglePic->bpe = 8;
      anglePic->dim = 2;
      anglePic->n[0] = xDim;
      anglePic->n[1] = yDim;
      anglePic->data = (ipInt1_t *)calloc(xDim*yDim,sizeof(ipInt1_t));
#endif

      picDoppler = timeSelector->GetOutput()->GetPic();
			picDoppler = ipFuncGausF( picDoppler, 5,2 , ipFuncBorderOld )  ;

      for (z=0 ; z<zDim ; z++) {

        for (y=1; y<yDim; y++) {

          if (y<m_Origin.y) continue;  // cannot compute StrainRate above Transducer-Position

          for (x=0; x<xDim; x++) {

            if ((m_Origin.x - x)==0) {  // winkelhalbierende

              int yDistanceInUnits = (int)( m_Distance/spacing[1]);
              int yTmp = ( (y-yDistanceInUnits)<0 )  ? 0 : (y-yDistanceInUnits);
              v1 = ((ipUInt1_t *)picDoppler->data)[z*slice_size + yTmp*xDim + x] ;
              v2 = ((ipUInt1_t *)picDoppler->data)[z*slice_size + y*xDim + x] ;

            } else {

              // compute angle to transducer position
              // m_Origin is given in units, not in mm
              alpha = atan( (float) (m_Origin.x - x)  / (float) (m_Origin.y - y) );

              // m_Distance is given in mm
              dx = -sin(alpha) * m_Distance;
              dy = -cos(alpha) * m_Distance;

              // convert to units
              dx = dx/spacing[0];
              dy = dy/spacing[1];

              //#define WEIGTHED
#ifdef WEIGTHED
              weightX = dx - floor(dx);
              weightY = dy - floor(dy);

              dxFloor = (int) floor(dx);
              dyFloor = (int) floor(dy);

              x1 = x + dxFloor;					// lower left
              y1 = y + dyFloor;

              x2 = x + (dxFloor+1);			// lower right
              y2 = y + dyFloor;

              x3 = x + (dxFloor+1);			// upper right
              y3 = y + (dyFloor+1);

              x4 = x + dxFloor;					// upper left
              y4 = y + (dyFloor+1);

              vTmp1 = ((ipUInt1_t *)picDoppler->data)[z*slice_size + y1*xDim + x1];
              vTmp2 = ((ipUInt1_t *)picDoppler->data)[z*slice_size + y2*xDim + x2];
              vTmp3 = ((ipUInt1_t *)picDoppler->data)[z*slice_size + y3*xDim + x3];
              vTmp4 = ((ipUInt1_t *)picDoppler->data)[z*slice_size + y4*xDim + x4];

              v1 = (int) ((1-weightX)*(1-weightY)*vTmp1 + weightX*(1-weightY)*vTmp2 + weightX*weightY*vTmp3 + (1-weightX)*weightY*vTmp4);
              v2 = ((ipUInt1_t *)picDoppler->data)[z*slice_size + y*xDim + x] ;
#else
              x1 = (int)(x + dx);
              y1 = (int)(y + dy);
              if (y1<0) y1=0;

#endif
              v1 = ((ipUInt1_t *)picDoppler->data)[z*slice_size + y1*xDim + x1];
              v2 = ((ipUInt1_t *)picDoppler->data)[z*slice_size + y*xDim + x] ;
            }

            if (v1==128) {  // schaue in Gegenrichtung, falls keine SRI hier berechenbar
              x1 = (int)(x - dx);
              y1 = (int)(y - dy);
              if (y1>yDim) y1=yDim;
              //swap v1 and v2, otherwise StrainRate is calculate in false direction
              v1 = v2;
              v2 = ((ipUInt1_t *)picDoppler->data)[z*slice_size + y1*xDim + x1];
            }

            if ( 	(v1==0 ) || (v2==0)  ||	// wenn keine Geschwindigkeit vorhanden
              // oder wenn nur ganz kleine Geschwindigkeit vorhanden
              (v1>=(128-m_NoStrainInterval) && v1<=(128+m_NoStrainInterval)) ||
              (v2>=(128-m_NoStrainInterval) && v2<=(128+m_NoStrainInterval))) {

                strainRate = 128;  // this means no deformation
                // this is neccessay due to the Cyl2Cart filter

              } else {
                strainRate = (int)( (v1 - v2)/2 + 128 );
                if (strainRate==128) strainRate=129;
              }

              if (strainRate < minStrainRate && strainRate > 0 )
                minStrainRate = strainRate;

              if (strainRate > maxStrainRate)
                maxStrainRate = strainRate;

              if (strainRate<0 ) {
                //strainRate = -strainRate;
                std::cout << " error: neg. strainRate ... exit() " << std::endl;
                std::cout << " x=" << x << " y=" << y << " z=" << z << std::endl;
                std::cout << " v1=" << v1 << " v2=" << v2 << " dist=" << m_Distance << std::endl;
                std::cout << " sr=" << strainRate  << std::endl;
                exit(0);
              }

              ((ipUInt1_t *)picStrainRate->data)[t*vol_size + z*slice_size + y*xDim + x]=strainRate;

              // cout << "z: " << z << " y: " << y << " x: " << x << " strainrate: " << strainRate << endl;

#ifdef WRITE_ANGLE_PIC
              //						if (!isAnglePicWritten)
              //					((ipInt1_t *)anglePic->data)[y*xDim + x] = (int) ( (alpha/1.6)*128);
              if (!isAnglePicWritten)
                ((ipInt1_t *)anglePic->data)[y*xDim + x] = (int) ( dx);

#endif

          }  // x

        } // y

        //isAnglePicWritten = ipTrue;

      } // z

      //isStrainComputed = ipTrue;
      std::string filenameD;
      filenameD ="doppler.pic";
      ipPicPut(const_cast<char *>(filenameD.c_str()),picDoppler);

#define WRITE_STRAIN_PIC
#ifdef WRITE_STRAIN_PIC
			char tmpfilename[100];
      sprintf(tmpfilename,"strain%d.pic",t);;
      ipPicPut(tmpfilename,picStrainRate);
#endif

#ifdef WRITE_ANGLE_PIC
      std::string filename2;
      filename2="angle.pic";
      ipPicPut(const_cast<char *>(filename2.c_str()),anglePic);
#endif
      ((ipUInt1_t *)picStrainRate->data)[0]=0;
      ((ipUInt1_t *)picStrainRate->data)[1]=255;

      output->SetPicVolume(picStrainRate, t, n);
    }
  }

	ipPicFree(picStrainRate);

#define WRITE_STRAIN_PIC
#ifdef WRITE_STRAIN_PIC
			picStrainRate = output->GetPic();
      std::string filename;
      filename ="strain.pic";
      ipPicPut(const_cast<char *>(filename.c_str()),picStrainRate);
#endif

  std::cout << "Strain Rate Image computed.... " << std::endl;
  std::cout << "  minStrainRate: " << minStrainRate << std::endl;
  std::cout << "  maxStrainRate: " << maxStrainRate << std::endl;
}

mitk::DopplerToStrainRateFilter::DopplerToStrainRateFilter()
: m_Distance(10), m_NoStrainInterval(2)
{

  m_Origin.x = 0;
  m_Origin.y = 0;
  m_Origin.z = 0;

}

float mitk::DopplerToStrainRateFilter::GetLimit()
{	return (128/m_Distance);
}

mitk::DopplerToStrainRateFilter::~DopplerToStrainRateFilter()
{

}

void mitk::DopplerToStrainRateFilter::GenerateInputRequestedRegion()
{
  Superclass::GenerateInputRequestedRegion();

  mitk::ImageToImageFilter::InputImagePointer input =
    const_cast< mitk::ImageToImageFilter::InputImageType * > ( this->GetInput() );
  mitk::Image::Pointer output = this->GetOutput();

  Image::RegionType requestedRegion;
  requestedRegion = output->GetRequestedRegion();
  requestedRegion.SetIndex(0, 0);
  requestedRegion.SetIndex(1, 0);
  requestedRegion.SetIndex(2, 0);
  //requestedRegion.SetIndex(3, 0);
  //requestedRegion.SetIndex(4, 0);
  requestedRegion.SetSize(0, input->GetDimension(0));
  requestedRegion.SetSize(1, input->GetDimension(1));
  requestedRegion.SetSize(2, input->GetDimension(2));
  //requestedRegion.SetSize(3, output->GetDimension(3));
  //requestedRegion.SetSize(4, output->GetNumberOfChannels());

  input->SetRequestedRegion( & requestedRegion );
}
<|endoftext|>