<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include "contentenumeration.hxx"
#include <svtools/inettbc.hxx>
#include <svtools/imagemgr.hxx>

#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/sdbc/XResultSet.hpp>
#include <com/sun/star/sdbc/XRow.hpp>
#include <com/sun/star/ucb/XDynamicResultSet.hpp>
#include <com/sun/star/ucb/XContentAccess.hpp>
#include <com/sun/star/util/DateTime.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/document/DocumentProperties.hpp>
#include <comphelper/processfactory.hxx>
#include <tools/debug.hxx>
#include <vcl/svapp.hxx>
#include <osl/mutex.hxx>

#include <memory>

//........................................................................
namespace svt
{
//........................................................................

#define ROW_TITLE           1
#define ROW_SIZE            2
#define ROW_DATE_MOD        3
#define ROW_DATE_CREATE     4
#define ROW_IS_FOLDER       5
#define ROW_TARGET_URL      6
#define ROW_IS_HIDDEN       7
#define ROW_IS_VOLUME       8
#define ROW_IS_REMOTE       9
#define ROW_IS_REMOVABLE    10
#define ROW_IS_FLOPPY       11
#define ROW_IS_COMPACTDISC  12

#define CONVERT_DATETIME( aUnoDT, aToolsDT ) \
    aToolsDT = ::DateTime( Date( aUnoDT.Day, aUnoDT.Month, aUnoDT.Year ), \
                           Time( aUnoDT.Hours, aUnoDT.Minutes, aUnoDT.Seconds, aUnoDT.NanoSeconds ) );

    using ::com::sun::star::uno::Reference;
    using ::com::sun::star::uno::Sequence;
    using ::com::sun::star::uno::Exception;
    using ::com::sun::star::uno::UNO_QUERY;
    using ::com::sun::star::uno::Any;
    using ::com::sun::star::util::DateTime;
    using ::com::sun::star::sdbc::XResultSet;
    using ::com::sun::star::sdbc::XRow;
    using ::com::sun::star::ucb::XDynamicResultSet;
    using ::com::sun::star::ucb::CommandAbortedException;
    using ::com::sun::star::ucb::XContentAccess;
    using ::com::sun::star::ucb::XCommandEnvironment;
    using ::com::sun::star::beans::XPropertySet;
    using ::com::sun::star::beans::PropertyValue;
    using ::com::sun::star::document::DocumentProperties;
    using ::ucbhelper::ResultSetInclude;
    using ::ucbhelper::INCLUDE_FOLDERS_AND_DOCUMENTS;

    //====================================================================
    //= FileViewContentEnumerator
    //====================================================================
    //--------------------------------------------------------------------
    FileViewContentEnumerator::FileViewContentEnumerator(
            const Reference< XCommandEnvironment >& _rxCommandEnv,
            ContentData& _rContentToFill, ::osl::Mutex& _rContentMutex,
            const IContentTitleTranslation* _pTranslator )
        :Thread                  ( "FileViewContentEnumerator" )
        ,m_rContent              ( _rContentToFill )
        ,m_rContentMutex         ( _rContentMutex  )
        ,m_xCommandEnv           ( _rxCommandEnv   )
        ,m_pTranslator           ( _pTranslator    )
        ,m_bCancelled            ( false           )
        ,m_rBlackList            ( ::com::sun::star::uno::Sequence< OUString >() )
    {
    }

    //--------------------------------------------------------------------
    FileViewContentEnumerator::~FileViewContentEnumerator()
    {
    }

    //--------------------------------------------------------------------
    void FileViewContentEnumerator::cancel()
    {
        ::osl::MutexGuard aGuard( m_aMutex );
        m_bCancelled = true;
        m_pResultHandler = NULL;
        m_pTranslator = NULL;
        m_aFolder.aContent = ::ucbhelper::Content();
        m_aFolder.sURL = "";
    }

    //--------------------------------------------------------------------
    EnumerationResult FileViewContentEnumerator::enumerateFolderContentSync(
        const FolderDescriptor& _rFolder,
        const ::com::sun::star::uno::Sequence< OUString >& rBlackList )
    {
        {
            ::osl::MutexGuard aGuard( m_aMutex );
            m_aFolder = _rFolder;
            m_pResultHandler = NULL;
            m_rBlackList = rBlackList;
        }
        return enumerateFolderContent();
    }

    //--------------------------------------------------------------------
    void FileViewContentEnumerator::enumerateFolderContent(
        const FolderDescriptor& _rFolder, IEnumerationResultHandler* _pResultHandler )
    {
        ::osl::MutexGuard aGuard( m_aMutex );
        m_aFolder = _rFolder;
        m_pResultHandler = _pResultHandler;

        OSL_ENSURE( m_aFolder.aContent.get().is() || !m_aFolder.sURL.isEmpty(),
            "FileViewContentEnumerator::enumerateFolderContent: invalid folder descriptor!" );

        launch();
            //TODO: a protocol is missing how to join with the launched thread
            // before exit(3), to ensure the thread is no longer relying on any
            // infrastructure while that infrastructure is being shut down in
            // atexit handlers
    }

    //--------------------------------------------------------------------
    EnumerationResult FileViewContentEnumerator::enumerateFolderContent()
    {
        EnumerationResult eResult = ERROR;
        try
        {

            Reference< XResultSet > xResultSet;
            Sequence< OUString > aProps(12);

            aProps[0] = OUString( "Title" );
            aProps[1] = OUString( "Size" );
            aProps[2] = OUString( "DateModified" );
            aProps[3] = OUString( "DateCreated" );
            aProps[4] = OUString( "IsFolder" );
            aProps[5] = OUString( "TargetURL" );
            aProps[6] = OUString( "IsHidden" );
            aProps[7] = OUString( "IsVolume" );
            aProps[8] = OUString( "IsRemote" );
            aProps[9] = OUString( "IsRemoveable" );
            aProps[10] = OUString( "IsFloppy" );
            aProps[11] = OUString( "IsCompactDisc" );

            Reference< XCommandEnvironment > xEnvironment;
            try
            {
                FolderDescriptor aFolder;
                {
                    ::osl::MutexGuard aGuard( m_aMutex );
                    aFolder = m_aFolder;
                    xEnvironment = m_xCommandEnv;
                }
                if ( !aFolder.aContent.get().is() )
                {
                    aFolder.aContent = ::ucbhelper::Content( aFolder.sURL, xEnvironment, comphelper::getProcessComponentContext() );
                    {
                        ::osl::MutexGuard aGuard( m_aMutex );
                        m_aFolder.aContent = aFolder.aContent;
                    }
                }

                Reference< XDynamicResultSet > xDynResultSet;
                ResultSetInclude eInclude = INCLUDE_FOLDERS_AND_DOCUMENTS;
                xDynResultSet = aFolder.aContent.createDynamicCursor( aProps, eInclude );

                if ( xDynResultSet.is() )
                    xResultSet = xDynResultSet->getStaticResultSet();
            }
            catch( CommandAbortedException& )
            {
                SAL_WARN( "svtools.contnr", "createCursor: CommandAbortedException" );
            }
            catch( Exception& )
            {
            }

            bool bCancelled = false;
            if ( xResultSet.is() )
            {
                Reference< XRow > xRow( xResultSet, UNO_QUERY );
                Reference< XContentAccess > xContentAccess( xResultSet, UNO_QUERY );

                try
                {
                    SortingData_Impl* pData;
                    DateTime aDT;

                    while ( !bCancelled && xResultSet->next() )
                    {
                        sal_Bool bIsHidden = xRow->getBoolean( ROW_IS_HIDDEN );
                        // don't show hidden files
                        if ( !bIsHidden || xRow->wasNull() )
                        {
                            pData = NULL;

                            aDT = xRow->getTimestamp( ROW_DATE_MOD );
                            sal_Bool bContainsDate = !xRow->wasNull();
                            if ( !bContainsDate )
                            {
                                aDT = xRow->getTimestamp( ROW_DATE_CREATE );
                                bContainsDate = !xRow->wasNull();
                            }

                            OUString aContentURL = xContentAccess->queryContentIdentifierString();
                            OUString aTargetURL = xRow->getString( ROW_TARGET_URL );
                            sal_Bool bHasTargetURL = !xRow->wasNull() && !aTargetURL.isEmpty();

                            OUString sRealURL = bHasTargetURL ? aTargetURL : aContentURL;

                            // check for restrictions
                            {
                                ::osl::MutexGuard aGuard( m_aMutex );
                                if ( /* m_rBlackList.hasElements() && */ URLOnBlackList ( sRealURL ) )
                                    continue;
                            }

                            pData = new SortingData_Impl;
                            pData->maTargetURL = sRealURL;

                            pData->mbIsFolder = xRow->getBoolean( ROW_IS_FOLDER ) && !xRow->wasNull();
                            pData->mbIsVolume = xRow->getBoolean( ROW_IS_VOLUME ) && !xRow->wasNull();
                            pData->mbIsRemote = xRow->getBoolean( ROW_IS_REMOTE ) && !xRow->wasNull();
                            pData->mbIsRemoveable = xRow->getBoolean( ROW_IS_REMOVABLE ) && !xRow->wasNull();
                            pData->mbIsFloppy = xRow->getBoolean( ROW_IS_FLOPPY ) && !xRow->wasNull();
                            pData->mbIsCompactDisc = xRow->getBoolean( ROW_IS_COMPACTDISC ) && !xRow->wasNull();
                            pData->SetNewTitle( xRow->getString( ROW_TITLE ) );
                            pData->maSize = xRow->getLong( ROW_SIZE );

                            if ( bHasTargetURL &&
                                INetURLObject( aContentURL ).GetProtocol() == INET_PROT_VND_SUN_STAR_HIER )
                            {
                                ::ucbhelper::Content aCnt( aTargetURL, xEnvironment, comphelper::getProcessComponentContext() );
                                try
                                {
                                aCnt.getPropertyValue("Size") >>= pData->maSize;
                                aCnt.getPropertyValue("DateModified") >>= aDT;
                                }
                                catch (...) {}
                            }

                            if ( bContainsDate )
                            {
                                CONVERT_DATETIME( aDT, pData->maModDate );
                            }

                            if ( pData->mbIsFolder )
                            {
                                SolarMutexGuard aGuard;
                                ::svtools::VolumeInfo aVolInfo( pData->mbIsVolume, pData->mbIsRemote,
                                                                pData->mbIsRemoveable, pData->mbIsFloppy,
                                                                pData->mbIsCompactDisc );
                                pData->maType = SvFileInformationManager::GetFolderDescription( aVolInfo );
                            }
                            else
                                pData->maType = SvFileInformationManager::GetFileDescription(
                                    INetURLObject( pData->maTargetURL ) );

                            // replace names on demand
                            {
                                ::osl::MutexGuard aGuard( m_aMutex );
                                if( m_pTranslator )
                                {
                                    OUString sNewTitle;
                                    sal_Bool bTranslated = sal_False;

                                    if ( pData->mbIsFolder )
                                        bTranslated = m_pTranslator->GetTranslation( pData->GetTitle(), sNewTitle );
                                    else
                                        bTranslated = implGetDocTitle( pData->maTargetURL, sNewTitle );

                                    if ( bTranslated )
                                        pData->ChangeTitle( sNewTitle );
                                }
                            }

                            {
                                ::osl::MutexGuard aGuard( m_rContentMutex );
                                m_rContent.push_back( pData );
                            }
                        }

                        {
                            ::osl::MutexGuard aGuard( m_aMutex );
                            bCancelled = m_bCancelled;
                        }
                    }
                    eResult = SUCCESS;
                }
                catch( CommandAbortedException& )
                {
                    SAL_WARN( "svtools.contnr", "FileViewContentEnumerator::enumerateFolderContent: caught an CommandAbortedException while enumerating!" );
                }
                catch( Exception& )
                {
                    SAL_WARN( "svtools.contnr", "FileViewContentEnumerator::enumerateFolderContent: caught an exception other than CommandAbortedException while enumerating!" );
                }
            }
        }
        catch( CommandAbortedException& )
        {
            SAL_WARN( "svtools.contnr", "FileViewContentEnumerator::enumerateFolderContent: caught an CommandAbortedException!" );
        }
        catch( Exception& )
        {
            SAL_WARN( "svtools.contnr", "FileViewContentEnumerator::enumerateFolderContent: caught an exception other than CommandAbortedException!" );
        }

        IEnumerationResultHandler* pHandler = NULL;
        {
            ::osl::MutexGuard aGuard( m_aMutex );
            pHandler = m_pResultHandler;
            if ( m_bCancelled )
                return ERROR;
        }

        {
            ::osl::MutexGuard aGuard( m_rContentMutex );
            if ( eResult != SUCCESS )
                // clear any "intermediate" and unfinished result
                m_rContent.clear();
        }

        if ( pHandler )
            pHandler->enumerationDone( eResult );
        return eResult;
    }

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

