<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: invalidatetree.cxx,v $
 *
 *  $Revision: 1.20 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 04:25:09 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include "cachecontroller.hxx"

#ifndef CONFIGMGR_CHANGE_HXX
#include "change.hxx"
#endif
#ifndef _CONFIGMGR_TREE_VALUENODE_HXX
#include "valuenode.hxx"
#endif

#ifndef CONFIGMGR_UPDATEHELPER_HXX
#include "updatehelper.hxx"
#endif
#ifndef _CONFIGMGR_TREEACTIONS_HXX_
#include "treeactions.hxx"
#endif

#ifndef CONFIGMGR_TREEACCESSOR_HXX
#include "treeaccessor.hxx"
#endif
#ifndef CONFIGMGR_UPDATEACCESSOR_HXX
#include "updateaccessor.hxx"
#endif

#ifndef _CONFIGMGR_TRACER_HXX_
#include "tracer.hxx"
#endif

#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_NOSUCHELEMENTEXCEPTION_HPP_
#include <com/sun/star/container/NoSuchElementException.hpp>
#endif

#ifndef _VOS_THREAD_HXX_
#include <vos/thread.hxx>
#endif

#ifndef INCLUDED_ALGORITHM
#include <algorithm>
#define INCLUDED_ALGORITHM
#endif

namespace configmgr
{

    using namespace com::sun::star::uno;
    using namespace configuration;
    namespace container = com::sun::star::container;
// -----------------------------------------------------------------------------
// ------------------------------- invalidateTree -------------------------------
// -----------------------------------------------------------------------------

namespace backend
{
// -----------------------------------------------------------------------------
std::auto_ptr<SubtreeChange> createDiffs(data::NodeAccessRef const& _aCachedNode,
                                            ISubtree const * _pLoadedSubtree,
                                            AbsolutePath const& _aAbsoluteSubtreePath)
{
    OSL_PRECOND(_aCachedNode.isValid(), "Need an existing node to create a diff");
    OSL_PRECOND(_pLoadedSubtree != 0, "Need a result node to create a diff");
    // Create a TreeChangeList with the right name, parentname and ConfigurationProperties
    std::auto_ptr<SubtreeChange> aNewChange(new SubtreeChange(_aAbsoluteSubtreePath.getLocalName().getName().toString(),
                                                                node::Attributes()) );

    if (!createUpdateFromDifference(*aNewChange, _aCachedNode, *_pLoadedSubtree))
        aNewChange.reset();

    return aNewChange;
}
// -----------------------------------------------------------------------------
#if 0
std::auto_ptr<ISubtree> TreeManager::loadNodeFromSession( AbsolutePath const& _aAbsoluteSubtreePath,
                                                     const vos::ORef < OOptions >& _xOptions,
                                                     sal_Int16 _nMinLevels)  CFG_UNO_THROW_ALL()
{
    TreeInfo* pInfo = this->requestTreeInfo(_xOptions,true /*create TreeInfo*/);

    CFG_TRACE_INFO_NI("cache manager: cache miss. going to load the node");
    rtl::Reference< OTreeLoader > xLoader = pInfo->getNewLoaderWithoutPending(_aAbsoluteSubtreePath, _nMinLevels, _xOptions, m_xBackend.get());

    OSL_ENSURE(xLoader.is(), "Did not receive a loader for retrieving the node");
    CFG_TRACE_INFO_NI("cache manager: cache miss. going to load the node");
    if (!xLoader.is())
        throw container::NoSuchElementException((::rtl::OUString::createFromAscii("Error while retrieving the node")), NULL);

    // now block for reading
    std::auto_ptr<ISubtree> pResponse;
    try
    {
        pResponse = xLoader->waitToResponse();
    }
    catch (uno::Exception& e)
    {
        pInfo->releaseLoader(xLoader);
        throw;
    }

    pInfo->releaseLoader(xLoader);

    return pResponse;
}
#endif
// -----------------------------------------------------------------------------

class OInvalidateTreeThread: public vos::OThread
{
    typedef backend::ICachedDataProvider CacheManager;
    typedef rtl::Reference< CacheManager > CacheManagerRef;
    CacheManagerRef     m_rTreeManager;
    Name                m_aComponentName;
    RequestOptions      m_aOptions;

public:
    OInvalidateTreeThread(CacheManager* _rTreeManager,  Name const & _aComponentName,
                          const RequestOptions& _aOptions)
    : m_rTreeManager(_rTreeManager)
    , m_aComponentName(_aComponentName)
    , m_aOptions(_aOptions)
    {}

    ~OInvalidateTreeThread()
    {}

private:
    virtual void SAL_CALL onTerminated()
    {
        delete this;
    }

    virtual void SAL_CALL run();
};

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

void CacheController::invalidateComponent(ComponentRequest const & _aComponent) CFG_UNO_THROW_ALL(  )
{
    if (!this->m_bDisposing)
    {
        // start the InvalidateTreeThread only, if we are not at disposemode
        if (OInvalidateTreeThread *pThread =
            new OInvalidateTreeThread(this, _aComponent.getComponentName(), _aComponent.getOptions()))
        {
            pThread->create();
        }
        else
            OSL_ENSURE(false, "Could not create refresher thread");
    }

}

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

CacheLocation CacheController::refreshComponent(ComponentRequest const & _aRequest) CFG_UNO_THROW_ALL()
{
    if (m_bDisposing) return CacheLocation();

    CacheRef aCache = this->getCacheAlways(_aRequest.getOptions());

    if (!aCache.is()) return CacheLocation();

    osl::MutexGuard aCacheLineGuard(aCache->mutex());

    // load the Node direct from the session, without using the cache
    ComponentRequest aForcedRequest(_aRequest);
    aForcedRequest.forceReload();

    ComponentResult aLoadedInstance = this->getComponentData(aForcedRequest,false);
    AbsolutePath aRequestPath = AbsolutePath::makeModulePath(_aRequest.getComponentName(), AbsolutePath::NoValidate());
    NodeInstance aNodeInstance(aLoadedInstance.mutableInstance().mutableData(),aRequestPath) ;
    NodeResult aLoadedNodeInstance(aNodeInstance) ;

    CacheLocation aResult;
    if (aLoadedNodeInstance.is())
    {
        Name aModuleName = aLoadedNodeInstance->root().getModuleName();

        memory::UpdateAccessor aChangingAccessor( aCache->getDataSegment(aModuleName) );
        OSL_ENSURE(aChangingAccessor.is(), "No existing cache line for tree being refreshed");

        data::TreeAddress aCachedTreeAddress = aCache->acquireModule(aModuleName);

        aResult.segment = aCache->getDataSegmentAddress(aModuleName);
        aResult.address = aCachedTreeAddress.addressValue();

        if (aCachedTreeAddress.is())
        try
        {
            std::auto_ptr<SubtreeChange> aTreeChanges;
            data::NodeAddress aRootAddress;

            {
                data::TreeAccessor aTreeAccess(aChangingAccessor.accessor(),aCachedTreeAddress);
                data::NodeAccessRef aRootNode = aTreeAccess.getRootNode();

                aTreeChanges = createDiffs(aRootNode, aLoadedNodeInstance->data().get(), aLoadedNodeInstance->root().location());
                aRootAddress = aRootNode.address();
            }

            if (aTreeChanges.get() != NULL)
            {
                // change all Values... found in the Subtree in the CacheTree
                applyUpdateWithAdjustmentToTree(*aTreeChanges, aChangingAccessor, aRootAddress);

                data::Accessor aNotifyLock = aChangingAccessor.downgrade(); // keep a read lock during notification

                UpdateRequest anUpdateReq(  aTreeChanges.get(),
                                            aLoadedNodeInstance->root().location(),
                                            _aRequest.getOptions()
                                          );

                m_aNotifier.notifyChanged(anUpdateReq);
            }

            aCache->releaseModule(aModuleName);
        }
        catch (...)
        {
            aCache->releaseModule(aModuleName);
            throw;
        }
    }
    return aResult;
}

// -----------------------------------------------------------------------------
void OInvalidateTreeThread::run()
{
    try
    {
        ComponentRequest aRequest(m_aComponentName, m_aOptions);
        m_rTreeManager->refreshComponent(aRequest);
    }
    catch(uno::Exception&)
    {
        // do nothing, only thread safe exception absorb
        CFG_TRACE_ERROR_NI("OInvalidateTreeThread::run: refreshing failed - ignoring the exception");
    }
}
// -----------------------------------------------------------------------------
    } // namespace backend

// -----------------------------------------------------------------------------
} // namespace configmgr

<commit_msg>INTEGRATION: CWS pchfix02 (1.20.60); FILE MERGED 2006/09/01 17:20:46 kaib 1.20.60.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: invalidatetree.cxx,v $
 *
 *  $Revision: 1.21 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-16 15:26:33 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

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

#include "cachecontroller.hxx"

#ifndef CONFIGMGR_CHANGE_HXX
#include "change.hxx"
#endif
#ifndef _CONFIGMGR_TREE_VALUENODE_HXX
#include "valuenode.hxx"
#endif

#ifndef CONFIGMGR_UPDATEHELPER_HXX
#include "updatehelper.hxx"
#endif
#ifndef _CONFIGMGR_TREEACTIONS_HXX_
#include "treeactions.hxx"
#endif

#ifndef CONFIGMGR_TREEACCESSOR_HXX
#include "treeaccessor.hxx"
#endif
#ifndef CONFIGMGR_UPDATEACCESSOR_HXX
#include "updateaccessor.hxx"
#endif

#ifndef _CONFIGMGR_TRACER_HXX_
#include "tracer.hxx"
#endif

#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_NOSUCHELEMENTEXCEPTION_HPP_
#include <com/sun/star/container/NoSuchElementException.hpp>
#endif

#ifndef _VOS_THREAD_HXX_
#include <vos/thread.hxx>
#endif

#ifndef INCLUDED_ALGORITHM
#include <algorithm>
#define INCLUDED_ALGORITHM
#endif

namespace configmgr
{