    sal_Bool FileViewContentEnumerator::URLOnBlackList ( const OUString& sRealURL )
    {
        OUString entryName = sRealURL.copy( sRealURL.lastIndexOf( '/' ) + 1 );

        for (int i = 0; i < m_rBlackList.getLength() ; i++)
        {
            if ( entryName.equals(  m_rBlackList[i] ) )
                return true;
        }

        return false;
    }

    //--------------------------------------------------------------------
    sal_Bool FileViewContentEnumerator::implGetDocTitle( const OUString& _rTargetURL, OUString& _rRet ) const
    {
        sal_Bool bRet = sal_False;

        try
        {
            ::osl::MutexGuard aGuard( m_aMutex );
            if (!m_xDocProps.is())
            {
                m_xDocProps.set(DocumentProperties::create(
                            ::comphelper::getProcessComponentContext()));
            }

            assert(m_xDocProps.is());
            if (!m_xDocProps.is())
                return sal_False;

            m_xDocProps->loadFromMedium(_rTargetURL, Sequence<PropertyValue>());

            OUString const sTitle(m_xDocProps->getTitle());
            if (!sTitle.isEmpty())
            {
                _rRet = sTitle;
                bRet = sal_True;
            }
        }
        catch ( const Exception& )
        {
        }

        return bRet;
    }

    //--------------------------------------------------------------------
    void FileViewContentEnumerator::execute()
    {
        enumerateFolderContent();
    }

//........................................................................
} // namespace svt
//........................................................................

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>cppcheck: reduce scope<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include "contentenumeration.hxx"
#include <svtools/inettbc.hxx>
#include <svtools/imagemgr.hxx>

#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/sdbc/XResultSet.hpp>
#include <com/sun/star/sdbc/XRow.hpp>
#include <com/sun/star/ucb/XDynamicResultSet.hpp>
#include <com/sun/star/ucb/XContentAccess.hpp>
#include <com/sun/star/util/DateTime.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/document/DocumentProperties.hpp>
#include <comphelper/processfactory.hxx>
#include <tools/debug.hxx>
#include <vcl/svapp.hxx>
#include <osl/mutex.hxx>

#include <memory>

//........................................................................
namespace svt
{
//........................................................................

#define ROW_TITLE           1
#define ROW_SIZE            2
#define ROW_DATE_MOD        3
#define ROW_DATE_CREATE     4
#define ROW_IS_FOLDER       5
#define ROW_TARGET_URL      6
#define ROW_IS_HIDDEN       7
#define ROW_IS_VOLUME       8
#define ROW_IS_REMOTE       9
#define ROW_IS_REMOVABLE    10
#define ROW_IS_FLOPPY       11
#define ROW_IS_COMPACTDISC  12

#define CONVERT_DATETIME( aUnoDT, aToolsDT ) \
    aToolsDT = ::DateTime( Date( aUnoDT.Day, aUnoDT.Month, aUnoDT.Year ), \
                           Time( aUnoDT.Hours, aUnoDT.Minutes, aUnoDT.Seconds, aUnoDT.NanoSeconds ) );

    using ::com::sun::star::uno::Reference;
    using ::com::sun::star::uno::Sequence;
    using ::com::sun::star::uno::Exception;
    using ::com::sun::star::uno::UNO_QUERY;
    using ::com::sun::star::uno::Any;
    using ::com::sun::star::util::DateTime;
    using ::com::sun::star::sdbc::XResultSet;
    using ::com::sun::star::sdbc::XRow;
    using ::com::sun::star::ucb::XDynamicResultSet;
    using ::com::sun::star::ucb::CommandAbortedException;
    using ::com::sun::star::ucb::XContentAccess;
    using ::com::sun::star::ucb::XCommandEnvironment;
    using ::com::sun::star::beans::XPropertySet;
    using ::com::sun::star::beans::PropertyValue;
    using ::com::sun::star::document::DocumentProperties;
    using ::ucbhelper::ResultSetInclude;
    using ::ucbhelper::INCLUDE_FOLDERS_AND_DOCUMENTS;

    //====================================================================
    //= FileViewContentEnumerator
    //====================================================================
    //--------------------------------------------------------------------
    FileViewContentEnumerator::FileViewContentEnumerator(
            const Reference< XCommandEnvironment >& _rxCommandEnv,
            ContentData& _rContentToFill, ::osl::Mutex& _rContentMutex,
            const IContentTitleTranslation* _pTranslator )
        :Thread                  ( "FileViewContentEnumerator" )
        ,m_rContent              ( _rContentToFill )
        ,m_rContentMutex         ( _rContentMutex  )
        ,m_xCommandEnv           ( _rxCommandEnv   )
        ,m_pTranslator           ( _pTranslator    )
        ,m_bCancelled            ( false           )
        ,m_rBlackList            ( ::com::sun::star::uno::Sequence< OUString >() )
    {
    }

    //--------------------------------------------------------------------
    FileViewContentEnumerator::~FileViewContentEnumerator()
    {
    }

    //--------------------------------------------------------------------
    void FileViewContentEnumerator::cancel()
    {
        ::osl::MutexGuard aGuard( m_aMutex );
        m_bCancelled = true;
        m_pResultHandler = NULL;
        m_pTranslator = NULL;
        m_aFolder.aContent = ::ucbhelper::Content();
        m_aFolder.sURL = "";
    }

    //--------------------------------------------------------------------
    EnumerationResult FileViewContentEnumerator::enumerateFolderContentSync(
        const FolderDescriptor& _rFolder,
        const ::com::sun::star::uno::Sequence< OUString >& rBlackList )
    {
        {
            ::osl::MutexGuard aGuard( m_aMutex );
            m_aFolder = _rFolder;
            m_pResultHandler = NULL;
            m_rBlackList = rBlackList;
        }
        return enumerateFolderContent();
    }

    //--------------------------------------------------------------------
    void FileViewContentEnumerator::enumerateFolderContent(
        const FolderDescriptor& _rFolder, IEnumerationResultHandler* _pResultHandler )
    {
        ::osl::MutexGuard aGuard( m_aMutex );
        m_aFolder = _rFolder;
        m_pResultHandler = _pResultHandler;

        OSL_ENSURE( m_aFolder.aContent.get().is() || !m_aFolder.sURL.isEmpty(),
            "FileViewContentEnumerator::enumerateFolderContent: invalid folder descriptor!" );

        launch();
            //TODO: a protocol is missing how to join with the launched thread
            // before exit(3), to ensure the thread is no longer relying on any
            // infrastructure while that infrastructure is being shut down in
            // atexit handlers
    }

    //--------------------------------------------------------------------
    EnumerationResult FileViewContentEnumerator::enumerateFolderContent()
    {
        EnumerationResult eResult = ERROR;
        try
        {

            Reference< XResultSet > xResultSet;
            Sequence< OUString > aProps(12);

            aProps[0] = OUString( "Title" );
            aProps[1] = OUString( "Size" );
            aProps[2] = OUString( "DateModified" );
            aProps[3] = OUString( "DateCreated" );
            aProps[4] = OUString( "IsFolder" );
            aProps[5] = OUString( "TargetURL" );
            aProps[6] = OUString( "IsHidden" );
            aProps[7] = OUString( "IsVolume" );
            aProps[8] = OUString( "IsRemote" );
            aProps[9] = OUString( "IsRemoveable" );
            aProps[10] = OUString( "IsFloppy" );
            aProps[11] = OUString( "IsCompactDisc" );

            Reference< XCommandEnvironment > xEnvironment;
            try
            {
                FolderDescriptor aFolder;
                {
                    ::osl::MutexGuard aGuard( m_aMutex );
                    aFolder = m_aFolder;
                    xEnvironment = m_xCommandEnv;
                }
                if ( !aFolder.aContent.get().is() )
                {
                    aFolder.aContent = ::ucbhelper::Content( aFolder.sURL, xEnvironment, comphelper::getProcessComponentContext() );
                    {
                        ::osl::MutexGuard aGuard( m_aMutex );
                        m_aFolder.aContent = aFolder.aContent;
                    }
                }

                Reference< XDynamicResultSet > xDynResultSet;
                ResultSetInclude eInclude = INCLUDE_FOLDERS_AND_DOCUMENTS;
                xDynResultSet = aFolder.aContent.createDynamicCursor( aProps, eInclude );

                if ( xDynResultSet.is() )
                    xResultSet = xDynResultSet->getStaticResultSet();
            }
            catch( CommandAbortedException& )
            {
                SAL_WARN( "svtools.contnr", "createCursor: CommandAbortedException" );
            }
            catch( Exception& )
            {
            }

            if ( xResultSet.is() )
            {
                Reference< XRow > xRow( xResultSet, UNO_QUERY );
                Reference< XContentAccess > xContentAccess( xResultSet, UNO_QUERY );

                try
                {
                    SortingData_Impl* pData;
                    DateTime aDT;

                    bool bCancelled = false;
                    while ( !bCancelled && xResultSet->next() )
                    {
                        sal_Bool bIsHidden = xRow->getBoolean( ROW_IS_HIDDEN );
                        // don't show hidden files
                        if ( !bIsHidden || xRow->wasNull() )
                        {
                            pData = NULL;

                            aDT = xRow->getTimestamp( ROW_DATE_MOD );
                            sal_Bool bContainsDate = !xRow->wasNull();
                            if ( !bContainsDate )
                            {
                                aDT = xRow->getTimestamp( ROW_DATE_CREATE );
                                bContainsDate = !xRow->wasNull();
                            }

                            OUString aContentURL = xContentAccess->queryContentIdentifierString();
                            OUString aTargetURL = xRow->getString( ROW_TARGET_URL );
                            sal_Bool bHasTargetURL = !xRow->wasNull() && !aTargetURL.isEmpty();

                            OUString sRealURL = bHasTargetURL ? aTargetURL : aContentURL;

                            // check for restrictions
                            {
                                ::osl::MutexGuard aGuard( m_aMutex );
                                if ( /* m_rBlackList.hasElements() && */ URLOnBlackList ( sRealURL ) )
                                    continue;
                            }

                            pData = new SortingData_Impl;
                            pData->maTargetURL = sRealURL;

                            pData->mbIsFolder = xRow->getBoolean( ROW_IS_FOLDER ) && !xRow->wasNull();
                            pData->mbIsVolume = xRow->getBoolean( ROW_IS_VOLUME ) && !xRow->wasNull();
                            pData->mbIsRemote = xRow->getBoolean( ROW_IS_REMOTE ) && !xRow->wasNull();
                            pData->mbIsRemoveable = xRow->getBoolean( ROW_IS_REMOVABLE ) && !xRow->wasNull();
                            pData->mbIsFloppy = xRow->getBoolean( ROW_IS_FLOPPY ) && !xRow->wasNull();
                            pData->mbIsCompactDisc = xRow->getBoolean( ROW_IS_COMPACTDISC ) && !xRow->wasNull();
                            pData->SetNewTitle( xRow->getString( ROW_TITLE ) );
                            pData->maSize = xRow->getLong( ROW_SIZE );

                            if ( bHasTargetURL &&
                                INetURLObject( aContentURL ).GetProtocol() == INET_PROT_VND_SUN_STAR_HIER )
                            {
                                ::ucbhelper::Content aCnt( aTargetURL, xEnvironment, comphelper::getProcessComponentContext() );
                                try
                                {
                                aCnt.getPropertyValue("Size") >>= pData->maSize;
                                aCnt.getPropertyValue("DateModified") >>= aDT;
                                }
                                catch (...) {}
                            }

                            if ( bContainsDate )
                            {
                                CONVERT_DATETIME( aDT, pData->maModDate );
                            }

                            if ( pData->mbIsFolder )
                            {
                                SolarMutexGuard aGuard;
                                ::svtools::VolumeInfo aVolInfo( pData->mbIsVolume, pData->mbIsRemote,
                                                                pData->mbIsRemoveable, pData->mbIsFloppy,
                                                                pData->mbIsCompactDisc );
                                pData->maType = SvFileInformationManager::GetFolderDescription( aVolInfo );
                            }
                            else
                                pData->maType = SvFileInformationManager::GetFileDescription(
                                    INetURLObject( pData->maTargetURL ) );

                            // replace names on demand
                            {
                                ::osl::MutexGuard aGuard( m_aMutex );
                                if( m_pTranslator )
                                {
                                    OUString sNewTitle;
                                    sal_Bool bTranslated = sal_False;

                                    if ( pData->mbIsFolder )
                                        bTranslated = m_pTranslator->GetTranslation( pData->GetTitle(), sNewTitle );
                                    else
                                        bTranslated = implGetDocTitle( pData->maTargetURL, sNewTitle );

                                    if ( bTranslated )
                                        pData->ChangeTitle( sNewTitle );
                                }
                            }

                            {
                                ::osl::MutexGuard aGuard( m_rContentMutex );
                                m_rContent.push_back( pData );
                            }
                        }

                        {
                            ::osl::MutexGuard aGuard( m_aMutex );
                            bCancelled = m_bCancelled;
                        }
                    }
                    eResult = SUCCESS;
                }
                catch( CommandAbortedException& )
                {
                    SAL_WARN( "svtools.contnr", "FileViewContentEnumerator::enumerateFolderContent: caught an CommandAbortedException while enumerating!" );
                }
                catch( Exception& )
                {
                    SAL_WARN( "svtools.contnr", "FileViewContentEnumerator::enumerateFolderContent: caught an exception other than CommandAbortedException while enumerating!" );
                }
            }
        }
        catch( CommandAbortedException& )
        {
            SAL_WARN( "svtools.contnr", "FileViewContentEnumerator::enumerateFolderContent: caught an CommandAbortedException!" );
        }
        catch( Exception& )
        {
            SAL_WARN( "svtools.contnr", "FileViewContentEnumerator::enumerateFolderContent: caught an exception other than CommandAbortedException!" );
        }

        IEnumerationResultHandler* pHandler = NULL;
        {
            ::osl::MutexGuard aGuard( m_aMutex );
            pHandler = m_pResultHandler;
            if ( m_bCancelled )
                return ERROR;
        }

        {
            ::osl::MutexGuard aGuard( m_rContentMutex );
            if ( eResult != SUCCESS )
                // clear any "intermediate" and unfinished result
                m_rContent.clear();
        }

        if ( pHandler )
            pHandler->enumerationDone( eResult );
        return eResult;
    }

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

    sal_Bool FileViewContentEnumerator::URLOnBlackList ( const OUString& sRealURL )
    {
        OUString entryName = sRealURL.copy( sRealURL.lastIndexOf( '/' ) + 1 );

        for (int i = 0; i < m_rBlackList.getLength() ; i++)
        {
            if ( entryName.equals(  m_rBlackList[i] ) )
                return true;
        }

        return false;
    }

    //--------------------------------------------------------------------
    sal_Bool FileViewContentEnumerator::implGetDocTitle( const OUString& _rTargetURL, OUString& _rRet ) const
    {
        sal_Bool bRet = sal_False;

        try
        {
            ::osl::MutexGuard aGuard( m_aMutex );
            if (!m_xDocProps.is())
            {
                m_xDocProps.set(DocumentProperties::create(
                            ::comphelper::getProcessComponentContext()));
            }

            assert(m_xDocProps.is());
            if (!m_xDocProps.is())
                return sal_False;

            m_xDocProps->loadFromMedium(_rTargetURL, Sequence<PropertyValue>());

            OUString const sTitle(m_xDocProps->getTitle());
            if (!sTitle.isEmpty())
            {
                _rRet = sTitle;
                bRet = sal_True;
            }
        }
        catch ( const Exception& )
        {
        }

        return bRet;
    }

    //--------------------------------------------------------------------
    void FileViewContentEnumerator::execute()
    {
        enumerateFolderContent();
    }

//........................................................................
} // namespace svt
//........................................................................

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


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

#include <string>
#include <regex>
#include <vector>

#include "rcpputils/find_and_replace.hpp"
#include "rclcpp/parameter_map.hpp"

using rclcpp::exceptions::InvalidParametersException;
using rclcpp::exceptions::InvalidParameterValueException;
using rclcpp::ParameterMap;
using rclcpp::ParameterValue;

ParameterMap
rclcpp::parameter_map_from(const rcl_params_t * const c_params, const char * node_fqn)
{
  if (NULL == c_params) {
    throw InvalidParametersException("parameters struct is NULL");
  } else if (NULL == c_params->node_names) {
    throw InvalidParametersException("node names array is NULL");
  } else if (NULL == c_params->params) {
    throw InvalidParametersException("node params array is NULL");
  }

  // Convert c structs into a list of parameters to set
  ParameterMap parameters;
  for (size_t n = 0; n < c_params->num_nodes; ++n) {
    const char * c_node_name = c_params->node_names[n];
    if (NULL == c_node_name) {
      throw InvalidParametersException("Node name at index " + std::to_string(n) + " is NULL");
    }

    /// make sure there is a leading slash on the fully qualified node name
    std::string node_name("/");
    if ('/' != c_node_name[0]) {
      node_name += c_node_name;
    } else {
      node_name = c_node_name;
    }

    if (node_fqn) {
      // Update the regular expression ["/*" -> "(/\\w+)" and "/**" -> "(/\\w+)*"]
      std::string regex = rcpputils::find_and_replace(node_name, "/*", "(/\\w+)");
      if (!std::regex_match(node_fqn, std::regex(regex))) {
        // No need to parse the items because the user just care about node_fqn
        continue;
      }

      node_name = node_fqn;
    }

    const rcl_node_params_t * const c_params_node = &(c_params->params[n]);

    std::vector<Parameter> & params_node = parameters[node_name];
    params_node.reserve(c_params_node->num_params);

    for (size_t p = 0; p < c_params_node->num_params; ++p) {
      const char * const c_param_name = c_params_node->parameter_names[p];
      if (NULL == c_param_name) {
        std::string message(
          "At node " + std::to_string(n) + " parameter " + std::to_string(p) + " name is NULL");
        throw InvalidParametersException(message);
      }
      const rcl_variant_t * const c_param_value = &(c_params_node->parameter_values[p]);
      params_node.emplace_back(c_param_name, parameter_value_from(c_param_value));
    }
  }

  return parameters;
}

ParameterValue
rclcpp::parameter_value_from(const rcl_variant_t * const c_param_value)
{
  if (NULL == c_param_value) {
    throw InvalidParameterValueException("Passed argument is NULL");
  }
  if (c_param_value->bool_value) {
    return ParameterValue(*(c_param_value->bool_value));
  } else if (c_param_value->integer_value) {
    return ParameterValue(*(c_param_value->integer_value));
  } else if (c_param_value->double_value) {
    return ParameterValue(*(c_param_value->double_value));
  } else if (c_param_value->string_value) {
    return ParameterValue(std::string(c_param_value->string_value));
  } else if (c_param_value->byte_array_value) {
    const rcl_byte_array_t * const byte_array = c_param_value->byte_array_value;
    std::vector<uint8_t> bytes;
    bytes.reserve(byte_array->size);
    for (size_t v = 0; v < byte_array->size; ++v) {
      bytes.push_back(byte_array->values[v]);
    }
    return ParameterValue(bytes);
  } else if (c_param_value->bool_array_value) {
    const rcl_bool_array_t * const bool_array = c_param_value->bool_array_value;
    std::vector<bool> bools;
    bools.reserve(bool_array->size);
    for (size_t v = 0; v < bool_array->size; ++v) {
      bools.push_back(bool_array->values[v]);
    }
    return ParameterValue(bools);
  } else if (c_param_value->integer_array_value) {
    const rcl_int64_array_t * const int_array = c_param_value->integer_array_value;
    std::vector<int64_t> integers;
    integers.reserve(int_array->size);
    for (size_t v = 0; v < int_array->size; ++v) {
      integers.push_back(int_array->values[v]);
    }
    return ParameterValue(integers);
  } else if (c_param_value->double_array_value) {
    const rcl_double_array_t * const double_array = c_param_value->double_array_value;
    std::vector<double> doubles;
    doubles.reserve(double_array->size);
    for (size_t v = 0; v < double_array->size; ++v) {
      doubles.push_back(double_array->values[v]);
    }
    return ParameterValue(doubles);
  } else if (c_param_value->string_array_value) {
    const rcutils_string_array_t * const string_array = c_param_value->string_array_value;
    std::vector<std::string> strings;
    strings.reserve(string_array->size);
    for (size_t v = 0; v < string_array->size; ++v) {
      strings.emplace_back(string_array->data[v]);
    }
    return ParameterValue(strings);
  }

  throw InvalidParameterValueException("No parameter value set");
}