    using namespace com::sun::star::uno;
    using namespace configuration;
    namespace container = com::sun::star::container;
// -----------------------------------------------------------------------------
// ------------------------------- invalidateTree -------------------------------
// -----------------------------------------------------------------------------

namespace backend
{
// -----------------------------------------------------------------------------
std::auto_ptr<SubtreeChange> createDiffs(data::NodeAccessRef const& _aCachedNode,
                                            ISubtree const * _pLoadedSubtree,
                                            AbsolutePath const& _aAbsoluteSubtreePath)
{
    OSL_PRECOND(_aCachedNode.isValid(), "Need an existing node to create a diff");
    OSL_PRECOND(_pLoadedSubtree != 0, "Need a result node to create a diff");
    // Create a TreeChangeList with the right name, parentname and ConfigurationProperties
    std::auto_ptr<SubtreeChange> aNewChange(new SubtreeChange(_aAbsoluteSubtreePath.getLocalName().getName().toString(),
                                                                node::Attributes()) );

    if (!createUpdateFromDifference(*aNewChange, _aCachedNode, *_pLoadedSubtree))
        aNewChange.reset();

    return aNewChange;
}
// -----------------------------------------------------------------------------
#if 0
std::auto_ptr<ISubtree> TreeManager::loadNodeFromSession( AbsolutePath const& _aAbsoluteSubtreePath,
                                                     const vos::ORef < OOptions >& _xOptions,
                                                     sal_Int16 _nMinLevels)  CFG_UNO_THROW_ALL()
{
    TreeInfo* pInfo = this->requestTreeInfo(_xOptions,true /*create TreeInfo*/);

    CFG_TRACE_INFO_NI("cache manager: cache miss. going to load the node");
    rtl::Reference< OTreeLoader > xLoader = pInfo->getNewLoaderWithoutPending(_aAbsoluteSubtreePath, _nMinLevels, _xOptions, m_xBackend.get());

    OSL_ENSURE(xLoader.is(), "Did not receive a loader for retrieving the node");
    CFG_TRACE_INFO_NI("cache manager: cache miss. going to load the node");
    if (!xLoader.is())
        throw container::NoSuchElementException((::rtl::OUString::createFromAscii("Error while retrieving the node")), NULL);

    // now block for reading
    std::auto_ptr<ISubtree> pResponse;
    try
    {
        pResponse = xLoader->waitToResponse();
    }
    catch (uno::Exception& e)
    {
        pInfo->releaseLoader(xLoader);
        throw;
    }

    pInfo->releaseLoader(xLoader);

    return pResponse;
}
#endif
// -----------------------------------------------------------------------------

class OInvalidateTreeThread: public vos::OThread
{
    typedef backend::ICachedDataProvider CacheManager;
    typedef rtl::Reference< CacheManager > CacheManagerRef;
    CacheManagerRef     m_rTreeManager;
    Name                m_aComponentName;
    RequestOptions      m_aOptions;

public:
    OInvalidateTreeThread(CacheManager* _rTreeManager,  Name const & _aComponentName,
                          const RequestOptions& _aOptions)
    : m_rTreeManager(_rTreeManager)
    , m_aComponentName(_aComponentName)
    , m_aOptions(_aOptions)
    {}

    ~OInvalidateTreeThread()
    {}

private:
    virtual void SAL_CALL onTerminated()
    {
        delete this;
    }

    virtual void SAL_CALL run();
};

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

void CacheController::invalidateComponent(ComponentRequest const & _aComponent) CFG_UNO_THROW_ALL(  )
{
    if (!this->m_bDisposing)
    {
        // start the InvalidateTreeThread only, if we are not at disposemode
        if (OInvalidateTreeThread *pThread =
            new OInvalidateTreeThread(this, _aComponent.getComponentName(), _aComponent.getOptions()))
        {
            pThread->create();
        }
        else
            OSL_ENSURE(false, "Could not create refresher thread");
    }

}

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

CacheLocation CacheController::refreshComponent(ComponentRequest const & _aRequest) CFG_UNO_THROW_ALL()
{
    if (m_bDisposing) return CacheLocation();

    CacheRef aCache = this->getCacheAlways(_aRequest.getOptions());

    if (!aCache.is()) return CacheLocation();

    osl::MutexGuard aCacheLineGuard(aCache->mutex());

    // load the Node direct from the session, without using the cache
    ComponentRequest aForcedRequest(_aRequest);
    aForcedRequest.forceReload();

    ComponentResult aLoadedInstance = this->getComponentData(aForcedRequest,false);
    AbsolutePath aRequestPath = AbsolutePath::makeModulePath(_aRequest.getComponentName(), AbsolutePath::NoValidate());
    NodeInstance aNodeInstance(aLoadedInstance.mutableInstance().mutableData(),aRequestPath) ;
    NodeResult aLoadedNodeInstance(aNodeInstance) ;

    CacheLocation aResult;
    if (aLoadedNodeInstance.is())
    {
        Name aModuleName = aLoadedNodeInstance->root().getModuleName();

        memory::UpdateAccessor aChangingAccessor( aCache->getDataSegment(aModuleName) );
        OSL_ENSURE(aChangingAccessor.is(), "No existing cache line for tree being refreshed");

        data::TreeAddress aCachedTreeAddress = aCache->acquireModule(aModuleName);

        aResult.segment = aCache->getDataSegmentAddress(aModuleName);
        aResult.address = aCachedTreeAddress.addressValue();

        if (aCachedTreeAddress.is())
        try
        {
            std::auto_ptr<SubtreeChange> aTreeChanges;
            data::NodeAddress aRootAddress;

            {
                data::TreeAccessor aTreeAccess(aChangingAccessor.accessor(),aCachedTreeAddress);
                data::NodeAccessRef aRootNode = aTreeAccess.getRootNode();

                aTreeChanges = createDiffs(aRootNode, aLoadedNodeInstance->data().get(), aLoadedNodeInstance->root().location());
                aRootAddress = aRootNode.address();
            }

            if (aTreeChanges.get() != NULL)
            {
                // change all Values... found in the Subtree in the CacheTree
                applyUpdateWithAdjustmentToTree(*aTreeChanges, aChangingAccessor, aRootAddress);

                data::Accessor aNotifyLock = aChangingAccessor.downgrade(); // keep a read lock during notification

                UpdateRequest anUpdateReq(  aTreeChanges.get(),
                                            aLoadedNodeInstance->root().location(),
                                            _aRequest.getOptions()
                                          );

                m_aNotifier.notifyChanged(anUpdateReq);
            }

            aCache->releaseModule(aModuleName);
        }
        catch (...)
        {
            aCache->releaseModule(aModuleName);
            throw;
        }
    }
    return aResult;
}

// -----------------------------------------------------------------------------
void OInvalidateTreeThread::run()
{
    try
    {
        ComponentRequest aRequest(m_aComponentName, m_aOptions);
        m_rTreeManager->refreshComponent(aRequest);
    }
    catch(uno::Exception&)
    {
        // do nothing, only thread safe exception absorb
        CFG_TRACE_ERROR_NI("OInvalidateTreeThread::run: refreshing failed - ignoring the exception");
    }
}
// -----------------------------------------------------------------------------
    } // namespace backend

// -----------------------------------------------------------------------------
} // namespace configmgr

<|endoftext|>


<commit_before>#include <stdexcept>
#include <functional>
#include <list>

#include "containers/iterators.hpp"
#include "unittest/gtest.hpp"

namespace unittest {

struct test_iterator : one_way_iterator_t<int> {
    typedef std::list<std::list<int> > data_blocks_t;
    explicit test_iterator(data_blocks_t& _data_blocks) : prefetches_count(0), blocked_without_prefetch(0), data_blocks(_data_blocks) {
        // remove empty blocks
        data_blocks.remove_if(std::mem_fun_ref(&data_blocks_t::value_type::empty));
        // add first empty block (so that we could check prefetch of the first block
        data_blocks.push_front(std::list<int>());
    }
    boost::optional<int> next() {
        if (data_blocks.empty())
            return boost::none;

        if (data_blocks.front().empty()) {
            blocked_without_prefetch++;
            data_blocks.pop_front();
        }
        if (data_blocks.empty())
            return boost::none;

        int result = data_blocks.front().front();
        data_blocks.front().pop_front();
        return boost::optional<int>(result);
    }
    void prefetch() {
        prefetches_count++;
        if (!data_blocks.empty() && data_blocks.front().empty()) {
            data_blocks.pop_front();
        }
    }