ParameterMap
rclcpp::parameter_map_from_yaml_file(const std::string & yaml_filename)
{
  rcutils_allocator_t allocator = rcutils_get_default_allocator();
  rcl_params_t * rcl_parameters = rcl_yaml_node_struct_init(allocator);
  const char * path = yaml_filename.c_str();
  if (!rcl_parse_yaml_file(path, rcl_parameters)) {
    rclcpp::exceptions::throw_from_rcl_error(RCL_RET_ERROR);
  }
  return rclcpp::parameter_map_from(rcl_parameters);
}
<commit_msg>fix memory leak (#1994)<commit_after>// Copyright 2018 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <string>
#include <regex>
#include <vector>

#include "rcpputils/find_and_replace.hpp"
#include "rcpputils/scope_exit.hpp"
#include "rclcpp/parameter_map.hpp"

using rclcpp::exceptions::InvalidParametersException;
using rclcpp::exceptions::InvalidParameterValueException;
using rclcpp::ParameterMap;
using rclcpp::ParameterValue;

ParameterMap
rclcpp::parameter_map_from(const rcl_params_t * const c_params, const char * node_fqn)
{
  if (NULL == c_params) {
    throw InvalidParametersException("parameters struct is NULL");
  } else if (NULL == c_params->node_names) {
    throw InvalidParametersException("node names array is NULL");
  } else if (NULL == c_params->params) {
    throw InvalidParametersException("node params array is NULL");
  }

  // Convert c structs into a list of parameters to set
  ParameterMap parameters;
  for (size_t n = 0; n < c_params->num_nodes; ++n) {
    const char * c_node_name = c_params->node_names[n];
    if (NULL == c_node_name) {
      throw InvalidParametersException("Node name at index " + std::to_string(n) + " is NULL");
    }

    /// make sure there is a leading slash on the fully qualified node name
    std::string node_name("/");
    if ('/' != c_node_name[0]) {
      node_name += c_node_name;
    } else {
      node_name = c_node_name;
    }

    if (node_fqn) {
      // Update the regular expression ["/*" -> "(/\\w+)" and "/**" -> "(/\\w+)*"]
      std::string regex = rcpputils::find_and_replace(node_name, "/*", "(/\\w+)");
      if (!std::regex_match(node_fqn, std::regex(regex))) {
        // No need to parse the items because the user just care about node_fqn
        continue;
      }

      node_name = node_fqn;
    }

    const rcl_node_params_t * const c_params_node = &(c_params->params[n]);

    std::vector<Parameter> & params_node = parameters[node_name];
    params_node.reserve(c_params_node->num_params);

    for (size_t p = 0; p < c_params_node->num_params; ++p) {
      const char * const c_param_name = c_params_node->parameter_names[p];
      if (NULL == c_param_name) {
        std::string message(
          "At node " + std::to_string(n) + " parameter " + std::to_string(p) + " name is NULL");
        throw InvalidParametersException(message);
      }
      const rcl_variant_t * const c_param_value = &(c_params_node->parameter_values[p]);
      params_node.emplace_back(c_param_name, parameter_value_from(c_param_value));
    }
  }

  return parameters;
}

ParameterValue
rclcpp::parameter_value_from(const rcl_variant_t * const c_param_value)
{
  if (NULL == c_param_value) {
    throw InvalidParameterValueException("Passed argument is NULL");
  }
  if (c_param_value->bool_value) {
    return ParameterValue(*(c_param_value->bool_value));
  } else if (c_param_value->integer_value) {
    return ParameterValue(*(c_param_value->integer_value));
  } else if (c_param_value->double_value) {
    return ParameterValue(*(c_param_value->double_value));
  } else if (c_param_value->string_value) {
    return ParameterValue(std::string(c_param_value->string_value));
  } else if (c_param_value->byte_array_value) {
    const rcl_byte_array_t * const byte_array = c_param_value->byte_array_value;
    std::vector<uint8_t> bytes;
    bytes.reserve(byte_array->size);
    for (size_t v = 0; v < byte_array->size; ++v) {
      bytes.push_back(byte_array->values[v]);
    }
    return ParameterValue(bytes);
  } else if (c_param_value->bool_array_value) {
    const rcl_bool_array_t * const bool_array = c_param_value->bool_array_value;
    std::vector<bool> bools;
    bools.reserve(bool_array->size);
    for (size_t v = 0; v < bool_array->size; ++v) {
      bools.push_back(bool_array->values[v]);
    }
    return ParameterValue(bools);
  } else if (c_param_value->integer_array_value) {
    const rcl_int64_array_t * const int_array = c_param_value->integer_array_value;
    std::vector<int64_t> integers;
    integers.reserve(int_array->size);
    for (size_t v = 0; v < int_array->size; ++v) {
      integers.push_back(int_array->values[v]);
    }
    return ParameterValue(integers);
  } else if (c_param_value->double_array_value) {
    const rcl_double_array_t * const double_array = c_param_value->double_array_value;
    std::vector<double> doubles;
    doubles.reserve(double_array->size);
    for (size_t v = 0; v < double_array->size; ++v) {
      doubles.push_back(double_array->values[v]);
    }
    return ParameterValue(doubles);
  } else if (c_param_value->string_array_value) {
    const rcutils_string_array_t * const string_array = c_param_value->string_array_value;
    std::vector<std::string> strings;
    strings.reserve(string_array->size);
    for (size_t v = 0; v < string_array->size; ++v) {
      strings.emplace_back(string_array->data[v]);
    }
    return ParameterValue(strings);
  }

  throw InvalidParameterValueException("No parameter value set");
}

ParameterMap
rclcpp::parameter_map_from_yaml_file(const std::string & yaml_filename)
{
  rcutils_allocator_t allocator = rcutils_get_default_allocator();
  rcl_params_t * rcl_parameters = rcl_yaml_node_struct_init(allocator);
  RCPPUTILS_SCOPE_EXIT(rcl_yaml_node_struct_fini(rcl_parameters); );
  const char * path = yaml_filename.c_str();
  if (!rcl_parse_yaml_file(path, rcl_parameters)) {
    rclcpp::exceptions::throw_from_rcl_error(RCL_RET_ERROR);
  }

  return rclcpp::parameter_map_from(rcl_parameters);
}
<|endoftext|>


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

// CLASS HEADER
#include <dali/internal/system/common/singleton-service-impl.h>

// EXTERNAL INCLUDES
#include <dali/integration-api/debug.h>

// INTERNAL INCLUDES
#if defined(DEBUG_ENABLED)
#include <dali/internal/system/common/logging.h>
Debug::Filter* gSingletonServiceLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_SINGLETON_SERVICE" );

// Need to define own macro as the log function is not installed when this object is created so no logging is shown with DALI_LOG_INFO at construction and destruction
#define DALI_LOG_SINGLETON_SERVICE_DIRECT(level, message)                        \
    if(gSingletonServiceLogFilter && gSingletonServiceLogFilter->IsEnabledFor(level)) { std::string string(message); Dali::TizenPlatform::LogMessage( Debug::DebugInfo, string );  }

#define DALI_LOG_SINGLETON_SERVICE(level, format, args...) DALI_LOG_INFO(gSingletonServiceLogFilter, level, format, ## args )

#else

#define DALI_LOG_SINGLETON_SERVICE_DIRECT(level, message)
#define DALI_LOG_SINGLETON_SERVICE(level, format, args...)

#endif

namespace Dali
{

namespace Internal
{

namespace Adaptor
{

namespace
{
thread_local SingletonService * gSingletonService = 0;
} // unnamed namespace

Dali::SingletonService SingletonService::New()
{
  Dali::SingletonService singletonService( new SingletonService );
  return singletonService;
}

Dali::SingletonService SingletonService::Get()
{
  Dali::SingletonService singletonService;
  if ( gSingletonService )
  {
    singletonService = Dali::SingletonService( gSingletonService );
  }
  return singletonService;
}

void SingletonService::Register( const std::type_info& info, BaseHandle singleton )
{
  if( singleton )
  {
    DALI_LOG_SINGLETON_SERVICE( Debug::General, "Singleton Added: %s\n", info.name() );
    mSingletonContainer.push_back( SingletonPair( info.name(), singleton ) );
  }
}

void SingletonService::UnregisterAll( )
{
  mSingletonContainer.clear();
}

BaseHandle SingletonService::GetSingleton( const std::type_info& info ) const
{
  BaseHandle object;

  const SingletonContainer::const_iterator end = mSingletonContainer.end();
  for( SingletonContainer::const_iterator iter = mSingletonContainer.begin(); iter != end; ++iter )
  {
    // comparing the addresses as these are allocated statically per library
    if( ( *iter ).first == info.name() )
    {
      object = ( *iter ).second;
    }
  }

  return object;
}

SingletonService::SingletonService()
: mSingletonContainer()
{
  // Can only have one instance of SingletonService
  DALI_ASSERT_ALWAYS( !gSingletonService && "Only one instance of SingletonService is allowed");

  gSingletonService = this;

  DALI_LOG_SINGLETON_SERVICE_DIRECT( Debug::Concise, "SingletonService Created\n" );
}

SingletonService::~SingletonService()
{
  gSingletonService = 0;

  DALI_LOG_SINGLETON_SERVICE_DIRECT( Debug::Concise, "SingletonService Destroyed\n" );
}

} // namespace Adaptor

} // namespace Internal

} // namespace Dali

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

// CLASS HEADER
#include <dali/internal/system/common/singleton-service-impl.h>

// EXTERNAL INCLUDES
#include <dali/integration-api/debug.h>
#include <dali/integration-api/core.h>
#include <dali/integration-api/adaptor.h>
#include <dali/internal/adaptor/common/adaptor-impl.h>

// INTERNAL INCLUDES
#if defined(DEBUG_ENABLED)
#include <dali/internal/system/common/logging.h>
Debug::Filter* gSingletonServiceLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_SINGLETON_SERVICE" );

// Need to define own macro as the log function is not installed when this object is created so no logging is shown with DALI_LOG_INFO at construction and destruction
#define DALI_LOG_SINGLETON_SERVICE_DIRECT(level, message)                        \
    if(gSingletonServiceLogFilter && gSingletonServiceLogFilter->IsEnabledFor(level)) { std::string string(message); Dali::TizenPlatform::LogMessage( Debug::DebugInfo, string );  }

#define DALI_LOG_SINGLETON_SERVICE(level, format, args...) DALI_LOG_INFO(gSingletonServiceLogFilter, level, format, ## args )

#else

#define DALI_LOG_SINGLETON_SERVICE_DIRECT(level, message)
#define DALI_LOG_SINGLETON_SERVICE(level, format, args...)

#endif

namespace Dali
{

namespace Internal
{

namespace Adaptor
{

namespace
{
thread_local SingletonService * gSingletonService = 0;
} // unnamed namespace

Dali::SingletonService SingletonService::New()
{
  Dali::SingletonService singletonService( new SingletonService );
  return singletonService;
}

Dali::SingletonService SingletonService::Get()
{
  Dali::SingletonService singletonService;
  if ( gSingletonService )
  {
    singletonService = Dali::SingletonService( gSingletonService );
  }
  return singletonService;
}

void SingletonService::Register( const std::type_info& info, BaseHandle singleton )
{
  if( singleton )
  {
    DALI_LOG_SINGLETON_SERVICE( Debug::General, "Singleton Added: %s\n", info.name() );
    mSingletonContainer.push_back( SingletonPair( info.name(), singleton ) );

    Integration::Processor* processor = dynamic_cast<Integration::Processor*>( &singleton.GetBaseObject() );
    if( processor )
    {
      Dali::Adaptor& adaptor = Dali::Adaptor::Get();
      Dali::Internal::Adaptor::Adaptor& adaptorImpl = Adaptor::GetImplementation( adaptor );
      Integration::Core& core = adaptorImpl.GetCore();
      core.RegisterProcessor( *processor );
    }
  }
}

void SingletonService::UnregisterAll( )
{
  mSingletonContainer.clear();
}

BaseHandle SingletonService::GetSingleton( const std::type_info& info ) const
{
  BaseHandle object;

  const SingletonContainer::const_iterator end = mSingletonContainer.end();
  for( SingletonContainer::const_iterator iter = mSingletonContainer.begin(); iter != end; ++iter )
  {
    // comparing the addresses as these are allocated statically per library
    if( ( *iter ).first == info.name() )
    {
      object = ( *iter ).second;
    }
  }

  return object;
}

SingletonService::SingletonService()
: mSingletonContainer()
{
  // Can only have one instance of SingletonService
  DALI_ASSERT_ALWAYS( !gSingletonService && "Only one instance of SingletonService is allowed");

  gSingletonService = this;

  DALI_LOG_SINGLETON_SERVICE_DIRECT( Debug::Concise, "SingletonService Created\n" );
}

SingletonService::~SingletonService()
{
  gSingletonService = 0;

  DALI_LOG_SINGLETON_SERVICE_DIRECT( Debug::Concise, "SingletonService Destroyed\n" );
}

} // namespace Adaptor

} // namespace Internal

} // namespace Dali
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: SwXMLBlockListContext.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: dvo $ $Date: 2001-11-01 19:35:28 $
 *
 *  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): Martin Gallwey (gallwey@sun.com)
 *
 *
 ************************************************************************/

#pragma hdrstop

#ifndef _SW_XMLBLOCKLISTCONTEXT_HXX
#include <SwXMLBlockListContext.hxx>
#endif

#ifndef _SW_XMLBLOCKIMPORT_HXX
#include <SwXMLBlockImport.hxx>
#endif

#ifndef _SW_XMLTEXTBLOCKS_HXX
#include <SwXMLTextBlocks.hxx>
#endif

#ifndef _XMLOFF_XMLIMP_HXX
#include <xmloff/xmlimp.hxx>
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include <xmloff/xmlnmspe.hxx>
#endif
#ifndef _UNOTOOLS_CHARCLASS_HXX
#include <unotools/charclass.hxx>
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
#ifndef _SWTYPES_HXX
#include <swtypes.hxx>
#endif

using namespace ::com::sun::star::uno;
using namespace ::com::sun::star;
using namespace ::xmloff::token;
using namespace ::rtl;

SwXMLBlockListContext::SwXMLBlockListContext(
   SwXMLBlockListImport& rImport,
   sal_uInt16 nPrefix,
   const OUString& rLocalName,
   const com::sun::star::uno::Reference<
   com::sun::star::xml::sax::XAttributeList > & xAttrList ) :
    rLocalRef (rImport),
    SvXMLImportContext ( rImport, nPrefix, rLocalName )
{
    sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;
    for (sal_Int16 i=0; i < nAttrCount; i++)
    {
        const OUString& rAttrName = xAttrList->getNameByIndex( i );
        OUString aLocalName;
        sal_uInt16 nPrefix = rImport.GetNamespaceMap().GetKeyByAttrName( rAttrName, &aLocalName);
        const OUString& rAttrValue = xAttrList->getValueByIndex( i );
        if ( XML_NAMESPACE_BLOCKLIST == nPrefix )
        {
            if ( IsXMLToken ( aLocalName, XML_LIST_NAME ) )
            {
                rImport.getBlockList().SetName(rAttrValue);
                break;
            }
        }
    }
}

SwXMLBlockListContext::~SwXMLBlockListContext ( void )
{
}

SvXMLImportContext *SwXMLBlockListContext::CreateChildContext(
    sal_uInt16 nPrefix,
    const OUString& rLocalName,
    const Reference< xml::sax::XAttributeList > & xAttrList )
{
    SvXMLImportContext *pContext = 0;
    if (nPrefix == XML_NAMESPACE_BLOCKLIST &&
        IsXMLToken ( rLocalName, XML_BLOCK ) )
        pContext = new SwXMLBlockContext (rLocalRef, nPrefix, rLocalName, xAttrList);
    else
        pContext = new SvXMLImportContext( rLocalRef, nPrefix, rLocalName);
    return pContext;
}

SwXMLBlockContext::SwXMLBlockContext(
   SwXMLBlockListImport& rImport,
   sal_uInt16 nPrefix,
   const OUString& rLocalName,
   const com::sun::star::uno::Reference<
   com::sun::star::xml::sax::XAttributeList > & xAttrList ) :
    rLocalRef(rImport),
    SvXMLImportContext ( rImport, nPrefix, rLocalName )
{
    static const CharClass & rCC = GetAppCharClass();
    String aShort, aLong, aPackageName;
    BOOL bTextOnly = FALSE;

    sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;
    for (sal_Int16 i=0; i < nAttrCount; i++)
    {
        const OUString& rAttrName = xAttrList->getNameByIndex( i );
        OUString aLocalName;
        sal_uInt16 nPrefix = rImport.GetNamespaceMap().GetKeyByAttrName( rAttrName, &aLocalName);
        const OUString& rAttrValue = xAttrList->getValueByIndex( i );
        if (XML_NAMESPACE_BLOCKLIST == nPrefix)
        {
            if ( IsXMLToken ( aLocalName, XML_ABBREVIATED_NAME ) )
            {
                aShort = rCC.upper(rAttrValue);
            }
            else if ( IsXMLToken ( aLocalName, XML_NAME ) )
            {
                aLong = rAttrValue;
            }
            else if ( IsXMLToken ( aLocalName, XML_PACKAGE_NAME ) )
            {
                aPackageName = rAttrValue;
            }
            else if ( IsXMLToken ( aLocalName, XML_UNFORMATTED_TEXT ) )
            {
                if ( IsXMLToken ( rAttrValue, XML_TRUE ) )
                    bTextOnly = TRUE;
            }
        }
    }
    if (!aShort.Len() || !aLong.Len() || !aPackageName.Len())
        return;
    rImport.getBlockList().AddName( aShort, aLong, aPackageName, bTextOnly);
}

SwXMLBlockContext::~SwXMLBlockContext ( void )
{
}

SwXMLTextBlockDocumentContext::SwXMLTextBlockDocumentContext(
   SwXMLTextBlockImport& rImport,
   sal_uInt16 nPrefix,
   const OUString& rLocalName,
   const com::sun::star::uno::Reference<
   com::sun::star::xml::sax::XAttributeList > & xAttrList ) :
    rLocalRef(rImport),
    SvXMLImportContext ( rImport, nPrefix, rLocalName )
{
}

SvXMLImportContext *SwXMLTextBlockDocumentContext::CreateChildContext(
    sal_uInt16 nPrefix,
    const OUString& rLocalName,
    const Reference< xml::sax::XAttributeList > & xAttrList )
{
    SvXMLImportContext *pContext = 0;
    if (nPrefix == XML_NAMESPACE_OFFICE &&
        IsXMLToken ( rLocalName, XML_BODY ) )
        pContext = new SwXMLTextBlockBodyContext (rLocalRef, nPrefix, rLocalName, xAttrList);
    else
        pContext = new SvXMLImportContext( rLocalRef, nPrefix, rLocalName);
    return pContext;
}
SwXMLTextBlockDocumentContext::~SwXMLTextBlockDocumentContext ( void )
{
}
SwXMLTextBlockBodyContext::SwXMLTextBlockBodyContext(
   SwXMLTextBlockImport& rImport,
   sal_uInt16 nPrefix,
   const OUString& rLocalName,
   const com::sun::star::uno::Reference<
   com::sun::star::xml::sax::XAttributeList > & xAttrList ) :
    rLocalRef(rImport),
    SvXMLImportContext ( rImport, nPrefix, rLocalName )
{
}

SvXMLImportContext *SwXMLTextBlockBodyContext::CreateChildContext(
    sal_uInt16 nPrefix,
    const OUString& rLocalName,
    const Reference< xml::sax::XAttributeList > & xAttrList )
{
    SvXMLImportContext *pContext = 0;
    if (nPrefix == XML_NAMESPACE_TEXT &&
        IsXMLToken ( rLocalName, XML_P ) )
        pContext = new SwXMLTextBlockParContext (rLocalRef, nPrefix, rLocalName, xAttrList);
    else
        pContext = new SvXMLImportContext( rLocalRef, nPrefix, rLocalName);
    return pContext;
}
SwXMLTextBlockBodyContext::~SwXMLTextBlockBodyContext ( void )
{
}
SwXMLTextBlockParContext::SwXMLTextBlockParContext(
   SwXMLTextBlockImport& rImport,
   sal_uInt16 nPrefix,
   const OUString& rLocalName,
   const com::sun::star::uno::Reference<
   com::sun::star::xml::sax::XAttributeList > & xAttrList ) :
    rLocalRef(rImport),
    SvXMLImportContext ( rImport, nPrefix, rLocalName )
{
}

void SwXMLTextBlockParContext::Characters( const ::rtl::OUString& rChars )
{
    rLocalRef.m_rText.Append ( rChars.getStr());
}
SwXMLTextBlockParContext::~SwXMLTextBlockParContext ( void )
{
    if (rLocalRef.bTextOnly)
        rLocalRef.m_rText.AppendAscii( "\015" );
    else
    {
        if (rLocalRef.m_rText.GetChar ( rLocalRef.m_rText.Len()) != ' ' )
            rLocalRef.m_rText.AppendAscii( " " );
    }
}
<commit_msg>INTEGRATION: CWS sb19 (1.6.876); FILE MERGED 2004/11/04 15:45:26 os 1.6.876.1: #i36685# AutoCorrection using attributed text fixed<commit_after>/*************************************************************************
 *
 *  $RCSfile: SwXMLBlockListContext.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: rt $ $Date: 2005-01-11 12:21:24 $
 *
 *  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): Martin Gallwey (gallwey@sun.com)
 *
 *
 ************************************************************************/

#pragma hdrstop

#ifndef _SW_XMLBLOCKLISTCONTEXT_HXX
#include <SwXMLBlockListContext.hxx>
#endif

#ifndef _SW_XMLBLOCKIMPORT_HXX
#include <SwXMLBlockImport.hxx>
#endif

#ifndef _SW_XMLTEXTBLOCKS_HXX
#include <SwXMLTextBlocks.hxx>
#endif

#ifndef _XMLOFF_XMLIMP_HXX
#include <xmloff/xmlimp.hxx>
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include <xmloff/xmlnmspe.hxx>
#endif
#ifndef _UNOTOOLS_CHARCLASS_HXX
#include <unotools/charclass.hxx>
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
#ifndef _SWTYPES_HXX
#include <swtypes.hxx>
#endif

using namespace ::com::sun::star::uno;
using namespace ::com::sun::star;
using namespace ::xmloff::token;
using namespace ::rtl;