    size_t prefetches_count;
    size_t blocked_without_prefetch;

private:
    data_blocks_t data_blocks;
};

struct delete_check_iterator : test_iterator {
    delete_check_iterator(data_blocks_t& data_blocks, bool *_deleted) : test_iterator(data_blocks), deleted(_deleted) { *deleted = false; }
    virtual ~delete_check_iterator() {
        *deleted = true;
    }
private:
    bool *deleted;
};

// Helper functions

std::list<int> parse_list_of_ints(const std::string &_l) {
    std::string l = _l;
    l += " ";

    std::list<int> result;
    std::string w;
    for (int i = 0, e = l.size(); i < e; ++i) {
        if (l[i] != ' ') {
            w.push_back(l[i]);
        } else if (!w.empty()) {
            int v = atoi(w.c_str());
            rassert(v != 0);
            result.push_back(v);

            w.clear();
        }
    }

    rassert(w.empty(), "we put a space at the end of l for a reason!");

    return result;
}

// parse the string "1 2 3 | 42 56 | 13" into a list of lists of integers, using '|' as a list separator
test_iterator::data_blocks_t parse_data_blocks(const std::string &_db) {
    std::string db = _db;
    db += " ";
    test_iterator::data_blocks_t result;
    std::string w;
    std::list<int> current_list;  // oh god

    for (int i = 0, e = db.size(); i < e; ++i) {
        if (db[i] != ' ') {
            w.push_back(db[i]);
        } else if (!w.empty()) {
            if (w == "|") {
                result.push_back(current_list);
                current_list.clear();
            } else {
                int v = atoi(w.c_str());
                rassert(v != 0);
                current_list.push_back(v);
            }
            w.clear();
        }
    }

    rassert(w.empty(), "we put a space at the end of db for a reason!");

    if (!current_list.empty()) {
        result.push_back(current_list);
    }

    return result;
}

std::list<int> data_blocks_to_list_of_ints(test_iterator::data_blocks_t& db) {
    std::list<int> result;
    for (test_iterator::data_blocks_t::iterator it = db.begin(); it != db.end(); ++it) {
        for (std::list<int>::iterator i = (*it).begin(); i != (*it).end(); ++i) {
            result.push_back(*i);
        }
        //std::copy((*it).begin(), (*it).end(), result.end());
    }
    return result;
}

// Tests

TEST(MergeIteratorsTest, merge_empty) {
    test_iterator::data_blocks_t empty_blocks;
    test_iterator *a = new test_iterator(empty_blocks);
    test_iterator *b = new test_iterator(empty_blocks);
    test_iterator *c = new test_iterator(empty_blocks);

    merge_ordered_data_iterator_t<int> merged;
    merged.add_mergee(a);
    merged.add_mergee(b);
    merged.add_mergee(c);

    ASSERT_FALSE(merged.next());
}

TEST(MergeIteratorsTest, parse_data_blocks) {
    test_iterator::data_blocks_t db = parse_data_blocks("1 2 3 | 42 56 | 93");
    ASSERT_EQ(db.size(), 3);
    ASSERT_EQ(db.front().size(), 3);
    ASSERT_EQ(db.back().size(), 1);
}

TEST(MergeIteratorsTest, three_way_merge) {
    test_iterator::data_blocks_t a_db = parse_data_blocks("1 2 3 | 7 | 10");
    test_iterator::data_blocks_t b_db = parse_data_blocks("4 | 6 8 9 | 11 13 16");
    test_iterator::data_blocks_t c_db = parse_data_blocks("5 8 | 9 | 12 15 16");

    test_iterator *a = new test_iterator(a_db);
    test_iterator *b = new test_iterator(b_db);
    test_iterator *c = new test_iterator(c_db);

    merge_ordered_data_iterator_t<int> merge_iterator;
    merge_iterator.add_mergee(a);
    merge_iterator.add_mergee(b);
    merge_iterator.add_mergee(c);

    std::list<int> merged;
    boost::optional<int> next;
    while ((next = merge_iterator.next())) {
        merged.push_back(next.get());
    }

    std::list<int> a_db_flat = data_blocks_to_list_of_ints(a_db);
    std::list<int> b_db_flat = data_blocks_to_list_of_ints(b_db);
    std::list<int> c_db_flat = data_blocks_to_list_of_ints(c_db);

    std::list<int> merged_expected;
    merged_expected.merge(a_db_flat);
    merged_expected.merge(b_db_flat);
    merged_expected.merge(c_db_flat);

    ASSERT_TRUE(std::equal(merged_expected.begin(), merged_expected.end(), merged.begin()));
}

TEST(MergeIteratorsTest, iterators_get_deleted) {
    test_iterator::data_blocks_t a_db = parse_data_blocks("1 2 3 | 7 | 10");
    test_iterator::data_blocks_t b_db = parse_data_blocks("4 | 6 8 9 | 11 13 16");
    test_iterator::data_blocks_t c_db = parse_data_blocks("5 8 | 9 | 12 15 16");
    test_iterator::data_blocks_t d_db = parse_data_blocks("");

    bool a_deleted = false, b_deleted = false, c_deleted = false, d_deleted = false;
    test_iterator *a = new delete_check_iterator(a_db, &a_deleted);
    test_iterator *b = new delete_check_iterator(b_db, &b_deleted);
    test_iterator *c = new delete_check_iterator(c_db, &c_deleted);
    test_iterator *d = new delete_check_iterator(d_db, &d_deleted);

    merge_ordered_data_iterator_t<int> merge_iterator;
    merge_iterator.add_mergee(a);
    merge_iterator.add_mergee(b);
    merge_iterator.add_mergee(c);
    merge_iterator.add_mergee(d);

    (void) merge_iterator.next();
    EXPECT_TRUE(d_deleted);

    boost::optional<int> next;
    bool expect_a_deleted = false;
    while ((next = merge_iterator.next())) {
        if (expect_a_deleted) {
            EXPECT_TRUE(a_deleted) << "merge_ordered_data_iterator_t should delete the iterator after it has exhausted";
        }

        if (next.get() == 10) {
            expect_a_deleted = true; // when the next element is fetched, merge iterator will recognize that
                                     // 'a' iterator has exhausted, so it can delete it
        }
    }

    EXPECT_TRUE(a_deleted) << "merge_ordered_data_iterator_t should have deleted the 'a' iterator long ago";
    EXPECT_TRUE(b_deleted && c_deleted) << "merge_ordered_data_iterator_t should delete the iterator after it has exhausted";

    a_deleted = false;
    b_deleted = false;
    {
        test_iterator *a = new delete_check_iterator(a_db, &a_deleted);
        test_iterator *b = new delete_check_iterator(b_db, &b_deleted);

        merge_ordered_data_iterator_t<int> merge_iterator;
        merge_iterator.add_mergee(a);
        merge_iterator.add_mergee(b);

        // get some data from the merge iterator, but don't exhaust the iterators
        (void) merge_iterator.next();
        (void) merge_iterator.next();
        (void) merge_iterator.next();
    }
    EXPECT_TRUE(a_deleted && b_deleted) << "merge_ordered_data_iterator_t should delete the iterators on destruction, even when they have not been exhausted";
}

}  // namespace unittest
<commit_msg>Reintroduce checks for non-blocking in merge iterator test.<commit_after>#include <stdexcept>
#include <functional>
#include <list>

#include "containers/iterators.hpp"
#include "unittest/gtest.hpp"

namespace unittest {

struct test_iterator : one_way_iterator_t<int> {
    typedef std::list<std::list<int> > data_blocks_t;
    test_iterator(data_blocks_t& _data_blocks, size_t& _blocked_without_prefetch) : prefetches_count(0), blocked_without_prefetch(_blocked_without_prefetch), data_blocks(_data_blocks) {
        blocked_without_prefetch = 0;

        // remove empty blocks
        data_blocks.remove_if(std::mem_fun_ref(&data_blocks_t::value_type::empty));
        // add first empty block (so that we could check prefetch of the first block
        data_blocks.push_front(std::list<int>());
    }
    boost::optional<int> next() {
        if (data_blocks.empty())
            return boost::none;

        if (data_blocks.front().empty()) {
            blocked_without_prefetch++;
            data_blocks.pop_front();
        }
        if (data_blocks.empty())
            return boost::none;

        int result = data_blocks.front().front();
        data_blocks.front().pop_front();
        return boost::optional<int>(result);
    }
    void prefetch() {
        prefetches_count++;
        if (!data_blocks.empty() && data_blocks.front().empty()) {
            data_blocks.pop_front();
        }
    }