SwXMLBlockListContext::SwXMLBlockListContext(
   SwXMLBlockListImport& rImport,
   sal_uInt16 nPrefix,
   const OUString& rLocalName,
   const com::sun::star::uno::Reference<
   com::sun::star::xml::sax::XAttributeList > & xAttrList ) :
    rLocalRef (rImport),
    SvXMLImportContext ( rImport, nPrefix, rLocalName )
{
    sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;
    for (sal_Int16 i=0; i < nAttrCount; i++)
    {
        const OUString& rAttrName = xAttrList->getNameByIndex( i );
        OUString aLocalName;
        sal_uInt16 nPrefix = rImport.GetNamespaceMap().GetKeyByAttrName( rAttrName, &aLocalName);
        const OUString& rAttrValue = xAttrList->getValueByIndex( i );
        if ( XML_NAMESPACE_BLOCKLIST == nPrefix )
        {
            if ( IsXMLToken ( aLocalName, XML_LIST_NAME ) )
            {
                rImport.getBlockList().SetName(rAttrValue);
                break;
            }
        }
    }
}

SwXMLBlockListContext::~SwXMLBlockListContext ( void )
{
}

SvXMLImportContext *SwXMLBlockListContext::CreateChildContext(
    sal_uInt16 nPrefix,
    const OUString& rLocalName,
    const Reference< xml::sax::XAttributeList > & xAttrList )
{
    SvXMLImportContext *pContext = 0;
    if (nPrefix == XML_NAMESPACE_BLOCKLIST &&
        IsXMLToken ( rLocalName, XML_BLOCK ) )
        pContext = new SwXMLBlockContext (rLocalRef, nPrefix, rLocalName, xAttrList);
    else
        pContext = new SvXMLImportContext( rLocalRef, nPrefix, rLocalName);
    return pContext;
}

SwXMLBlockContext::SwXMLBlockContext(
   SwXMLBlockListImport& rImport,
   sal_uInt16 nPrefix,
   const OUString& rLocalName,
   const com::sun::star::uno::Reference<
   com::sun::star::xml::sax::XAttributeList > & xAttrList ) :
    rLocalRef(rImport),
    SvXMLImportContext ( rImport, nPrefix, rLocalName )
{
    static const CharClass & rCC = GetAppCharClass();
    String aShort, aLong, aPackageName;
    BOOL bTextOnly = FALSE;

    sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;
    for (sal_Int16 i=0; i < nAttrCount; i++)
    {
        const OUString& rAttrName = xAttrList->getNameByIndex( i );
        OUString aLocalName;
        sal_uInt16 nPrefix = rImport.GetNamespaceMap().GetKeyByAttrName( rAttrName, &aLocalName);
        const OUString& rAttrValue = xAttrList->getValueByIndex( i );
        if (XML_NAMESPACE_BLOCKLIST == nPrefix)
        {
            if ( IsXMLToken ( aLocalName, XML_ABBREVIATED_NAME ) )
            {
                aShort = rCC.upper(rAttrValue);
            }
            else if ( IsXMLToken ( aLocalName, XML_NAME ) )
            {
                aLong = rAttrValue;
            }
            else if ( IsXMLToken ( aLocalName, XML_PACKAGE_NAME ) )
            {
                aPackageName = rAttrValue;
            }
            else if ( IsXMLToken ( aLocalName, XML_UNFORMATTED_TEXT ) )
            {
                if ( IsXMLToken ( rAttrValue, XML_TRUE ) )
                    bTextOnly = TRUE;
            }
        }
    }
    if (!aShort.Len() || !aLong.Len() || !aPackageName.Len())
        return;
    rImport.getBlockList().AddName( aShort, aLong, aPackageName, bTextOnly);
}

SwXMLBlockContext::~SwXMLBlockContext ( void )
{
}

SwXMLTextBlockDocumentContext::SwXMLTextBlockDocumentContext(
   SwXMLTextBlockImport& rImport,
   sal_uInt16 nPrefix,
   const OUString& rLocalName,
   const com::sun::star::uno::Reference<
   com::sun::star::xml::sax::XAttributeList > & xAttrList ) :
    rLocalRef(rImport),
    SvXMLImportContext ( rImport, nPrefix, rLocalName )
{
}

SvXMLImportContext *SwXMLTextBlockDocumentContext::CreateChildContext(
    sal_uInt16 nPrefix,
    const OUString& rLocalName,
    const Reference< xml::sax::XAttributeList > & xAttrList )
{
    SvXMLImportContext *pContext = 0;
    if (nPrefix == XML_NAMESPACE_OFFICE &&
        IsXMLToken ( rLocalName, XML_BODY ) )
        pContext = new SwXMLTextBlockBodyContext (rLocalRef, nPrefix, rLocalName, xAttrList);
    else
        pContext = new SvXMLImportContext( rLocalRef, nPrefix, rLocalName);
    return pContext;
}
SwXMLTextBlockDocumentContext::~SwXMLTextBlockDocumentContext ( void )
{
}

SwXMLTextBlockTextContext::SwXMLTextBlockTextContext(
   SwXMLTextBlockImport& rImport,
   sal_uInt16 nPrefix,
   const OUString& rLocalName,
   const com::sun::star::uno::Reference<
   com::sun::star::xml::sax::XAttributeList > & xAttrList ) :
    rLocalRef(rImport),
    SvXMLImportContext ( rImport, nPrefix, rLocalName )
{
}

SvXMLImportContext *SwXMLTextBlockTextContext::CreateChildContext(
    sal_uInt16 nPrefix,
    const OUString& rLocalName,
    const Reference< xml::sax::XAttributeList > & xAttrList )
{
    SvXMLImportContext *pContext = 0;
    if (nPrefix == XML_NAMESPACE_TEXT &&
        IsXMLToken ( rLocalName, XML_P ) )
        pContext = new SwXMLTextBlockParContext (rLocalRef, nPrefix, rLocalName, xAttrList);
    else
        pContext = new SvXMLImportContext( rLocalRef, nPrefix, rLocalName);
    return pContext;
}
SwXMLTextBlockTextContext::~SwXMLTextBlockTextContext ( void )
{
}

SwXMLTextBlockBodyContext::SwXMLTextBlockBodyContext(
   SwXMLTextBlockImport& rImport,
   sal_uInt16 nPrefix,
   const OUString& rLocalName,
   const com::sun::star::uno::Reference<
   com::sun::star::xml::sax::XAttributeList > & xAttrList ) :
    rLocalRef(rImport),
    SvXMLImportContext ( rImport, nPrefix, rLocalName )
{
}

SvXMLImportContext *SwXMLTextBlockBodyContext::CreateChildContext(
    sal_uInt16 nPrefix,
    const OUString& rLocalName,
    const Reference< xml::sax::XAttributeList > & xAttrList )
{
    SvXMLImportContext *pContext = 0;
    if (nPrefix == XML_NAMESPACE_OFFICE &&
        IsXMLToken ( rLocalName, XML_TEXT ) )
        pContext = new SwXMLTextBlockTextContext (rLocalRef, nPrefix, rLocalName, xAttrList);
    else if (nPrefix == XML_NAMESPACE_TEXT &&
        IsXMLToken ( rLocalName, XML_P ) )
        pContext = new SwXMLTextBlockParContext (rLocalRef, nPrefix, rLocalName, xAttrList);
    else
        pContext = new SvXMLImportContext( rLocalRef, nPrefix, rLocalName);
    return pContext;
}
SwXMLTextBlockBodyContext::~SwXMLTextBlockBodyContext ( void )
{
}
SwXMLTextBlockParContext::SwXMLTextBlockParContext(
   SwXMLTextBlockImport& rImport,
   sal_uInt16 nPrefix,
   const OUString& rLocalName,
   const com::sun::star::uno::Reference<
   com::sun::star::xml::sax::XAttributeList > & xAttrList ) :
    rLocalRef(rImport),
    SvXMLImportContext ( rImport, nPrefix, rLocalName )
{
}

void SwXMLTextBlockParContext::Characters( const ::rtl::OUString& rChars )
{
    rLocalRef.m_rText.Append ( rChars.getStr());
}
SwXMLTextBlockParContext::~SwXMLTextBlockParContext ( void )
{
    if (rLocalRef.bTextOnly)
        rLocalRef.m_rText.AppendAscii( "\015" );
    else
    {
        if (rLocalRef.m_rText.GetChar ( rLocalRef.m_rText.Len()) != ' ' )
            rLocalRef.m_rText.AppendAscii( " " );
    }
}
<|endoftext|>


<commit_before>#include <boost/asio/async_result.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/asio/spawn.hpp>
#include <boost/asio/use_future.hpp>
#include <silicium/boost_threading.hpp>
#include <silicium/config.hpp>

namespace Si
{
	namespace asio
	{
		template <class T, class ThreadingAPI>
		struct background_task
		{
			template <class F, class CompletionToken>
			auto async_call(F &&function, CompletionToken &&token)
			{
				typedef typename boost::asio::handler_type<CompletionToken, void(T)>::type handler_type;
				handler_type handler(std::forward<CompletionToken>(token));
				boost::asio::async_result<handler_type> result(handler);
				m_handle = ThreadingAPI::launch_async([
					SILICIUM_MOVE_CAPTURE(function, std::forward<F>(function)),
					SILICIUM_MOVE_CAPTURE(handler, std::move(handler))
				]() mutable
				{
					std::move(handler)(std::forward<F>(function)());
				});
				return result.get();
			}

			~background_task()
			{
				m_handle.get();
			}

		private:

			typename ThreadingAPI::template future<void>::type m_handle;
		};
	}
}

BOOST_AUTO_TEST_CASE(background_task_async_call)
{
	Si::asio::background_task<int, Si::boost_threading> task;
	std::future<int> f = task.async_call(
		[]
		{
			return 4;
		},
		boost::asio::use_future
	);
	BOOST_CHECK_EQUAL(4, f.get());
}

BOOST_AUTO_TEST_CASE(background_task_async_call_into_coroutine)
{
	boost::thread::id const test_thread = boost::this_thread::get_id();
	boost::thread::id background_thread;
	{
		Si::asio::background_task<Si::nothing, Si::boost_threading> task;
		auto handler = [](){};
		boost::asio::spawn(
			std::move(handler),
			[&task, &background_thread, test_thread](boost::asio::basic_yield_context<decltype(handler)> yield)
		{
			BOOST_CHECK_EQUAL(test_thread, boost::this_thread::get_id());
			task.async_call(
				[]()
				{
					return Si::nothing();
				}, yield);
			//the coroutine is running the background thread now
			background_thread = boost::this_thread::get_id();
			BOOST_CHECK_NE(test_thread, background_thread);
		});
	}
	BOOST_CHECK_NE(background_thread, boost::thread::id());
	BOOST_CHECK_NE(background_thread, test_thread);
}
<commit_msg>make background_task movable<commit_after>#include <boost/asio/async_result.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/asio/spawn.hpp>
#include <boost/asio/use_future.hpp>
#include <silicium/boost_threading.hpp>
#include <silicium/config.hpp>

namespace Si
{
	namespace asio
	{
		template <class T, class ThreadingAPI>
		struct background_task
		{
			background_task()
			{
			}

			background_task(background_task &&other) BOOST_NOEXCEPT
				: m_handle(other.m_handle)
			{
			}

			background_task &operator = (background_task &&other) BOOST_NOEXCEPT
			{
				m_handle = std::move(other.m_handle);
				return *this;
			}

			template <class F, class CompletionToken>
			auto async_call(F &&function, CompletionToken &&token)
			{
				typedef typename boost::asio::handler_type<CompletionToken, void(T)>::type handler_type;
				handler_type handler(std::forward<CompletionToken>(token));
				boost::asio::async_result<handler_type> result(handler);
				m_handle = ThreadingAPI::launch_async([
					SILICIUM_MOVE_CAPTURE(function, std::forward<F>(function)),
					SILICIUM_MOVE_CAPTURE(handler, std::move(handler))
				]() mutable
				{
					std::move(handler)(std::forward<F>(function)());
				});
				return result.get();
			}

			~background_task()
			{
				m_handle.get();
			}

		private:

			typename ThreadingAPI::template future<void>::type m_handle;

			SILICIUM_DISABLE_COPY(background_task)
		};
	}
}

BOOST_AUTO_TEST_CASE(background_task_async_call)
{
	Si::asio::background_task<int, Si::boost_threading> task;
	std::future<int> f = task.async_call(
		[]
		{
			return 4;
		},
		boost::asio::use_future
	);
	BOOST_CHECK_EQUAL(4, f.get());
}

BOOST_AUTO_TEST_CASE(background_task_async_call_into_coroutine)
{
	boost::thread::id const test_thread = boost::this_thread::get_id();
	boost::thread::id background_thread;
	{
		Si::asio::background_task<Si::nothing, Si::boost_threading> task;
		auto handler = [](){};
		boost::asio::spawn(
			std::move(handler),
			[&task, &background_thread, test_thread](boost::asio::basic_yield_context<decltype(handler)> yield)
		{
			BOOST_CHECK_EQUAL(test_thread, boost::this_thread::get_id());
			task.async_call(
				[]()
				{
					return Si::nothing();
				}, yield);
			//the coroutine is running the background thread now
			background_thread = boost::this_thread::get_id();
			BOOST_CHECK_NE(test_thread, background_thread);
		});
	}
	BOOST_CHECK_NE(background_thread, boost::thread::id());
	BOOST_CHECK_NE(background_thread, test_thread);
}
<|endoftext|>


<commit_before># include <iostream> // Header
# define CATCH_CONFIG_RUNNER
using namespace std; // Namensraum finden
# include <catch.hpp>

int number, i;
bool prime;

bool is_prime(int number)
{
    int i = 0;
    for(int i=2; i < number; i++)
    {
       if(number%i != 0)
          {prime = true;}
       else
          {prime = false;}
    }
}

TEST_CASE ("is_prime", "[is_prime]")
{
REQUIRE(is_prime (2) == false);
REQUIRE(is_prime (6) == false);
REQUIRE(is_prime (4) == false);
REQUIRE(is_prime (7) == true);
REQUIRE(is_prime (11) == true);
REQUIRE(is_prime (13) == true);
REQUIRE(is_prime (8) == false);
REQUIRE(is_prime (60) == false);
}

int main(int argc, char* argv[])
{
  return Catch::Session().run(argc, argv);
}<commit_msg>is_prime Korrektur<commit_after># include <iostream> // Header
# define CATCH_CONFIG_RUNNER
using namespace std; // Namensraum finden
# include <catch.hpp>

int number, i;
bool prime;

bool is_prime(int number)
{
    int i = 0;
    for(int i=2; i < number; i++)
    {
       if(number%i == 0)
          {prime = false;}
       else
          {prime = true;}
    return prime;
    }
}

TEST_CASE ("is_prime", "[is_prime]")
{
REQUIRE(is_prime (2) == false);
REQUIRE(is_prime (6) == false);
REQUIRE(is_prime (4) == false);
REQUIRE(is_prime (7) == true);
REQUIRE(is_prime (11) == true);
REQUIRE(is_prime (13) == true);
REQUIRE(is_prime (8) == false);
REQUIRE(is_prime (60) == false);
}

int main(int argc, char* argv[])
{
  return Catch::Session().run(argc, argv);
}<|endoftext|>


<commit_before>#ifndef UTILITY_HPP_
#define UTILITY_HPP_
#include "FAST/ExecutionDevice.hpp"
#include "FAST/Data/DataTypes.hpp"
#include <algorithm>
#include <functional>
#include <cctype>
#include <locale>

// This file contains a set of utility functions

// Undefine windows crap
#undef min
#undef max