    size_t prefetches_count;
    size_t& blocked_without_prefetch;

private:
    data_blocks_t data_blocks;
};

struct delete_check_iterator : test_iterator {
    delete_check_iterator(data_blocks_t& data_blocks, size_t& blocked_without_prefetch, bool *_deleted) : test_iterator(data_blocks, blocked_without_prefetch), deleted(_deleted) { *deleted = false; }
    virtual ~delete_check_iterator() {
        *deleted = true;
    }
private:
    bool *deleted;
};

// Helper functions

std::list<int> parse_list_of_ints(const std::string &_l) {
    std::string l = _l;
    l += " ";

    std::list<int> result;
    std::string w;
    for (int i = 0, e = l.size(); i < e; ++i) {
        if (l[i] != ' ') {
            w.push_back(l[i]);
        } else if (!w.empty()) {
            int v = atoi(w.c_str());
            rassert(v != 0);
            result.push_back(v);

            w.clear();
        }
    }

    rassert(w.empty(), "we put a space at the end of l for a reason!");

    return result;
}

// parse the string "1 2 3 | 42 56 | 13" into a list of lists of integers, using '|' as a list separator
test_iterator::data_blocks_t parse_data_blocks(const std::string &_db) {
    std::string db = _db;
    db += " ";
    test_iterator::data_blocks_t result;
    std::string w;
    std::list<int> current_list;  // oh god

    for (int i = 0, e = db.size(); i < e; ++i) {
        if (db[i] != ' ') {
            w.push_back(db[i]);
        } else if (!w.empty()) {
            if (w == "|") {
                result.push_back(current_list);
                current_list.clear();
            } else {
                int v = atoi(w.c_str());
                rassert(v != 0);
                current_list.push_back(v);
            }
            w.clear();
        }
    }

    rassert(w.empty(), "we put a space at the end of db for a reason!");

    if (!current_list.empty()) {
        result.push_back(current_list);
    }

    return result;
}

std::list<int> data_blocks_to_list_of_ints(test_iterator::data_blocks_t& db) {
    std::list<int> result;
    for (test_iterator::data_blocks_t::iterator it = db.begin(); it != db.end(); ++it) {
        for (std::list<int>::iterator i = (*it).begin(); i != (*it).end(); ++i) {
            result.push_back(*i);
        }
        //std::copy((*it).begin(), (*it).end(), result.end());
    }
    return result;
}

// Tests

TEST(MergeIteratorsTest, merge_empty) {
    test_iterator::data_blocks_t empty_blocks;
    size_t blocked_without_prefetch_a, blocked_without_prefetch_b, blocked_without_prefetch_c;
    test_iterator *a = new test_iterator(empty_blocks, blocked_without_prefetch_a);
    test_iterator *b = new test_iterator(empty_blocks, blocked_without_prefetch_b);
    test_iterator *c = new test_iterator(empty_blocks, blocked_without_prefetch_c);

    merge_ordered_data_iterator_t<int> merged;
    merged.add_mergee(a);
    merged.add_mergee(b);
    merged.add_mergee(c);

    ASSERT_FALSE(merged.next());
    ASSERT_EQ(blocked_without_prefetch_a, 0);
    ASSERT_EQ(blocked_without_prefetch_b, 0);
    ASSERT_EQ(blocked_without_prefetch_c, 0);
}

TEST(MergeIteratorsTest, parse_data_blocks) {
    test_iterator::data_blocks_t db = parse_data_blocks("1 2 3 | 42 56 | 93");
    ASSERT_EQ(db.size(), 3);
    ASSERT_EQ(db.front().size(), 3);
    ASSERT_EQ(db.back().size(), 1);
}

TEST(MergeIteratorsTest, three_way_merge) {
    test_iterator::data_blocks_t a_db = parse_data_blocks("1 2 3 | 7 | 10");
    test_iterator::data_blocks_t b_db = parse_data_blocks("4 | 6 8 9 | 11 13 16");
    test_iterator::data_blocks_t c_db = parse_data_blocks("5 8 | 9 | 12 15 16");

    size_t blocked_without_prefetch_a, blocked_without_prefetch_b, blocked_without_prefetch_c;
    test_iterator *a = new test_iterator(a_db, blocked_without_prefetch_a);
    test_iterator *b = new test_iterator(b_db, blocked_without_prefetch_b);
    test_iterator *c = new test_iterator(c_db, blocked_without_prefetch_c);

    merge_ordered_data_iterator_t<int> merge_iterator;
    merge_iterator.add_mergee(a);
    merge_iterator.add_mergee(b);
    merge_iterator.add_mergee(c);

    std::list<int> merged;
    boost::optional<int> next;
    while ((next = merge_iterator.next())) {
        merged.push_back(next.get());
    }

    std::list<int> a_db_flat = data_blocks_to_list_of_ints(a_db);
    std::list<int> b_db_flat = data_blocks_to_list_of_ints(b_db);
    std::list<int> c_db_flat = data_blocks_to_list_of_ints(c_db);

    std::list<int> merged_expected;
    merged_expected.merge(a_db_flat);
    merged_expected.merge(b_db_flat);
    merged_expected.merge(c_db_flat);

    ASSERT_TRUE(std::equal(merged_expected.begin(), merged_expected.end(), merged.begin()));
    ASSERT_EQ(blocked_without_prefetch_a, 0);
    ASSERT_EQ(blocked_without_prefetch_b, 0);
    ASSERT_EQ(blocked_without_prefetch_c, 0);
}

TEST(MergeIteratorsTest, iterators_get_deleted) {
    test_iterator::data_blocks_t a_db = parse_data_blocks("1 2 3 | 7 | 10");
    test_iterator::data_blocks_t b_db = parse_data_blocks("4 | 6 8 9 | 11 13 16");
    test_iterator::data_blocks_t c_db = parse_data_blocks("5 8 | 9 | 12 15 16");
    test_iterator::data_blocks_t d_db = parse_data_blocks("");

    size_t blocked_without_prefetch_a, blocked_without_prefetch_b, blocked_without_prefetch_c, blocked_without_prefetch_d;
    bool a_deleted = false, b_deleted = false, c_deleted = false, d_deleted = false;
    test_iterator *a = new delete_check_iterator(a_db, blocked_without_prefetch_a, &a_deleted);
    test_iterator *b = new delete_check_iterator(b_db, blocked_without_prefetch_b, &b_deleted);
    test_iterator *c = new delete_check_iterator(c_db, blocked_without_prefetch_c, &c_deleted);
    test_iterator *d = new delete_check_iterator(d_db, blocked_without_prefetch_d, &d_deleted);

    merge_ordered_data_iterator_t<int> merge_iterator;
    merge_iterator.add_mergee(a);
    merge_iterator.add_mergee(b);
    merge_iterator.add_mergee(c);
    merge_iterator.add_mergee(d);

    (void) merge_iterator.next();
    EXPECT_TRUE(d_deleted);

    boost::optional<int> next;
    bool expect_a_deleted = false;
    while ((next = merge_iterator.next())) {
        if (expect_a_deleted) {
            EXPECT_TRUE(a_deleted) << "merge_ordered_data_iterator_t should delete the iterator after it has exhausted";
        }

        if (next.get() == 10) {
            expect_a_deleted = true; // when the next element is fetched, merge iterator will recognize that
                                     // 'a' iterator has exhausted, so it can delete it
        }
    }

    EXPECT_TRUE(a_deleted) << "merge_ordered_data_iterator_t should have deleted the 'a' iterator long ago";
    EXPECT_TRUE(b_deleted && c_deleted) << "merge_ordered_data_iterator_t should delete the iterator after it has exhausted";

    ASSERT_EQ(blocked_without_prefetch_a, 0);
    ASSERT_EQ(blocked_without_prefetch_b, 0);
    ASSERT_EQ(blocked_without_prefetch_c, 0);
    ASSERT_EQ(blocked_without_prefetch_d, 0);

    a_deleted = false;
    b_deleted = false;
    {
        test_iterator *a = new delete_check_iterator(a_db, blocked_without_prefetch_a, &a_deleted);
        test_iterator *b = new delete_check_iterator(b_db, blocked_without_prefetch_b, &b_deleted);

        merge_ordered_data_iterator_t<int> merge_iterator;
        merge_iterator.add_mergee(a);
        merge_iterator.add_mergee(b);

        // get some data from the merge iterator, but don't exhaust the iterators
        (void) merge_iterator.next();
        (void) merge_iterator.next();
        (void) merge_iterator.next();
    }
    EXPECT_TRUE(a_deleted && b_deleted) << "merge_ordered_data_iterator_t should delete the iterators on destruction, even when they have not been exhausted";
    ASSERT_EQ(blocked_without_prefetch_a, 0);
    ASSERT_EQ(blocked_without_prefetch_b, 0);
}

}  // namespace unittest
<|endoftext|>


<commit_before>#pragma once

#include "math_helpers.hpp"

#include <array>
#include <cassert>
#include <tuple>

namespace cu
{

/// An N-dimensional point whose coordinate type is @c T.
///
/// The coordinates can be accessed via the @c operator[]().
/// The constructor takes the same arguments as an @c std::array<T,N>.
template <typename T, std::size_t N>
class Point
{
public:
  template <typename ...Us, typename = decltype(std::array<T,N>{std::declval<Us>()...})>
  Point( Us && ...args )
    : x_{ std::forward<Us>(args)... }
  {}

  T &operator[]( std::size_t idx )
  {
    return x_[idx];
  }

  const T & operator[]( std::size_t idx ) const
  {
    return x_[idx];
  }

  bool operator==( const Point & other )
  {
    return x_ == other.x_;
  }

private:
  std::array<T,N> x_;
};

/// An @c N-dimensional rectangle whose coordinate type is @c T.
///
/// The rectangle is determined by two points @c A and @c B, where no
/// coordinate of @c A may be larger than the corresponding coordinate
/// of @c B. This ensures, that the edges of the rectangle all have
/// non-negative lenghts.
template <typename T, std::size_t N>
class Rect
{
  using Point = Point<T,N>;
public:
  Rect()
  {}

  Rect( Point A, Point B )
    : A_(A)
    , B_(B)
  {
    checkInvariants();
  }

  constexpr Point A() const { return A_; }
  constexpr Point B() const { return B_; }

  void setA( const Point & P ) { A_ = P; checkInvariants(); }
  void setB( const Point & P ) { B_ = P; checkInvariants(); }

private:
  void checkInvariants() const
  {
    for ( std::size_t i = 0; i != N; ++i )
      assert( A_[i] <= B_[i] );
  }

  Point A_;
  Point B_;
};

namespace detail
{
  template <typename T>
  std::pair<T,T> intersect_interval( const T & a1, const T & b1,
                                     const T & a2, const T & b2 )
  {
    if ( b1 < a2 || a1 > b2 )
      return { {}, {} };
    return { std::max( a1, a2 ), std::min(b1, b2) };
  }

  template <typename T, std::size_t N, std::size_t ...indices>
  Rect<T,N> intersect_impl( const Rect<T,N> & lhs,
                            const Rect<T,N> & rhs,
                            std::index_sequence<indices...> )
  {
    Point<T,N> A;
    Point<T,N> B;
    for ( std::size_t i = 0; i != N; ++i )
    {
      std::tie( A[i], B[i] ) = intersect_interval(
            lhs.A()[i], lhs.B()[i],
            rhs.A()[i], rhs.B()[i] );
    }
    return { A, B };
  }
}

/// Calculates the intersection of two rectangles.
///
/// If the intersection is empty, then the resulting rectangle will have
/// volume @c 0.
template <typename T, std::size_t N>
Rect<T,N> operator &( const Rect<T,N> & lhs, const Rect<T,N> & rhs )
{
  return detail::intersect_impl( lhs, rhs, std::make_index_sequence<N>() );
}

template <typename T, std::size_t N>
bool operator==( const Rect<T,N> & lhs, const Rect<T,N> & rhs )
{
  return lhs.A() == rhs.A() && lhs.B() == rhs.B();
}

} // namespace cu
<commit_msg>Compile bug fix. Added namespace to cu::Point.<commit_after>#pragma once

#include "math_helpers.hpp"

#include <array>
#include <cassert>
#include <tuple>

namespace cu
{

/// An N-dimensional point whose coordinate type is @c T.
///
/// The coordinates can be accessed via the @c operator[]().
/// The constructor takes the same arguments as an @c std::array<T,N>.
template <typename T, std::size_t N>
class Point
{
public:
  template <typename ...Us, typename = decltype(std::array<T,N>{std::declval<Us>()...})>
  Point( Us && ...args )
    : x_{ std::forward<Us>(args)... }
  {}

  T &operator[]( std::size_t idx )
  {
    return x_[idx];
  }

  const T & operator[]( std::size_t idx ) const
  {
    return x_[idx];
  }

  bool operator==( const Point & other )
  {
    return x_ == other.x_;
  }

private:
  std::array<T,N> x_;
};

/// An @c N-dimensional rectangle whose coordinate type is @c T.
///
/// The rectangle is determined by two points @c A and @c B, where no
/// coordinate of @c A may be larger than the corresponding coordinate
/// of @c B. This ensures, that the edges of the rectangle all have
/// non-negative lenghts.
template <typename T, std::size_t N>
class Rect
{
  using Point = cu::Point<T,N>;
public:
  Rect()
  {}

  Rect( Point A, Point B )
    : A_(A)
    , B_(B)
  {
    checkInvariants();
  }

  constexpr Point A() const { return A_; }
  constexpr Point B() const { return B_; }

  void setA( const Point & P ) { A_ = P; checkInvariants(); }
  void setB( const Point & P ) { B_ = P; checkInvariants(); }

private:
  void checkInvariants() const
  {
    for ( std::size_t i = 0; i != N; ++i )
      assert( A_[i] <= B_[i] );
  }