namespace fast {

FAST_EXPORT double log2(double n);
FAST_EXPORT double round(double n);
FAST_EXPORT double round(double n, int decimals);

/**
 * Does simply x^2 = x*x
 * @tparam T
 * @param x a numeric value
 * @return x*x
 */
template <class T>
T square(T x) {
    return x*x;
}

template <typename ...Args>
std::string format(std::string format, Args && ... args) {
    auto size = std::snprintf(nullptr, 0, format.c_str(), std::forward<Args>(args)...);
    std::string output(size + 1, '\0');
    std::sprintf(&output[0], format.c_str(), std::forward<Args>(args)...);
    return output;
}

template<class T>
T min(T a, T b) {
    return a < b ? a : b;
}

template<class T>
T max(T a, T b) {
    return a > b ? a : b;
}

template<class T>
T sign(T value) {
    if(value > 0) {
        return 1;
    } else if (value < 0) {
        return -1;
    } else {
        return 0;
    }
}

FAST_EXPORT unsigned int getPowerOfTwoSize(unsigned int size);
FAST_EXPORT void* allocateDataArray(unsigned int voxels, DataType type, unsigned int nrOfComponents);
template <class T>
float getSumFromOpenCLImageResult(void* voidData, unsigned int size, unsigned int nrOfComponents) {
    T* data = (T*)voidData;
    float sum = 0.0f;
    for(unsigned int i = 0; i < size*nrOfComponents; i += nrOfComponents) {
        sum += data[i];
    }
    return sum;
}

FAST_EXPORT void getMaxAndMinFromOpenCLImage(OpenCLDevice::pointer device, cl::Image2D image, DataType type, float* min, float* max);
FAST_EXPORT void getMaxAndMinFromOpenCLImage(OpenCLDevice::pointer device, cl::Image3D image, DataType type, float* min, float* max);
FAST_EXPORT void getMaxAndMinFromOpenCLBuffer(OpenCLDevice::pointer device, cl::Buffer buffer, unsigned int size, DataType type, float* min, float* max);
FAST_EXPORT void getIntensitySumFromOpenCLImage(OpenCLDevice::pointer device, cl::Image2D image, DataType type, float* sum);

template <class T>
void getMaxAndMinFromData(void* voidData, unsigned int nrOfElements, float* min, float* max) {
    T* data = (T*)voidData;

    *min = std::numeric_limits<float>::max();
    *max = std::numeric_limits<float>::min();
    for(unsigned int i = 0; i < nrOfElements; i++) {
        if((float)data[i] < *min) {
            *min = (float)data[i];
        }
        if((float)data[i] > *max) {
            *max = (float)data[i];
        }
    }
}

template <class T>
float getSumFromData(void* voidData, unsigned int nrOfElements) {
    T* data = (T*)voidData;

    float sum = 0.0f;
    for(unsigned int i = 0; i < nrOfElements; i++) {
        sum += (float)data[i];
    }
    return sum;
}

FAST_EXPORT cl::size_t<3> createRegion(unsigned int x, unsigned int y, unsigned int z);
FAST_EXPORT cl::size_t<3> createRegion(Vector3ui size);
FAST_EXPORT cl::size_t<3> createOrigoRegion();

FAST_EXPORT std::string getCLErrorString(cl_int err);

/**
 * Function for splitting a string
 * @param input string
 * @param delimiter string
 * @return vector of strings
 */
FAST_EXPORT std::vector<std::string> split(const std::string input, const std::string& delimiter = " ");

// trim from start (in place)
static inline void ltrim(std::string &s) {
    s.erase(s.begin(), std::find_if(s.begin(), s.end(),
                                    std::not1(std::ptr_fun<int, int>(std::isspace))));
}

// trim from end (in place)
static inline void rtrim(std::string &s) {
    s.erase(std::find_if(s.rbegin(), s.rend(),
                         std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
}

// trim from both ends (in place)
static inline void trim(std::string &s) {
    ltrim(s);
    rtrim(s);
}

/*
 * Replace all occurences of from to to in str
 */
FAST_EXPORT std::string replace(std::string str, std::string find, std::string replacement);

template <class T>
static inline void hash_combine(std::size_t& seed, const T& v)
{
    std::hash<T> hasher;
    seed ^= hasher(v) + 0x9e3779b9 + (seed<<6) + (seed>>2);
}

FAST_EXPORT Matrix4f loadPerspectiveMatrix(float fovy, float aspect, float zNear, float zFar);

FAST_EXPORT Matrix4f loadOrthographicMatrix(float left, float right, float bottom, float top, float zNear, float zFar);

/**
 * Creates a directory at the given path.
 * Throws exception if it fails
 */
FAST_EXPORT void createDirectory(std::string path);

/**
 * Creates all directories in the given path.
 * Throws exception if it fails
 */
FAST_EXPORT void createDirectories(std::string path);

/**
 * Check if file exists
 * @param filename
 * @return
 */
FAST_EXPORT bool fileExists(std::string filename);

/**
 * Returns a list of all files in a directory
 * @param path
 * @param getFiles Set to true to find files in directory
 * @param getDirectories Set to true to find subdirectories
 * @return list of files or subdirectories
 */
FAST_EXPORT std::vector<std::string> getDirectoryList(std::string path, bool getFiles = true, bool getDirectories = false);

/**
 * Returns the dir name of the given path. Example: getDirName("/home/user/something/file.txt")
 * returns home/user/something/.
 *
 * @param path
 * @return
 */
FAST_EXPORT std::string getDirName(std::string path);

/**
 * Returns a string of the current date
 * @param format see http://en.cppreference.com/w/cpp/chrono/c/strftime
 * @return
 */
FAST_EXPORT std::string currentDateTime(std::string format = "%Y-%m-%d-%H%M%S");

/**
 * Removes trailing /
 * @param path
 * @return
 */
FAST_EXPORT std::string join(std::string path);

/**
 * Get modified date of a file as a string
 * @param filename
 * @return
 */
FAST_EXPORT std::string getModifiedDate(std::string filename);

/**
 * Join multiple paths.
 *
 * @tparam T
 * @param path1
 * @param args
 * @return
 */
template<typename ...T>
std::string join(const std::string& path1, T... args) {
    return path1 + "/" + join(args...);
}

/**
 * Check if path is a file.
 * @param path
 * @return
 */
FAST_EXPORT bool isFile(const std::string& path);

/**
 * Check if path is a directory.
 * @param path
 * @return
 */
FAST_EXPORT bool isDir(const std::string& path);

/**
 * Same as make_unique(std::size_t size), except this version will not
 * value initialize the dynamic array. This is useful for large arrays.
 * @tparam T
 * @param size
 * @return
 */
template <class T>
std::unique_ptr<T> make_uninitialized_unique(std::size_t size) {
    return std::unique_ptr<T>(new typename std::remove_extent<T>::type[size]);
}

} // end namespace fast

#endif /* UTILITY_HPP_ */
<commit_msg>removed std functions deprecated in C++17<commit_after>#ifndef UTILITY_HPP_
#define UTILITY_HPP_
#include "FAST/ExecutionDevice.hpp"
#include "FAST/Data/DataTypes.hpp"
#include <algorithm>
#include <functional>
#include <cctype>
#include <locale>

// This file contains a set of utility functions

// Undefine windows crap
#undef min
#undef max

namespace fast {

FAST_EXPORT double log2(double n);
FAST_EXPORT double round(double n);
FAST_EXPORT double round(double n, int decimals);

/**
 * Does simply x^2 = x*x
 * @tparam T
 * @param x a numeric value
 * @return x*x
 */
template <class T>
T square(T x) {
    return x*x;
}

template <typename ...Args>
std::string format(std::string format, Args && ... args) {
    auto size = std::snprintf(nullptr, 0, format.c_str(), std::forward<Args>(args)...);
    std::string output(size + 1, '\0');
    std::sprintf(&output[0], format.c_str(), std::forward<Args>(args)...);
    return output;
}

template<class T>
T min(T a, T b) {
    return a < b ? a : b;
}

template<class T>
T max(T a, T b) {
    return a > b ? a : b;
}

template<class T>
T sign(T value) {
    if(value > 0) {
        return 1;
    } else if (value < 0) {
        return -1;
    } else {
        return 0;
    }
}

FAST_EXPORT unsigned int getPowerOfTwoSize(unsigned int size);
FAST_EXPORT void* allocateDataArray(unsigned int voxels, DataType type, unsigned int nrOfComponents);
template <class T>
float getSumFromOpenCLImageResult(void* voidData, unsigned int size, unsigned int nrOfComponents) {
    T* data = (T*)voidData;
    float sum = 0.0f;
    for(unsigned int i = 0; i < size*nrOfComponents; i += nrOfComponents) {
        sum += data[i];
    }
    return sum;
}

FAST_EXPORT void getMaxAndMinFromOpenCLImage(OpenCLDevice::pointer device, cl::Image2D image, DataType type, float* min, float* max);
FAST_EXPORT void getMaxAndMinFromOpenCLImage(OpenCLDevice::pointer device, cl::Image3D image, DataType type, float* min, float* max);
FAST_EXPORT void getMaxAndMinFromOpenCLBuffer(OpenCLDevice::pointer device, cl::Buffer buffer, unsigned int size, DataType type, float* min, float* max);
FAST_EXPORT void getIntensitySumFromOpenCLImage(OpenCLDevice::pointer device, cl::Image2D image, DataType type, float* sum);

template <class T>
void getMaxAndMinFromData(void* voidData, unsigned int nrOfElements, float* min, float* max) {
    T* data = (T*)voidData;

    *min = std::numeric_limits<float>::max();
    *max = std::numeric_limits<float>::min();
    for(unsigned int i = 0; i < nrOfElements; i++) {
        if((float)data[i] < *min) {
            *min = (float)data[i];
        }
        if((float)data[i] > *max) {
            *max = (float)data[i];
        }
    }
}

template <class T>
float getSumFromData(void* voidData, unsigned int nrOfElements) {
    T* data = (T*)voidData;

    float sum = 0.0f;
    for(unsigned int i = 0; i < nrOfElements; i++) {
        sum += (float)data[i];
    }
    return sum;
}

FAST_EXPORT cl::size_t<3> createRegion(unsigned int x, unsigned int y, unsigned int z);
FAST_EXPORT cl::size_t<3> createRegion(Vector3ui size);
FAST_EXPORT cl::size_t<3> createOrigoRegion();

FAST_EXPORT std::string getCLErrorString(cl_int err);

/**
 * Function for splitting a string
 * @param input string
 * @param delimiter string
 * @return vector of strings
 */
FAST_EXPORT std::vector<std::string> split(const std::string input, const std::string& delimiter = " ");

// trim from start (in place)
static inline void ltrim(std::string &s) {
    s.erase(s.begin(), std::find_if(s.begin(), s.end(),
        [](unsigned char c) {return !std::isspace(c); }));
}

// trim from end (in place)
static inline void rtrim(std::string &s) {
    s.erase(std::find_if(s.rbegin(), s.rend(),
        [](unsigned char c) {return !std::isspace(c); }).base(), s.end());
}

// trim from both ends (in place)
static inline void trim(std::string &s) {
    ltrim(s);
    rtrim(s);
}

/*
 * Replace all occurences of from to to in str
 */
FAST_EXPORT std::string replace(std::string str, std::string find, std::string replacement);

template <class T>
static inline void hash_combine(std::size_t& seed, const T& v)
{
    std::hash<T> hasher;
    seed ^= hasher(v) + 0x9e3779b9 + (seed<<6) + (seed>>2);
}

FAST_EXPORT Matrix4f loadPerspectiveMatrix(float fovy, float aspect, float zNear, float zFar);

FAST_EXPORT Matrix4f loadOrthographicMatrix(float left, float right, float bottom, float top, float zNear, float zFar);

/**
 * Creates a directory at the given path.
 * Throws exception if it fails
 */
FAST_EXPORT void createDirectory(std::string path);

/**
 * Creates all directories in the given path.
 * Throws exception if it fails
 */
FAST_EXPORT void createDirectories(std::string path);

/**
 * Check if file exists
 * @param filename
 * @return
 */
FAST_EXPORT bool fileExists(std::string filename);

/**
 * Returns a list of all files in a directory
 * @param path
 * @param getFiles Set to true to find files in directory
 * @param getDirectories Set to true to find subdirectories
 * @return list of files or subdirectories
 */
FAST_EXPORT std::vector<std::string> getDirectoryList(std::string path, bool getFiles = true, bool getDirectories = false);

/**
 * Returns the dir name of the given path. Example: getDirName("/home/user/something/file.txt")
 * returns home/user/something/.
 *
 * @param path
 * @return
 */
FAST_EXPORT std::string getDirName(std::string path);

/**
 * Returns a string of the current date
 * @param format see http://en.cppreference.com/w/cpp/chrono/c/strftime
 * @return
 */
FAST_EXPORT std::string currentDateTime(std::string format = "%Y-%m-%d-%H%M%S");

/**
 * Removes trailing /
 * @param path
 * @return
 */
FAST_EXPORT std::string join(std::string path);

/**
 * Get modified date of a file as a string
 * @param filename
 * @return
 */
FAST_EXPORT std::string getModifiedDate(std::string filename);

/**
 * Join multiple paths.
 *
 * @tparam T
 * @param path1
 * @param args
 * @return
 */
template<typename ...T>
std::string join(const std::string& path1, T... args) {
    return path1 + "/" + join(args...);
}

/**
 * Check if path is a file.
 * @param path
 * @return
 */
FAST_EXPORT bool isFile(const std::string& path);

/**
 * Check if path is a directory.
 * @param path
 * @return
 */
FAST_EXPORT bool isDir(const std::string& path);

/**
 * Same as make_unique(std::size_t size), except this version will not
 * value initialize the dynamic array. This is useful for large arrays.
 * @tparam T
 * @param size
 * @return
 */
template <class T>
std::unique_ptr<T> make_uninitialized_unique(std::size_t size) {
    return std::unique_ptr<T>(new typename std::remove_extent<T>::type[size]);
}

} // end namespace fast

#endif /* UTILITY_HPP_ */
<|endoftext|>


<commit_before>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**
 * CONDOR Copyright Notice
 *
 * See LICENSE.TXT for additional notices and disclaimers.
 *
 * Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department,
 * University of Wisconsin-Madison, Madison, WI.  All Rights Reserved.
 * No use of the CONDOR Software Program Source Code is authorized
 * without the express consent of the CONDOR Team.  For more information
 * contact: CONDOR Team, Attention: Professor Miron Livny,
 * 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685,
 * (608) 262-0856 or miron@cs.wisc.edu.
 *
 * U.S. Government Rights Restrictions: Use, duplication, or disclosure
 * by the U.S. Government is subject to restrictions as set forth in
 * subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer
 * Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and
 * (2) of Commercial Computer Software-Restricted Rights at 48 CFR
 * 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron
 * Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison,
 * WI 53706-1685, (608) 262-0856 or miron@cs.wisc.edu.
****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/
#include "condor_common.h"
#include "condor_state.h"

static char *_FileName_ = __FILE__;

static char* condor_states [] = { "Owner", "Unclaimed", "Matched",
								  "Claimed", "Preempting" };

static char* condor_activities [] = { "Idle", "Busy", "Vacating",
									  "Suspended", "Benchmarking",
									  "Killing" };

State
string_to_state(char* state_string)
{
	int i;
	for( i=0; i<_state_threshold_; i++ ) {
		if( !strcmp(condor_states[i], state_string) ) {
			return (State)i;
		}
	}
	return _error_state_;
}

char*
state_to_string( State state )
{
	if( state < _state_threshold_ ) {
		return condor_states[state];
	} else {
		return "Unknown";
	}
}

Activity
string_to_activity( char* act_string )
{
	int i;
	for( i=0; i<_act_threshold_; i++ ) {
		if( !strcmp(condor_activities[i], act_string) ) {
			return (Activity)i;
		}
	}
	return _error_act_;
}

char*
activity_to_string( Activity act )
{
	if( act < _act_threshold_ ) {
		return condor_activities[act];
	} else {
		return "Unknown";
	}
}

<commit_msg>+ Added strings for "Delete", "Shutdown", and "None" states. + Removed _FileName_ since it's not needed.<commit_after>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**
 * CONDOR Copyright Notice
 *
 * See LICENSE.TXT for additional notices and disclaimers.
 *
 * Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department,
 * University of Wisconsin-Madison, Madison, WI.  All Rights Reserved.
 * No use of the CONDOR Software Program Source Code is authorized
 * without the express consent of the CONDOR Team.  For more information
 * contact: CONDOR Team, Attention: Professor Miron Livny,
 * 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685,
 * (608) 262-0856 or miron@cs.wisc.edu.
 *
 * U.S. Government Rights Restrictions: Use, duplication, or disclosure
 * by the U.S. Government is subject to restrictions as set forth in
 * subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer
 * Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and
 * (2) of Commercial Computer Software-Restricted Rights at 48 CFR
 * 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron
 * Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison,
 * WI 53706-1685, (608) 262-0856 or miron@cs.wisc.edu.
****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/
#include "condor_common.h"
#include "condor_state.h"

static char* condor_states [] =
{ "None", "Owner", "Unclaimed", "Matched",  "Claimed", "Preempting",
  "Shutdown", "Delete" };

static char* condor_activities [] =
{ "None", "Idle", "Busy", "Vacating", "Suspended", "Benchmarking",
  "Killing" };

State
string_to_state(char* state_string)
{
	int i;
	for( i=0; i<_state_threshold_; i++ ) {
		if( !strcmp(condor_states[i], state_string) ) {
			return (State)i;
		}
	}
	return _error_state_;
}

char*
state_to_string( State state )
{
	if( state < _state_threshold_ ) {
		return condor_states[state];
	} else {
		return "Unknown";
	}
}

Activity
string_to_activity( char* act_string )
{
	int i;
	for( i=0; i<_act_threshold_; i++ ) {
		if( !strcmp(condor_activities[i], act_string) ) {
			return (Activity)i;
		}
	}
	return _error_act_;
}

char*
activity_to_string( Activity act )
{
	if( act < _act_threshold_ ) {
		return condor_activities[act];
	} else {
		return "Unknown";
	}
}

<|endoftext|>