  Point A_;
  Point B_;
};

namespace detail
{
  template <typename T>
  std::pair<T,T> intersect_interval( const T & a1, const T & b1,
                                     const T & a2, const T & b2 )
  {
    if ( b1 < a2 || a1 > b2 )
      return { {}, {} };
    return { std::max( a1, a2 ), std::min(b1, b2) };
  }

  template <typename T, std::size_t N, std::size_t ...indices>
  Rect<T,N> intersect_impl( const Rect<T,N> & lhs,
                            const Rect<T,N> & rhs,
                            std::index_sequence<indices...> )
  {
    Point<T,N> A;
    Point<T,N> B;
    for ( std::size_t i = 0; i != N; ++i )
    {
      std::tie( A[i], B[i] ) = intersect_interval(
            lhs.A()[i], lhs.B()[i],
            rhs.A()[i], rhs.B()[i] );
    }
    return { A, B };
  }
}

/// Calculates the intersection of two rectangles.
///
/// If the intersection is empty, then the resulting rectangle will have
/// volume @c 0.
template <typename T, std::size_t N>
Rect<T,N> operator &( const Rect<T,N> & lhs, const Rect<T,N> & rhs )
{
  return detail::intersect_impl( lhs, rhs, std::make_index_sequence<N>() );
}

template <typename T, std::size_t N>
bool operator==( const Rect<T,N> & lhs, const Rect<T,N> & rhs )
{
  return lhs.A() == rhs.A() && lhs.B() == rhs.B();
}

} // namespace cu
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#ifndef _CONNECTIVITY_COMMONTOOLS_HXX_
#define _CONNECTIVITY_COMMONTOOLS_HXX_

#include <rtl/ustring.hxx>
#include <com/sun/star/lang/DisposedException.hpp>
#include <com/sun/star/uno/Any.hxx>
#ifndef _VECTOR_
#include <vector>
#endif
#include <cppuhelper/weakref.hxx>
#include <comphelper/stl_types.hxx>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/sdbcx/XColumnsSupplier.hpp>
#include <osl/interlck.h>
#include <jvmaccess/virtualmachine.hxx>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include "connectivity/dbtoolsdllapi.hxx"

namespace com { namespace sun { namespace star { namespace util {
    struct Date;
    struct DateTime;
    struct Time;
}
}}}

namespace connectivity
{
    //------------------------------------------------------------------------------
    OOO_DLLPUBLIC_DBTOOLS sal_Bool match(const sal_Unicode* pWild, const sal_Unicode* pStr, const sal_Unicode cEscape);
    //------------------------------------------------------------------------------
    OOO_DLLPUBLIC_DBTOOLS rtl::OUString toString(const ::com::sun::star::uno::Any& rValue);
    OOO_DLLPUBLIC_DBTOOLS rtl::OUString toDateString(const ::com::sun::star::util::Date& rDate);
    OOO_DLLPUBLIC_DBTOOLS rtl::OUString toTimeString(const ::com::sun::star::util::Time& rTime);
    OOO_DLLPUBLIC_DBTOOLS rtl::OUString toDateTimeString(const ::com::sun::star::util::DateTime& rDateTime);

    // typedefs
    typedef std::vector< ::com::sun::star::uno::WeakReferenceHelper > OWeakRefArray;
    typedef ::com::sun::star::uno::Reference< ::com::sun::star::sdbcx::XColumnsSupplier>    OSQLTable;

    DECLARE_STL_MAP(::rtl::OUString,OSQLTable,comphelper::UStringMixLess,  OSQLTables);

    // -------------------------------------------------------------------------
    // class ORefVector allows reference counting on a std::vector
    // -------------------------------------------------------------------------
    template< class VectorVal > class ORefVector
    {
        std::vector< VectorVal > m_vector;
        oslInterlockedCount         m_refCount;

    protected:
        virtual ~ORefVector(){}
    public:
        typedef std::vector< VectorVal > Vector;

        ORefVector() : m_refCount(0) {}
        ORefVector(size_t _st) : m_vector(_st) , m_refCount(0) {}
        ORefVector(const ORefVector& _rRH) : m_vector(_rRH.m_vector),m_refCount(0)
        {
        }
        ORefVector& operator=(const ORefVector& _rRH)
        {
            if ( &_rRH != this )
            {
                m_vector = _rRH.m_vector;
            }
            return *this;
        }

        std::vector< VectorVal > & get() { return m_vector; }
        std::vector< VectorVal > const & get() const { return m_vector; }

        inline static void * SAL_CALL operator new( size_t nSize ) SAL_THROW( () )
            { return ::rtl_allocateMemory( nSize ); }
        inline static void SAL_CALL operator delete( void * pMem ) SAL_THROW( () )
            { ::rtl_freeMemory( pMem ); }
        inline static void * SAL_CALL operator new( size_t, void * pMem ) SAL_THROW( () )
            { return pMem; }
        inline static void SAL_CALL operator delete( void *, void * ) SAL_THROW( () )
            {}

        void acquire()
        {
            osl_incrementInterlockedCount( &m_refCount );
        }
        void release()
        {
            if (! osl_decrementInterlockedCount( &m_refCount ))
                delete this;
        }

    };
    // -------------------------------------------------------------------------
    // class ORowVector incudes refcounting and initialze himself
    // with at least one element. This first element is reserved for
    // the bookmark
    // -------------------------------------------------------------------------
    template< class VectorVal > class ORowVector : public  ORefVector< VectorVal >
    {
    public:
        ORowVector() : ORefVector< VectorVal >(1){}
        ORowVector(size_t _st) : ORefVector< VectorVal >(_st+1)
            {}
    };

    typedef ORefVector< ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet> > OSQLColumns;

    // =======================================================================================
    // search from __first to __last the column with the name _rVal
    // when no such column exist __last is returned
    OOO_DLLPUBLIC_DBTOOLS
    OSQLColumns::Vector::const_iterator find(   OSQLColumns::Vector::const_iterator __first,
                                        OSQLColumns::Vector::const_iterator __last,
                                        const ::rtl::OUString& _rVal,
                                        const ::comphelper::UStringMixEqual& _rCase);
    // =======================================================================================
    // search from __first to __last the column with the realname _rVal
    // when no such column exist __last is returned
    OOO_DLLPUBLIC_DBTOOLS
    OSQLColumns::Vector::const_iterator findRealName(   OSQLColumns::Vector::const_iterator __first,
                                                OSQLColumns::Vector::const_iterator __last,
                                                const ::rtl::OUString& _rVal,
                                                const ::comphelper::UStringMixEqual& _rCase);

    // =======================================================================================
    // the first two find methods are much faster than the one below
    // =======================================================================================
    // search from __first to __last the column with the property _rProp equals the value _rVal
    // when no such column exist __last is returned
    OOO_DLLPUBLIC_DBTOOLS
    OSQLColumns::Vector::const_iterator find(   OSQLColumns::Vector::const_iterator __first,
                                        OSQLColumns::Vector::const_iterator __last,
                                        const ::rtl::OUString& _rProp,
                                        const ::rtl::OUString& _rVal,
                                        const ::comphelper::UStringMixEqual& _rCase);

    OOO_DLLPUBLIC_DBTOOLS void checkDisposed(sal_Bool _bThrow) throw ( ::com::sun::star::lang::DisposedException );

    /** creates a java virtual machine
        @param  _rxFactory
            The ORB.
        @return
            The JavaVM.
    */
    OOO_DLLPUBLIC_DBTOOLS ::rtl::Reference< jvmaccess::VirtualMachine > getJavaVM(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory);

    /** return <TRUE/> if the java class exists, otherwise <FALSE/>.
        @param  _pJVM
            The JavaVM.
        @param  _sClassName
            The class name to look for.
    */
    OOO_DLLPUBLIC_DBTOOLS sal_Bool existsJavaClassByName( const ::rtl::Reference< jvmaccess::VirtualMachine >& _pJVM,const ::rtl::OUString& _sClassName );
}

//==================================================================================

#define DECLARE_SERVICE_INFO()  \
    virtual ::rtl::OUString SAL_CALL getImplementationName(  ) throw (::com::sun::star::uno::RuntimeException); \
    virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw(::com::sun::star::uno::RuntimeException); \
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames(  ) throw(::com::sun::star::uno::RuntimeException) \

#define IMPLEMENT_SERVICE_INFO(classname, implasciiname, serviceasciiname)  \
    ::rtl::OUString SAL_CALL classname::getImplementationName(  ) throw (::com::sun::star::uno::RuntimeException)   \
    {   \
        return ::rtl::OUString::createFromAscii(implasciiname); \
    }   \
    ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL classname::getSupportedServiceNames(  ) throw(::com::sun::star::uno::RuntimeException)  \
    {   \
        ::com::sun::star::uno::Sequence< ::rtl::OUString > aSupported(1);   \
        aSupported[0] = ::rtl::OUString::createFromAscii(serviceasciiname); \
        return aSupported;  \
    }   \
    sal_Bool SAL_CALL classname::supportsService( const ::rtl::OUString& _rServiceName ) throw(::com::sun::star::uno::RuntimeException) \
    {   \
        Sequence< ::rtl::OUString > aSupported(getSupportedServiceNames());             \
        const ::rtl::OUString* pSupported = aSupported.getConstArray();                 \
        const ::rtl::OUString* pEnd = pSupported + aSupported.getLength();              \
        for (;pSupported != pEnd && !pSupported->equals(_rServiceName); ++pSupported)   \
            ;                                                                           \
                                                                                \
        return pSupported != pEnd;                                                      \
    }   \

//==================================================================================

#endif // _CONNECTIVITY_COMMONTOOLS_HXX_

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>overload match and avoid implicit cast<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#ifndef _CONNECTIVITY_COMMONTOOLS_HXX_
#define _CONNECTIVITY_COMMONTOOLS_HXX_

#include <rtl/ustring.hxx>
#include <com/sun/star/lang/DisposedException.hpp>
#include <com/sun/star/uno/Any.hxx>
#ifndef _VECTOR_
#include <vector>
#endif
#include <cppuhelper/weakref.hxx>
#include <comphelper/stl_types.hxx>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/sdbcx/XColumnsSupplier.hpp>
#include <osl/interlck.h>
#include <jvmaccess/virtualmachine.hxx>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include "connectivity/dbtoolsdllapi.hxx"

namespace com { namespace sun { namespace star { namespace util {
    struct Date;
    struct DateTime;
    struct Time;
}
}}}

namespace connectivity
{
    //------------------------------------------------------------------------------
    OOO_DLLPUBLIC_DBTOOLS sal_Bool match(const sal_Unicode* pWild, const sal_Unicode* pStr, const sal_Unicode cEscape);
    inline sal_Bool match(const ::rtl::OUString &rWild, const ::rtl::OUString &rStr, const sal_Unicode cEscape)
    {
        return match(rWild.getStr(), rStr.getStr(), cEscape);
    }
    //------------------------------------------------------------------------------
    OOO_DLLPUBLIC_DBTOOLS rtl::OUString toString(const ::com::sun::star::uno::Any& rValue);
    OOO_DLLPUBLIC_DBTOOLS rtl::OUString toDateString(const ::com::sun::star::util::Date& rDate);
    OOO_DLLPUBLIC_DBTOOLS rtl::OUString toTimeString(const ::com::sun::star::util::Time& rTime);
    OOO_DLLPUBLIC_DBTOOLS rtl::OUString toDateTimeString(const ::com::sun::star::util::DateTime& rDateTime);

    // typedefs
    typedef std::vector< ::com::sun::star::uno::WeakReferenceHelper > OWeakRefArray;
    typedef ::com::sun::star::uno::Reference< ::com::sun::star::sdbcx::XColumnsSupplier>    OSQLTable;

    DECLARE_STL_MAP(::rtl::OUString,OSQLTable,comphelper::UStringMixLess,  OSQLTables);

    // -------------------------------------------------------------------------
    // class ORefVector allows reference counting on a std::vector
    // -------------------------------------------------------------------------
    template< class VectorVal > class ORefVector
    {
        std::vector< VectorVal > m_vector;
        oslInterlockedCount         m_refCount;

    protected:
        virtual ~ORefVector(){}
    public:
        typedef std::vector< VectorVal > Vector;

        ORefVector() : m_refCount(0) {}
        ORefVector(size_t _st) : m_vector(_st) , m_refCount(0) {}
        ORefVector(const ORefVector& _rRH) : m_vector(_rRH.m_vector),m_refCount(0)
        {
        }
        ORefVector& operator=(const ORefVector& _rRH)
        {
            if ( &_rRH != this )
            {
                m_vector = _rRH.m_vector;
            }
            return *this;
        }

        std::vector< VectorVal > & get() { return m_vector; }
        std::vector< VectorVal > const & get() const { return m_vector; }

        inline static void * SAL_CALL operator new( size_t nSize ) SAL_THROW( () )
            { return ::rtl_allocateMemory( nSize ); }
        inline static void SAL_CALL operator delete( void * pMem ) SAL_THROW( () )
            { ::rtl_freeMemory( pMem ); }
        inline static void * SAL_CALL operator new( size_t, void * pMem ) SAL_THROW( () )
            { return pMem; }
        inline static void SAL_CALL operator delete( void *, void * ) SAL_THROW( () )
            {}

        void acquire()
        {
            osl_incrementInterlockedCount( &m_refCount );
        }
        void release()
        {
            if (! osl_decrementInterlockedCount( &m_refCount ))
                delete this;
        }

    };
    // -------------------------------------------------------------------------
    // class ORowVector incudes refcounting and initialze himself
    // with at least one element. This first element is reserved for
    // the bookmark
    // -------------------------------------------------------------------------
    template< class VectorVal > class ORowVector : public  ORefVector< VectorVal >
    {
    public:
        ORowVector() : ORefVector< VectorVal >(1){}
        ORowVector(size_t _st) : ORefVector< VectorVal >(_st+1)
            {}
    };

    typedef ORefVector< ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet> > OSQLColumns;

    // =======================================================================================
    // search from __first to __last the column with the name _rVal
    // when no such column exist __last is returned
    OOO_DLLPUBLIC_DBTOOLS
    OSQLColumns::Vector::const_iterator find(   OSQLColumns::Vector::const_iterator __first,
                                        OSQLColumns::Vector::const_iterator __last,
                                        const ::rtl::OUString& _rVal,
                                        const ::comphelper::UStringMixEqual& _rCase);
    // =======================================================================================
    // search from __first to __last the column with the realname _rVal
    // when no such column exist __last is returned
    OOO_DLLPUBLIC_DBTOOLS
    OSQLColumns::Vector::const_iterator findRealName(   OSQLColumns::Vector::const_iterator __first,
                                                OSQLColumns::Vector::const_iterator __last,
                                                const ::rtl::OUString& _rVal,
                                                const ::comphelper::UStringMixEqual& _rCase);

    // =======================================================================================
    // the first two find methods are much faster than the one below
    // =======================================================================================
    // search from __first to __last the column with the property _rProp equals the value _rVal
    // when no such column exist __last is returned
    OOO_DLLPUBLIC_DBTOOLS
    OSQLColumns::Vector::const_iterator find(   OSQLColumns::Vector::const_iterator __first,
                                        OSQLColumns::Vector::const_iterator __last,
                                        const ::rtl::OUString& _rProp,
                                        const ::rtl::OUString& _rVal,
                                        const ::comphelper::UStringMixEqual& _rCase);

    OOO_DLLPUBLIC_DBTOOLS void checkDisposed(sal_Bool _bThrow) throw ( ::com::sun::star::lang::DisposedException );

    /** creates a java virtual machine
        @param  _rxFactory
            The ORB.
        @return
            The JavaVM.
    */
    OOO_DLLPUBLIC_DBTOOLS ::rtl::Reference< jvmaccess::VirtualMachine > getJavaVM(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory);

    /** return <TRUE/> if the java class exists, otherwise <FALSE/>.
        @param  _pJVM
            The JavaVM.
        @param  _sClassName
            The class name to look for.
    */
    OOO_DLLPUBLIC_DBTOOLS sal_Bool existsJavaClassByName( const ::rtl::Reference< jvmaccess::VirtualMachine >& _pJVM,const ::rtl::OUString& _sClassName );
}

//==================================================================================

#define DECLARE_SERVICE_INFO()  \
    virtual ::rtl::OUString SAL_CALL getImplementationName(  ) throw (::com::sun::star::uno::RuntimeException); \
    virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw(::com::sun::star::uno::RuntimeException); \
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames(  ) throw(::com::sun::star::uno::RuntimeException) \

#define IMPLEMENT_SERVICE_INFO(classname, implasciiname, serviceasciiname)  \
    ::rtl::OUString SAL_CALL classname::getImplementationName(  ) throw (::com::sun::star::uno::RuntimeException)   \
    {   \
        return ::rtl::OUString::createFromAscii(implasciiname); \
    }   \
    ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL classname::getSupportedServiceNames(  ) throw(::com::sun::star::uno::RuntimeException)  \
    {   \
        ::com::sun::star::uno::Sequence< ::rtl::OUString > aSupported(1);   \
        aSupported[0] = ::rtl::OUString::createFromAscii(serviceasciiname); \
        return aSupported;  \
    }   \
    sal_Bool SAL_CALL classname::supportsService( const ::rtl::OUString& _rServiceName ) throw(::com::sun::star::uno::RuntimeException) \
    {   \
        Sequence< ::rtl::OUString > aSupported(getSupportedServiceNames());             \
        const ::rtl::OUString* pSupported = aSupported.getConstArray();                 \
        const ::rtl::OUString* pEnd = pSupported + aSupported.getLength();              \
        for (;pSupported != pEnd && !pSupported->equals(_rServiceName); ++pSupported)   \
            ;                                                                           \
                                                                                \
        return pSupported != pEnd;                                                      \
    }   \

//==================================================================================

#endif // _CONNECTIVITY_COMMONTOOLS_HXX_

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


<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 <sal/macros.h>
#include "MDriver.hxx"
#include "MConnection.hxx"
#include "connectivity/dbexception.hxx"
#include "resource/mozab_res.hrc"
#include "resource/common_res.hrc"

#include <tools/solar.h>
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::beans;
using namespace com::sun::star::sdbc;
using namespace connectivity::mozab;

namespace connectivity
{
    namespace mozab
    {
        //------------------------------------------------------------------
        ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >  SAL_CALL MozabDriver_CreateInstance(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory) throw( ::com::sun::star::uno::Exception )
        {
            return *(new MozabDriver( _rxFactory ));
        }
    }
}
// --------------------------------------------------------------------------------
MozabDriver::MozabDriver(
    const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory)
    : ODriver_BASE(m_aMutex), m_xMSFactory( _rxFactory )
    ,m_hModule(NULL)
    ,m_pCreationFunc(NULL)
{
}
// -----------------------------------------------------------------------------
MozabDriver::~MozabDriver()
{
}
// --------------------------------------------------------------------------------
void MozabDriver::disposing()
{
    ::osl::MutexGuard aGuard(m_aMutex);

    // when driver will be destroied so all our connections have to be destroied as well
    for (OWeakRefArray::iterator i = m_xConnections.begin(); m_xConnections.end() != i; ++i)
    {
        Reference< XComponent > xComp(i->get(), UNO_QUERY);
        if (xComp.is())
            xComp->dispose();
    }
    m_xConnections.clear();
    connectivity::OWeakRefArray().swap(m_xConnections); // this really clears

    ODriver_BASE::disposing();
    if(m_hModule)
    {
        m_pCreationFunc = NULL;
        osl_unloadModule(m_hModule);
        m_hModule = NULL;
    }
}

// static ServiceInfo
//------------------------------------------------------------------------------
rtl::OUString MozabDriver::getImplementationName_Static(  ) throw(RuntimeException)
{
    return rtl::OUString(MOZAB_DRIVER_IMPL_NAME);
        // this name is referenced in the configuration and in the mozab.xml
        // Please take care when changing it.
}
//------------------------------------------------------------------------------
Sequence< ::rtl::OUString > MozabDriver::getSupportedServiceNames_Static(  ) throw (RuntimeException)
{
    // which service is supported
    // for more information @see com.sun.star.sdbc.Driver
    Sequence< ::rtl::OUString > aSNS( 1 );
    aSNS[0] = ::rtl::OUString( "com.sun.star.sdbc.Driver");
    return aSNS;
}

//------------------------------------------------------------------
::rtl::OUString SAL_CALL MozabDriver::getImplementationName(  ) throw(RuntimeException)
{
    return getImplementationName_Static();
}

//------------------------------------------------------------------
sal_Bool SAL_CALL MozabDriver::supportsService( const ::rtl::OUString& _rServiceName ) throw(RuntimeException)
{
    Sequence< ::rtl::OUString > aSupported(getSupportedServiceNames());
    const ::rtl::OUString* pSupported = aSupported.getConstArray();
    const ::rtl::OUString* pEnd = pSupported + aSupported.getLength();
    for (;pSupported != pEnd && !pSupported->equals(_rServiceName); ++pSupported)
        ;

    return pSupported != pEnd;
}

//------------------------------------------------------------------
Sequence< ::rtl::OUString > SAL_CALL MozabDriver::getSupportedServiceNames(  ) throw(RuntimeException)
{
    return getSupportedServiceNames_Static();
}

// --------------------------------------------------------------------------------
Reference< XConnection > SAL_CALL MozabDriver::connect( const ::rtl::OUString& url, const Sequence< PropertyValue >& info ) throw(SQLException, RuntimeException)
{
    if ( !ensureInit() )
        return NULL;

    if ( ! acceptsURL( url ) )
        return NULL;
    // create a new connection with the given properties and append it to our vector
    Reference< XConnection > xCon;
    if (m_pCreationFunc)
    {
        ::osl::MutexGuard aGuard(m_aMutex);
        //We must make sure we create an com.sun.star.mozilla.MozillaBootstrap brfore call any mozilla codes
        Reference<XInterface> xInstance = m_xMSFactory->createInstance(::rtl::OUString( "com.sun.star.mozilla.MozillaBootstrap") );
        OSL_ENSURE( xInstance.is(), "failed to create instance" );

        OConnection* pCon = reinterpret_cast<OConnection*>((*m_pCreationFunc)(this));
        xCon = pCon;    // important here because otherwise the connection could be deleted inside (refcount goes -> 0)
        pCon->construct(url,info);              // late constructor call which can throw exception and allows a correct dtor call when so
        m_xConnections.push_back(WeakReferenceHelper(*pCon));

    }
    else
    {
        ::connectivity::SharedResources aResources;
        const ::rtl::OUString sError( aResources.getResourceStringWithSubstitution(
                STR_COULD_NOT_LOAD_LIB,
                "$libname$", ::rtl::OUString( SVLIBRARY( "mozabdrv" ) )
             ) );

        ::dbtools::throwGenericSQLException(sError,*this);
    }

    return xCon;
}
// --------------------------------------------------------------------------------
sal_Bool SAL_CALL MozabDriver::acceptsURL( const ::rtl::OUString& url )
        throw(SQLException, RuntimeException)
{
    if ( !ensureInit() )
        return sal_False;

    // here we have to look if we support this url format
    return impl_classifyURL(url) != Unknown;
}
// --------------------------------------------------------------------------------
Sequence< DriverPropertyInfo > SAL_CALL MozabDriver::getPropertyInfo( const ::rtl::OUString& url, const Sequence< PropertyValue >& /*info*/ ) throw(SQLException, RuntimeException)
{
    if ( !ensureInit() )
        return Sequence< DriverPropertyInfo >();

    if ( acceptsURL(url) )
    {
        if ( impl_classifyURL(url) != LDAP )
            return Sequence< DriverPropertyInfo >();

        ::std::vector< DriverPropertyInfo > aDriverInfo;
        aDriverInfo.push_back(DriverPropertyInfo(
                ::rtl::OUString("BaseDN")
                ,::rtl::OUString("Base DN.")
                ,sal_False
                ,::rtl::OUString()
                ,Sequence< ::rtl::OUString >())
                );
        aDriverInfo.push_back(DriverPropertyInfo(
                ::rtl::OUString("MaxRowCount")
                ,::rtl::OUString("Records (max.)")
                ,sal_False
                ,::rtl::OUString("100")
                ,Sequence< ::rtl::OUString >())
                );
        return Sequence< DriverPropertyInfo >(&aDriverInfo[0],aDriverInfo.size());
    }
    ::connectivity::SharedResources aResources;
    const ::rtl::OUString sMessage = aResources.getResourceString(STR_URI_SYNTAX_ERROR);
    ::dbtools::throwGenericSQLException(sMessage ,*this);
    // if you have something special to say return it here :-)
    return Sequence< DriverPropertyInfo >();
}
// --------------------------------------------------------------------------------
sal_Int32 SAL_CALL MozabDriver::getMajorVersion(  ) throw(RuntimeException)
{
    return 1; // depends on you
}
// --------------------------------------------------------------------------------
sal_Int32 SAL_CALL MozabDriver::getMinorVersion(  ) throw(RuntimeException)
{
    return 0; // depends on you
}
// --------------------------------------------------------------------------------
EDriverType MozabDriver::impl_classifyURL( const ::rtl::OUString& url )
{
    // Skip 'sdbc:mozab: part of URL
    //
    sal_Int32 nLen = url.indexOf(':');
    nLen = url.indexOf(':',nLen+1);
    ::rtl::OUString aAddrbookURI(url.copy(nLen+1));
    // Get Scheme
    nLen = aAddrbookURI.indexOf(':');
    ::rtl::OUString aAddrbookScheme;
    if ( nLen == -1 )
    {
        // There isn't any subschema: - but could be just subschema
        if ( !aAddrbookURI.isEmpty() )
            aAddrbookScheme= aAddrbookURI;
        else if(url == ::rtl::OUString("sdbc:address:") )
            return Unknown; // TODO check
        else
            return Unknown;
    }
    else
        aAddrbookScheme = aAddrbookURI.copy(0, nLen);

    struct __scheme_map
    {
        EDriverType eType;
        const sal_Char* pScheme;
    } aSchemeMap[] =
    {
#if defined(WNT)
        { Outlook,          "outlook" },
        { OutlookExpress,   "outlookexp" },
#endif
        { Mozilla,          "mozilla" },
        { ThunderBird,      "thunderbird" },
        { LDAP,             "ldap" }
    };

    for ( size_t i=0; i < sizeof( aSchemeMap ) / sizeof( aSchemeMap[0] ); ++i )
    {
        if ( aAddrbookScheme.compareToAscii( aSchemeMap[i].pScheme ) == 0 )
            return aSchemeMap[i].eType;
    }

    return Unknown;
}

// --------------------------------------------------------------------------------
namespace
{
    template< typename FUNCTION >
    void lcl_getFunctionFromModuleOrUnload( oslModule& _rModule, const sal_Char* _pAsciiSymbolName, FUNCTION& _rFunction )
    {
        _rFunction = NULL;
        if ( _rModule )
        {
            const ::rtl::OUString sSymbolName = ::rtl::OUString::createFromAscii( _pAsciiSymbolName );
            _rFunction = (FUNCTION)( osl_getFunctionSymbol( _rModule, sSymbolName.pData ) );

            if ( !_rFunction )
            {   // did not find the symbol
                OSL_FAIL( ( ::rtl::OString( "lcl_getFunctionFromModuleOrUnload: could not find the symbol " ) + ::rtl::OString( _pAsciiSymbolName ) ).getStr() );
                osl_unloadModule( _rModule );
                _rModule = NULL;
            }
        }
    }
}

// -----------------------------------------------------------------------------
extern "C" { static void SAL_CALL thisModule() {} }

bool MozabDriver::ensureInit()
{
    if ( m_hModule )
        return true;

    OSL_ENSURE(NULL == m_pCreationFunc, "MozabDriver::ensureInit: inconsistence: already have a factory function!");

    const ::rtl::OUString sModuleName(SVLIBRARY( "mozabdrv" ));

    // load the mozabdrv library
    m_hModule = osl_loadModuleRelative(&thisModule, sModuleName.pData, 0);
    OSL_ENSURE(NULL != m_hModule, "MozabDriver::ensureInit: could not load the mozabdrv library!");
    if ( !m_hModule )
        return false;

    OSetMozabServiceFactory pSetFactoryFunc( NULL );

    lcl_getFunctionFromModuleOrUnload( m_hModule, "setMozabServiceFactory",          pSetFactoryFunc   );
    lcl_getFunctionFromModuleOrUnload( m_hModule, "OMozabConnection_CreateInstance", m_pCreationFunc   );

    if ( !m_hModule )
        // one of the symbols did not exist
        return false;

    if ( m_xMSFactory.is() )
    {
        // for purpose of transfer safety, the interface needs to be acuired once
        // (will be release by the callee)
        m_xMSFactory->acquire();
        ( *pSetFactoryFunc )( m_xMSFactory.get() );
    }

    return true;
}
// -----------------------------------------------------------------------------

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Fix debug build<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 <sal/macros.h>
#include "MDriver.hxx"
#include "MConnection.hxx"
#include "connectivity/dbexception.hxx"
#include "resource/mozab_res.hrc"
#include "resource/common_res.hrc"

#include <tools/solar.h>
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::beans;
using namespace com::sun::star::sdbc;
using namespace connectivity::mozab;

namespace connectivity
{
    namespace mozab
    {
        //------------------------------------------------------------------
        ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >  SAL_CALL MozabDriver_CreateInstance(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory) throw( ::com::sun::star::uno::Exception )
        {
            return *(new MozabDriver( _rxFactory ));
        }
    }
}
// --------------------------------------------------------------------------------
MozabDriver::MozabDriver(
    const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory)
    : ODriver_BASE(m_aMutex), m_xMSFactory( _rxFactory )
    ,m_hModule(NULL)
    ,m_pCreationFunc(NULL)
{
}
// -----------------------------------------------------------------------------
MozabDriver::~MozabDriver()
{
}
// --------------------------------------------------------------------------------
void MozabDriver::disposing()
{
    ::osl::MutexGuard aGuard(m_aMutex);

    // when driver will be destroied so all our connections have to be destroied as well
    for (OWeakRefArray::iterator i = m_xConnections.begin(); m_xConnections.end() != i; ++i)
    {
        Reference< XComponent > xComp(i->get(), UNO_QUERY);
        if (xComp.is())
            xComp->dispose();
    }
    m_xConnections.clear();
    connectivity::OWeakRefArray().swap(m_xConnections); // this really clears

    ODriver_BASE::disposing();
    if(m_hModule)
    {
        m_pCreationFunc = NULL;
        osl_unloadModule(m_hModule);
        m_hModule = NULL;
    }
}

// static ServiceInfo
//------------------------------------------------------------------------------
rtl::OUString MozabDriver::getImplementationName_Static(  ) throw(RuntimeException)
{
    return rtl::OUString(MOZAB_DRIVER_IMPL_NAME);
        // this name is referenced in the configuration and in the mozab.xml
        // Please take care when changing it.
}
//------------------------------------------------------------------------------
Sequence< ::rtl::OUString > MozabDriver::getSupportedServiceNames_Static(  ) throw (RuntimeException)
{
    // which service is supported
    // for more information @see com.sun.star.sdbc.Driver
    Sequence< ::rtl::OUString > aSNS( 1 );
    aSNS[0] = ::rtl::OUString( "com.sun.star.sdbc.Driver");
    return aSNS;
}

//------------------------------------------------------------------
::rtl::OUString SAL_CALL MozabDriver::getImplementationName(  ) throw(RuntimeException)
{
    return getImplementationName_Static();
}

//------------------------------------------------------------------
sal_Bool SAL_CALL MozabDriver::supportsService( const ::rtl::OUString& _rServiceName ) throw(RuntimeException)
{
    Sequence< ::rtl::OUString > aSupported(getSupportedServiceNames());
    const ::rtl::OUString* pSupported = aSupported.getConstArray();
    const ::rtl::OUString* pEnd = pSupported + aSupported.getLength();
    for (;pSupported != pEnd && !pSupported->equals(_rServiceName); ++pSupported)
        ;

    return pSupported != pEnd;
}

//------------------------------------------------------------------
Sequence< ::rtl::OUString > SAL_CALL MozabDriver::getSupportedServiceNames(  ) throw(RuntimeException)
{
    return getSupportedServiceNames_Static();
}

// --------------------------------------------------------------------------------
Reference< XConnection > SAL_CALL MozabDriver::connect( const ::rtl::OUString& url, const Sequence< PropertyValue >& info ) throw(SQLException, RuntimeException)
{
    if ( !ensureInit() )
        return NULL;

    if ( ! acceptsURL( url ) )
        return NULL;
    // create a new connection with the given properties and append it to our vector
    Reference< XConnection > xCon;
    if (m_pCreationFunc)
    {
        ::osl::MutexGuard aGuard(m_aMutex);
        //We must make sure we create an com.sun.star.mozilla.MozillaBootstrap brfore call any mozilla codes
        Reference<XInterface> xInstance = m_xMSFactory->createInstance(::rtl::OUString( "com.sun.star.mozilla.MozillaBootstrap") );
        OSL_ENSURE( xInstance.is(), "failed to create instance" );

        OConnection* pCon = reinterpret_cast<OConnection*>((*m_pCreationFunc)(this));
        xCon = pCon;    // important here because otherwise the connection could be deleted inside (refcount goes -> 0)
        pCon->construct(url,info);              // late constructor call which can throw exception and allows a correct dtor call when so
        m_xConnections.push_back(WeakReferenceHelper(*pCon));

    }
    else
    {
        ::connectivity::SharedResources aResources;
        const ::rtl::OUString sError( aResources.getResourceStringWithSubstitution(
                STR_COULD_NOT_LOAD_LIB,
                "$libname$", ::rtl::OUString( SVLIBRARY( "mozabdrv" ) )
             ) );

        ::dbtools::throwGenericSQLException(sError,*this);
    }

    return xCon;
}
// --------------------------------------------------------------------------------
sal_Bool SAL_CALL MozabDriver::acceptsURL( const ::rtl::OUString& url )
        throw(SQLException, RuntimeException)
{
    if ( !ensureInit() )
        return sal_False;

    // here we have to look if we support this url format
    return impl_classifyURL(url) != Unknown;
}
// --------------------------------------------------------------------------------
Sequence< DriverPropertyInfo > SAL_CALL MozabDriver::getPropertyInfo( const ::rtl::OUString& url, const Sequence< PropertyValue >& /*info*/ ) throw(SQLException, RuntimeException)
{
    if ( !ensureInit() )
        return Sequence< DriverPropertyInfo >();

    if ( acceptsURL(url) )
    {
        if ( impl_classifyURL(url) != LDAP )
            return Sequence< DriverPropertyInfo >();

        ::std::vector< DriverPropertyInfo > aDriverInfo;
        aDriverInfo.push_back(DriverPropertyInfo(
                ::rtl::OUString("BaseDN")
                ,::rtl::OUString("Base DN.")
                ,sal_False
                ,::rtl::OUString()
                ,Sequence< ::rtl::OUString >())
                );
        aDriverInfo.push_back(DriverPropertyInfo(
                ::rtl::OUString("MaxRowCount")
                ,::rtl::OUString("Records (max.)")
                ,sal_False
                ,::rtl::OUString("100")
                ,Sequence< ::rtl::OUString >())
                );
        return Sequence< DriverPropertyInfo >(&aDriverInfo[0],aDriverInfo.size());
    }
    ::connectivity::SharedResources aResources;
    const ::rtl::OUString sMessage = aResources.getResourceString(STR_URI_SYNTAX_ERROR);
    ::dbtools::throwGenericSQLException(sMessage ,*this);
    // if you have something special to say return it here :-)
    return Sequence< DriverPropertyInfo >();
}
// --------------------------------------------------------------------------------
sal_Int32 SAL_CALL MozabDriver::getMajorVersion(  ) throw(RuntimeException)
{
    return 1; // depends on you
}
// --------------------------------------------------------------------------------
sal_Int32 SAL_CALL MozabDriver::getMinorVersion(  ) throw(RuntimeException)
{
    return 0; // depends on you
}
// --------------------------------------------------------------------------------
EDriverType MozabDriver::impl_classifyURL( const ::rtl::OUString& url )
{
    // Skip 'sdbc:mozab: part of URL
    //
    sal_Int32 nLen = url.indexOf(':');
    nLen = url.indexOf(':',nLen+1);
    ::rtl::OUString aAddrbookURI(url.copy(nLen+1));
    // Get Scheme
    nLen = aAddrbookURI.indexOf(':');
    ::rtl::OUString aAddrbookScheme;
    if ( nLen == -1 )
    {
        // There isn't any subschema: - but could be just subschema
        if ( !aAddrbookURI.isEmpty() )
            aAddrbookScheme= aAddrbookURI;
        else if(url == ::rtl::OUString("sdbc:address:") )
            return Unknown; // TODO check
        else
            return Unknown;
    }
    else
        aAddrbookScheme = aAddrbookURI.copy(0, nLen);

    struct __scheme_map
    {
        EDriverType eType;
        const sal_Char* pScheme;
    } aSchemeMap[] =
    {
#if defined(WNT)
        { Outlook,          "outlook" },
        { OutlookExpress,   "outlookexp" },
#endif
        { Mozilla,          "mozilla" },
        { ThunderBird,      "thunderbird" },
        { LDAP,             "ldap" }
    };

    for ( size_t i=0; i < sizeof( aSchemeMap ) / sizeof( aSchemeMap[0] ); ++i )
    {
        if ( aAddrbookScheme.compareToAscii( aSchemeMap[i].pScheme ) == 0 )
            return aSchemeMap[i].eType;
    }

    return Unknown;
}

// --------------------------------------------------------------------------------
namespace
{
    template< typename FUNCTION >
    void lcl_getFunctionFromModuleOrUnload( oslModule& _rModule, const sal_Char* _pAsciiSymbolName, FUNCTION& _rFunction )
    {
        _rFunction = NULL;
        if ( _rModule )
        {
            const ::rtl::OUString sSymbolName = ::rtl::OUString::createFromAscii( _pAsciiSymbolName );
            _rFunction = (FUNCTION)( osl_getFunctionSymbol( _rModule, sSymbolName.pData ) );

            if ( !_rFunction )
            {   // did not find the symbol
                rtl::OUStringBuffer aBuf;
                aBuf.append( "lcl_getFunctionFromModuleOrUnload: could not find the symbol " );
                aBuf.append( sSymbolName );
                OSL_FAIL( aBuf.makeStringAndClear().getStr() );
                osl_unloadModule( _rModule );
                _rModule = NULL;
            }
        }
    }
}

// -----------------------------------------------------------------------------
extern "C" { static void SAL_CALL thisModule() {} }

bool MozabDriver::ensureInit()
{
    if ( m_hModule )
        return true;

    OSL_ENSURE(NULL == m_pCreationFunc, "MozabDriver::ensureInit: inconsistence: already have a factory function!");

    const ::rtl::OUString sModuleName(SVLIBRARY( "mozabdrv" ));

    // load the mozabdrv library
    m_hModule = osl_loadModuleRelative(&thisModule, sModuleName.pData, 0);
    OSL_ENSURE(NULL != m_hModule, "MozabDriver::ensureInit: could not load the mozabdrv library!");
    if ( !m_hModule )
        return false;

    OSetMozabServiceFactory pSetFactoryFunc( NULL );

    lcl_getFunctionFromModuleOrUnload( m_hModule, "setMozabServiceFactory",          pSetFactoryFunc   );
    lcl_getFunctionFromModuleOrUnload( m_hModule, "OMozabConnection_CreateInstance", m_pCreationFunc   );

    if ( !m_hModule )
        // one of the symbols did not exist
        return false;

    if ( m_xMSFactory.is() )
    {
        // for purpose of transfer safety, the interface needs to be acuired once
        // (will be release by the callee)
        m_xMSFactory->acquire();
        ( *pSetFactoryFunc )( m_xMSFactory.get() );
    }

    return true;
}
// -----------------------------------------------------------------------------

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