<commit_before>/*************************************************************************
 *
 *  $RCSfile: YTables.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2004-10-22 08:44: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): _______________________________________
 *
 *
 ************************************************************************/

#ifndef CONNECTIVITY_MYSQL_TABLES_HXX
#include "mysql/YTables.hxx"
#endif
#ifndef _CONNECTIVITY_MYSQL_VIEWS_HXX_
#include "mysql/YViews.hxx"
#endif
#ifndef CONNECTIVITY_MYSQL_TABLE_HXX
#include "mysql/YTable.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_
#include <com/sun/star/sdbc/XResultSet.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_COLUMNVALUE_HPP_
#include <com/sun/star/sdbc/ColumnValue.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_PRIVILEGE_HPP_
#include <com/sun/star/sdbcx/Privilege.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_KEYRULE_HPP_
#include <com/sun/star/sdbc/KeyRule.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_KEYTYPE_HPP_
#include <com/sun/star/sdbcx/KeyType.hpp>
#endif
#ifndef CONNECTIVITY_MYSQL_CATALOG_HXX
#include "mysql/YCatalog.hxx"
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef _CONNECTIVITY_DBTOOLS_HXX_
#include "connectivity/dbtools.hxx"
#endif
#ifndef _DBHELPER_DBEXCEPTION_HXX_
#include "connectivity/dbexception.hxx"
#endif
#ifndef _CPPUHELPER_INTERFACECONTAINER_H_
#include <cppuhelper/interfacecontainer.h>
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef CONNECTIVITY_CONNECTION_HXX
#include "TConnection.hxx"
#endif

using namespace ::comphelper;

using namespace ::cppu;
using namespace connectivity::mysql;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
using namespace dbtools;
typedef connectivity::sdbcx::OCollection OCollection_TYPE;

Reference< XNamed > OTables::createObject(const ::rtl::OUString& _rName)
{
    ::rtl::OUString sCatalog,sSchema,sTable;
    ::dbtools::qualifiedNameComponents(m_xMetaData,_rName,sCatalog,sSchema,sTable,::dbtools::eInDataManipulation);

    static const ::rtl::OUString s_sTableTypeView(RTL_CONSTASCII_USTRINGPARAM("VIEW"));
    static const ::rtl::OUString s_sTableTypeTable(RTL_CONSTASCII_USTRINGPARAM("TABLE"));
    static const ::rtl::OUString s_sAll(RTL_CONSTASCII_USTRINGPARAM("%"));

    Sequence< ::rtl::OUString > sTableTypes(3);
    sTableTypes[0] = s_sTableTypeView;
    sTableTypes[1] = s_sTableTypeTable;
    sTableTypes[2] = s_sAll;    // just to be sure to include anything else ....

    Any aCatalog;
    if ( sCatalog.getLength() )
        aCatalog <<= sCatalog;
    Reference< XResultSet > xResult = m_xMetaData->getTables(aCatalog,sSchema,sTable,sTableTypes);

    Reference< XNamed > xRet = NULL;
    if ( xResult.is() )
    {
        Reference< XRow > xRow(xResult,UNO_QUERY);
        if ( xResult->next() ) // there can be only one table with this name
        {
//          Reference<XStatement> xStmt = m_xConnection->createStatement();
//          if ( xStmt.is() )
//          {
//              Reference< XResultSet > xPrivRes = xStmt->executeQuery();
//              Reference< XRow > xPrivRow(xPrivRes,UNO_QUERY);
//              while ( xPrivRes.is() && xPrivRes->next() )
//              {
//                  if ( xPrivRow->getString(1) )
//                  {
//                  }
//              }
//          }
            sal_Int32 nPrivileges = Privilege::DROP         |
                                    Privilege::REFERENCE    |
                                    Privilege::ALTER        |
                                    Privilege::CREATE       |
                                    Privilege::READ         |
                                    Privilege::DELETE       |
                                    Privilege::UPDATE       |
                                    Privilege::INSERT       |
                                    Privilege::SELECT;

            OMySQLTable* pRet = new OMySQLTable( this
                                                ,static_cast<OMySQLCatalog&>(m_rParent).getConnection()
                                                ,sTable
                                                ,xRow->getString(4)
                                                ,xRow->getString(5)
                                                ,sSchema
                                                ,sCatalog
                                                ,nPrivileges);
            xRet = pRet;
        }
        ::comphelper::disposeComponent(xResult);
    }

    return xRet;
}
// -------------------------------------------------------------------------
void OTables::impl_refresh(  ) throw(RuntimeException)
{
    static_cast<OMySQLCatalog&>(m_rParent).refreshTables();
}
// -------------------------------------------------------------------------
void OTables::disposing(void)
{
    m_xMetaData = NULL;
    OCollection::disposing();
}
// -------------------------------------------------------------------------
Reference< XPropertySet > OTables::createEmptyObject()
{
    return new OMySQLTable(this,static_cast<OMySQLCatalog&>(m_rParent).getConnection());
}
// -----------------------------------------------------------------------------
Reference< XNamed > OTables::cloneObject(const Reference< XPropertySet >& _xDescriptor)
{
    Reference< XNamed > xName(_xDescriptor,UNO_QUERY);
    OSL_ENSURE(xName.is(),"Must be a XName interface here !");
    return xName.is() ? createObject(xName->getName()) : Reference< XNamed >();
}
// -------------------------------------------------------------------------
// XAppend
void OTables::appendObject( const Reference< XPropertySet >& descriptor )
{
    ::rtl::OUString aName = getString(descriptor->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME)));
    if(!aName.getLength())
        ::dbtools::throwFunctionSequenceException(static_cast<XTypeProvider*>(this));

    createTable(descriptor);
}
// -------------------------------------------------------------------------
// XDrop
void OTables::dropObject(sal_Int32 _nPos,const ::rtl::OUString _sElementName)
{
    Reference< ::com::sun::star::lang::XUnoTunnel> xTunnel(getObject(_nPos),UNO_QUERY);
    sal_Bool bIsNew = sal_False;
    if(xTunnel.is())
    {
        connectivity::sdbcx::ODescriptor* pTable = (connectivity::sdbcx::ODescriptor*)xTunnel->getSomething(connectivity::sdbcx::ODescriptor::getUnoTunnelImplementationId());
        if(pTable)
            bIsNew = pTable->isNew();
    }
    if (!bIsNew)
    {
        Reference< XConnection > xConnection = static_cast<OMySQLCatalog&>(m_rParent).getConnection();

        ::rtl::OUString sCatalog,sSchema,sTable;
        ::dbtools::qualifiedNameComponents(m_xMetaData,_sElementName,sCatalog,sSchema,sTable,::dbtools::eInDataManipulation);

        ::rtl::OUString aSql = ::rtl::OUString::createFromAscii("DROP ");

        Reference<XPropertySet> xProp(xTunnel,UNO_QUERY);
        sal_Bool bIsView;
        if(bIsView = (xProp.is() && ::comphelper::getString(xProp->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPE))) == ::rtl::OUString::createFromAscii("VIEW"))) // here we have a view
            aSql += ::rtl::OUString::createFromAscii("VIEW ");
        else
            aSql += ::rtl::OUString::createFromAscii("TABLE ");

        ::rtl::OUString sComposedName;
        ::dbtools::composeTableName(m_xMetaData,sCatalog,sSchema,sTable,sComposedName,sal_True,::dbtools::eInDataManipulation);
        aSql += sComposedName;
        Reference< XStatement > xStmt = xConnection->createStatement(  );
        if ( xStmt.is() )
        {
            xStmt->execute(aSql);
            ::comphelper::disposeComponent(xStmt);
        }
        // if no exception was thrown we must delete it from the views
        if ( bIsView )
        {
            OViews* pViews = static_cast<OViews*>(static_cast<OMySQLCatalog&>(m_rParent).getPrivateViews());
            if ( pViews && pViews->hasByName(_sElementName) )
                pViews->dropByNameImpl(_sElementName);
        }
    }
}
// -------------------------------------------------------------------------
void OTables::createTable( const Reference< XPropertySet >& descriptor )
{
    Reference< XConnection > xConnection = static_cast<OMySQLCatalog&>(m_rParent).getConnection();
    ::rtl::OUString aSql = ::dbtools::createSqlCreateTableStatement(descriptor,xConnection);

    Reference< XStatement > xStmt = xConnection->createStatement(  );
    if ( xStmt.is() )
    {
        xStmt->execute(aSql);
        ::comphelper::disposeComponent(xStmt);
    }
}
// -----------------------------------------------------------------------------
void OTables::appendNew(const ::rtl::OUString& _rsNewTable)
{
    insertElement(_rsNewTable,NULL);

    // notify our container listeners
    ContainerEvent aEvent(static_cast<XContainer*>(this), makeAny(_rsNewTable), Any(), Any());
    OInterfaceIteratorHelper aListenerLoop(m_aContainerListeners);
    while (aListenerLoop.hasMoreElements())
        static_cast<XContainerListener*>(aListenerLoop.next())->elementInserted(aEvent);
}
// -----------------------------------------------------------------------------

<commit_msg>INTEGRATION: CWS dba24 (1.5.32); FILE MERGED 2005/02/09 08:07:47 oj 1.5.32.1: #i26950# remove the need for XNamed<commit_after>/*************************************************************************
 *
 *  $RCSfile: YTables.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: vg $ $Date: 2005-03-10 15:31:32 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#ifndef CONNECTIVITY_MYSQL_TABLES_HXX
#include "mysql/YTables.hxx"
#endif
#ifndef _CONNECTIVITY_MYSQL_VIEWS_HXX_
#include "mysql/YViews.hxx"
#endif
#ifndef CONNECTIVITY_MYSQL_TABLE_HXX
#include "mysql/YTable.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_
#include <com/sun/star/sdbc/XResultSet.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_COLUMNVALUE_HPP_
#include <com/sun/star/sdbc/ColumnValue.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_PRIVILEGE_HPP_
#include <com/sun/star/sdbcx/Privilege.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_KEYRULE_HPP_
#include <com/sun/star/sdbc/KeyRule.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_KEYTYPE_HPP_
#include <com/sun/star/sdbcx/KeyType.hpp>
#endif
#ifndef CONNECTIVITY_MYSQL_CATALOG_HXX
#include "mysql/YCatalog.hxx"
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef _CONNECTIVITY_DBTOOLS_HXX_
#include "connectivity/dbtools.hxx"
#endif
#ifndef _DBHELPER_DBEXCEPTION_HXX_
#include "connectivity/dbexception.hxx"
#endif
#ifndef _CPPUHELPER_INTERFACECONTAINER_H_
#include <cppuhelper/interfacecontainer.h>
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef CONNECTIVITY_CONNECTION_HXX
#include "TConnection.hxx"
#endif

using namespace ::comphelper;
using namespace connectivity;
using namespace ::cppu;
using namespace connectivity::mysql;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
using namespace dbtools;
typedef connectivity::sdbcx::OCollection OCollection_TYPE;

sdbcx::ObjectType OTables::createObject(const ::rtl::OUString& _rName)
{
    ::rtl::OUString sCatalog,sSchema,sTable;
    ::dbtools::qualifiedNameComponents(m_xMetaData,_rName,sCatalog,sSchema,sTable,::dbtools::eInDataManipulation);

    static const ::rtl::OUString s_sTableTypeView(RTL_CONSTASCII_USTRINGPARAM("VIEW"));
    static const ::rtl::OUString s_sTableTypeTable(RTL_CONSTASCII_USTRINGPARAM("TABLE"));
    static const ::rtl::OUString s_sAll(RTL_CONSTASCII_USTRINGPARAM("%"));

    Sequence< ::rtl::OUString > sTableTypes(3);
    sTableTypes[0] = s_sTableTypeView;
    sTableTypes[1] = s_sTableTypeTable;
    sTableTypes[2] = s_sAll;    // just to be sure to include anything else ....

    Any aCatalog;
    if ( sCatalog.getLength() )
        aCatalog <<= sCatalog;
    Reference< XResultSet > xResult = m_xMetaData->getTables(aCatalog,sSchema,sTable,sTableTypes);

    sdbcx::ObjectType xRet = NULL;
    if ( xResult.is() )
    {
        Reference< XRow > xRow(xResult,UNO_QUERY);
        if ( xResult->next() ) // there can be only one table with this name
        {
//          Reference<XStatement> xStmt = m_xConnection->createStatement();
//          if ( xStmt.is() )
//          {
//              Reference< XResultSet > xPrivRes = xStmt->executeQuery();
//              Reference< XRow > xPrivRow(xPrivRes,UNO_QUERY);
//              while ( xPrivRes.is() && xPrivRes->next() )
//              {
//                  if ( xPrivRow->getString(1) )
//                  {
//                  }
//              }
//          }
            sal_Int32 nPrivileges = Privilege::DROP         |
                                    Privilege::REFERENCE    |
                                    Privilege::ALTER        |
                                    Privilege::CREATE       |
                                    Privilege::READ         |
                                    Privilege::DELETE       |
                                    Privilege::UPDATE       |
                                    Privilege::INSERT       |
                                    Privilege::SELECT;

            OMySQLTable* pRet = new OMySQLTable( this
                                                ,static_cast<OMySQLCatalog&>(m_rParent).getConnection()
                                                ,sTable
                                                ,xRow->getString(4)
                                                ,xRow->getString(5)
                                                ,sSchema
                                                ,sCatalog
                                                ,nPrivileges);
            xRet = pRet;
        }
        ::comphelper::disposeComponent(xResult);
    }

    return xRet;
}
// -------------------------------------------------------------------------
void OTables::impl_refresh(  ) throw(RuntimeException)
{
    static_cast<OMySQLCatalog&>(m_rParent).refreshTables();
}
// -------------------------------------------------------------------------
void OTables::disposing(void)
{
    m_xMetaData = NULL;
    OCollection::disposing();
}
// -------------------------------------------------------------------------
Reference< XPropertySet > OTables::createEmptyObject()
{
    return new OMySQLTable(this,static_cast<OMySQLCatalog&>(m_rParent).getConnection());
}
// -------------------------------------------------------------------------
// XAppend
void OTables::appendObject( const Reference< XPropertySet >& descriptor )
{
    ::rtl::OUString aName = getString(descriptor->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME)));
    if(!aName.getLength())
        ::dbtools::throwFunctionSequenceException(static_cast<XTypeProvider*>(this));

    createTable(descriptor);
}
// -------------------------------------------------------------------------
// XDrop
void OTables::dropObject(sal_Int32 _nPos,const ::rtl::OUString _sElementName)
{
    Reference< ::com::sun::star::lang::XUnoTunnel> xTunnel(getObject(_nPos),UNO_QUERY);
    sal_Bool bIsNew = sal_False;
    if(xTunnel.is())
    {
        connectivity::sdbcx::ODescriptor* pTable = (connectivity::sdbcx::ODescriptor*)xTunnel->getSomething(connectivity::sdbcx::ODescriptor::getUnoTunnelImplementationId());
        if(pTable)
            bIsNew = pTable->isNew();
    }
    if (!bIsNew)
    {
        Reference< XConnection > xConnection = static_cast<OMySQLCatalog&>(m_rParent).getConnection();

        ::rtl::OUString sCatalog,sSchema,sTable;
        ::dbtools::qualifiedNameComponents(m_xMetaData,_sElementName,sCatalog,sSchema,sTable,::dbtools::eInDataManipulation);

        ::rtl::OUString aSql = ::rtl::OUString::createFromAscii("DROP ");

        Reference<XPropertySet> xProp(xTunnel,UNO_QUERY);
        sal_Bool bIsView;
        if(bIsView = (xProp.is() && ::comphelper::getString(xProp->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPE))) == ::rtl::OUString::createFromAscii("VIEW"))) // here we have a view
            aSql += ::rtl::OUString::createFromAscii("VIEW ");
        else
            aSql += ::rtl::OUString::createFromAscii("TABLE ");

        ::rtl::OUString sComposedName;
        ::dbtools::composeTableName(m_xMetaData,sCatalog,sSchema,sTable,sComposedName,sal_True,::dbtools::eInDataManipulation);
        aSql += sComposedName;
        Reference< XStatement > xStmt = xConnection->createStatement(  );
        if ( xStmt.is() )
        {
            xStmt->execute(aSql);
            ::comphelper::disposeComponent(xStmt);
        }
        // if no exception was thrown we must delete it from the views
        if ( bIsView )
        {
            OViews* pViews = static_cast<OViews*>(static_cast<OMySQLCatalog&>(m_rParent).getPrivateViews());
            if ( pViews && pViews->hasByName(_sElementName) )
                pViews->dropByNameImpl(_sElementName);
        }
    }
}
// -------------------------------------------------------------------------
void OTables::createTable( const Reference< XPropertySet >& descriptor )
{
    Reference< XConnection > xConnection = static_cast<OMySQLCatalog&>(m_rParent).getConnection();
    ::rtl::OUString aSql = ::dbtools::createSqlCreateTableStatement(descriptor,xConnection);

    Reference< XStatement > xStmt = xConnection->createStatement(  );
    if ( xStmt.is() )
    {
        xStmt->execute(aSql);
        ::comphelper::disposeComponent(xStmt);
    }
}
// -----------------------------------------------------------------------------
void OTables::appendNew(const ::rtl::OUString& _rsNewTable)
{
    insertElement(_rsNewTable,NULL);

    // notify our container listeners
    ContainerEvent aEvent(static_cast<XContainer*>(this), makeAny(_rsNewTable), Any(), Any());
    OInterfaceIteratorHelper aListenerLoop(m_aContainerListeners);
    while (aListenerLoop.hasMoreElements())
        static_cast<XContainerListener*>(aListenerLoop.next())->elementInserted(aEvent);
}
// -----------------------------------------------------------------------------
::rtl::OUString OTables::getNameForObject(const sdbcx::ObjectType& _xObject)
{
    OSL_ENSURE(_xObject.is(),"OTables::getNameForObject: Object is NULL!");
    return ::dbtools::composeTableName(m_xMetaData,_xObject,sal_False,::dbtools::eInDataManipulation);
}
// -----------------------------------------------------------------------------

<|endoftext|>


<commit_before>/*
 * trie_buffer.hpp
 *
 *  Created on: Feb 17, 2015
 *      Author: masha
 */

#ifndef INCLUDE_POOL_BUFFER_HPP_
#define INCLUDE_POOL_BUFFER_HPP_

#include "abaptr.hpp"

#include <atomic>
#include <cassert>
#include <algorithm>

namespace lfds
{
namespace
{
template<class T>
struct pool_node
{
    typedef pool_node<T> this_type;
    this_type* m_next;
    T m_data;

    static this_type* recover(T* p)
    {
        static constexpr int offset =
                reinterpret_cast<char*>(&reinterpret_cast<this_type*>(0)->m_data)
                        - reinterpret_cast<char*>(0);

        return reinterpret_cast<this_type*>(reinterpret_cast<char*>(p) - offset);
    }
};

template<class T, class Allocator>
struct pool_chunk
{
    typedef pool_chunk<T, Allocator> this_type;
    typedef pool_node<T> node_type;
    typedef std::size_t size_type;
    typedef T value_type;
    typedef typename Allocator::template rebind<value_type>::other allocator_type;

    this_type* m_next;
    size_type m_size;
    node_type m_data[1];  //-- trailing array of nodes

    pool_chunk(size_type size) :
            m_next(), m_size(size)
    {
    }

    void construct(allocator_type & a)
    {
        for (size_type i = 0; i < m_size; ++i)
        {
            a.construct(&m_data[i]);
        }
    }
    void destroy(allocator_type & a)
    {
        for (size_type i = 0; i < m_size; ++i)
        {
            a.destroy(&m_data[i]);
        }
    }

    static size_type getByteSize(size_type chunkSize)
    {
        return sizeof(this_type) + sizeof(node_type) * (chunkSize - 1);
    }
};

template<class T>
inline void atomic_push(std::atomic<T*> & list, T* head, T* tail)
{
    bool success;
    do
    {
        tail->m_next = list.load(std::memory_order_relaxed);
        success = list.compare_exchange_weak(tail->m_next, tail->m_next,
                std::memory_order_relaxed, std::memory_order_relaxed);
    } while (!success);
}

template<class T>
inline void atomic_push(std::atomic<T*> & list, T* val)
{
    atomic_push(list, val, val);
}

template<class T>
inline void atomic_push(volatile abaptr<T> & list, T* head, T* tail)
{
    bool success;
    do
    {
        abaptr<T> old_ptr = list;
        tail->m_next = old_ptr.m_ptr;
        abaptr<T> new_ptr =
        { head, old_ptr.m_counter + 1 };
        success = list.atomic_cas(old_ptr, new_ptr);
    } while (!success);
}

template<class T>
inline void atomic_push(volatile abaptr<T> & list, T* val)
{
    atomic_push(list, val, val);
}

}

template<class T, class Allocator>
class pool_buffer
{
public:
    typedef pool_buffer<T, Allocator> this_type;
    typedef T value_type;

    typedef pool_chunk<value_type, Allocator> chunk_type;

    typedef typename Allocator::template rebind<char>::other byte_allocator_type;
    typedef typename Allocator::template rebind<chunk_type>::other chunk_allocator_type;
    typedef typename chunk_type::node_type node_type;
    typedef typename chunk_type::allocator_type node_allocator_type;
    typedef std::size_t size_type;

    static constexpr unsigned int MIN_SIZE = 32;

private:
    pool_buffer(const this_type&) = delete;
    this_type& operator=(const this_type&) = delete;

public:
    pool_buffer(size_type initialCapacity) :
            m_reserved(0), m_freeNodes(nullptr), m_chunks(nullptr), m_byte_allocator(), m_node_allocator(), m_chunk_allocator()
    {
        m_freeNodes.m_ptr = reserve(initialCapacity).first;
    }
    ~pool_buffer()
    {
        chunk_type* chunk = m_chunks.load(std::memory_order_relaxed);
        while (chunk)
        {
            chunk_type* next = chunk->m_next;
            deallocate_chunk(chunk);
            chunk = next;
        }
    }

    T* allocate()
    {
        // pop node
        bool success = false;
        node_type* node;

        do
        {
            abaptr<node_type> old_val = m_freeNodes;
            node = old_val.m_ptr;
            if (!node)
            {
                auto headtail = reserve(size());

                node = headtail.first;
                node_type* head = node->m_next;
                node_type* tail = headtail.second;
                atomic_push(m_freeNodes, head, tail);
                break;
            }
            else
            {
                abaptr<node_type> new_val =
                { node->m_next, old_val.m_counter + 1 };
                success = m_freeNodes.atomic_cas(old_val, new_val);
            }
        } while (!success);
        return &node->m_data;
    }
    void deallocate(T* p)
    {
        node_type* node = node_type::recover(p);
        atomic_push(m_freeNodes, node);
    }
    size_type size() const
    {
        return m_reserved.load(std::memory_order_relaxed);
    }
private:
    std::pair<node_type*, node_type*> reserve(size_type size)
    {
        static constexpr size_type min_size = MIN_SIZE;
        size_type chunk_size = std::max(size, min_size);
        chunk_type* chunk = allocate_chunk(chunk_size);

        node_type* data = chunk->m_data;
        node_type* head = data;
        head->m_next = nullptr;
        for (size_type i = 1; i < chunk->m_size; ++i)
        {
            node_type* node = &data[i];
            node->m_next = head;
            head = node;
        }
        atomic_push(m_chunks, chunk);
        m_reserved.fetch_add(chunk_size, std::memory_order_relaxed);
        return std::make_pair(head, data);
    }

    chunk_type* allocate_chunk(size_type chunk_size)
    {
        size_type byte_size = chunk_type::getByteSize(chunk_size);
        char* raw_ptr = m_byte_allocator.allocate(byte_size);
        chunk_type* chunk = reinterpret_cast<chunk_type*>(raw_ptr);
        m_chunk_allocator.construct(chunk, chunk_size);
        chunk->construct(m_node_allocator);
        return chunk;
    }

    void deallocate_chunk(chunk_type* chunk)
    {
        size_type byte_size = chunk_type::getByteSize(chunk->m_size);
        char* raw_ptr = reinterpret_cast<char*>(chunk);

        chunk->destroy(m_node_allocator);
        m_chunk_allocator.destroy(chunk);

        m_byte_allocator.deallocate(raw_ptr, byte_size);
    }
private:
    std::atomic<size_type> m_reserved;
    volatile abaptr<node_type> m_freeNodes;
    std::atomic<chunk_type*> m_chunks;
    byte_allocator_type m_byte_allocator;
    node_allocator_type m_node_allocator;
    chunk_allocator_type m_chunk_allocator;
};
}

#endif /* INCLUDE_POOL_BUFFER_HPP_ */
<commit_msg>Warning fixed<commit_after>/*
 * trie_buffer.hpp
 *
 *  Created on: Feb 17, 2015
 *      Author: masha
 */

#ifndef INCLUDE_POOL_BUFFER_HPP_
#define INCLUDE_POOL_BUFFER_HPP_

#include "abaptr.hpp"

#include <atomic>
#include <cassert>
#include <cstddef>
#include <algorithm>

namespace lfds
{
namespace
{
template<class T>
struct pool_node
{
    typedef pool_node<T> this_type;
    this_type* m_next;
    T m_data;

    static this_type* recover(T* p)
    {
        static constexpr int offset = offsetof(this_type, m_data);
        return reinterpret_cast<this_type*>(reinterpret_cast<char*>(p) - offset);
    }
};

template<class T, class Allocator>
struct pool_chunk
{
    typedef pool_chunk<T, Allocator> this_type;
    typedef pool_node<T> node_type;
    typedef std::size_t size_type;
    typedef T value_type;
    typedef typename Allocator::template rebind<value_type>::other allocator_type;

    this_type* m_next;
    size_type m_size;
    node_type m_data[1];  //-- trailing array of nodes

    pool_chunk(size_type size) :
            m_next(), m_size(size)
    {
    }

    void construct(allocator_type & a)
    {
        for (size_type i = 0; i < m_size; ++i)
        {
            a.construct(&m_data[i]);
        }
    }
    void destroy(allocator_type & a)
    {
        for (size_type i = 0; i < m_size; ++i)
        {
            a.destroy(&m_data[i]);
        }
    }

    static size_type getByteSize(size_type chunkSize)
    {
        return sizeof(this_type) + sizeof(node_type) * (chunkSize - 1);
    }
};

template<class T>
inline void atomic_push(std::atomic<T*> & list, T* head, T* tail)
{
    bool success;
    do
    {
        tail->m_next = list.load(std::memory_order_relaxed);
        success = list.compare_exchange_weak(tail->m_next, tail->m_next,
                std::memory_order_relaxed, std::memory_order_relaxed);
    } while (!success);
}

template<class T>
inline void atomic_push(std::atomic<T*> & list, T* val)
{
    atomic_push(list, val, val);
}

template<class T>
inline void atomic_push(volatile abaptr<T> & list, T* head, T* tail)
{
    bool success;
    do
    {
        abaptr<T> old_ptr = list;
        tail->m_next = old_ptr.m_ptr;
        abaptr<T> new_ptr =
        { head, old_ptr.m_counter + 1 };
        success = list.atomic_cas(old_ptr, new_ptr);
    } while (!success);
}

template<class T>
inline void atomic_push(volatile abaptr<T> & list, T* val)
{
    atomic_push(list, val, val);
}

}

template<class T, class Allocator>
class pool_buffer
{
public:
    typedef pool_buffer<T, Allocator> this_type;
    typedef T value_type;

    typedef pool_chunk<value_type, Allocator> chunk_type;

    typedef typename Allocator::template rebind<char>::other byte_allocator_type;
    typedef typename Allocator::template rebind<chunk_type>::other chunk_allocator_type;
    typedef typename chunk_type::node_type node_type;
    typedef typename chunk_type::allocator_type node_allocator_type;
    typedef std::size_t size_type;

    static constexpr unsigned int MIN_SIZE = 32;

private:
    pool_buffer(const this_type&) = delete;
    this_type& operator=(const this_type&) = delete;

public:
    pool_buffer(size_type initialCapacity) :
            m_reserved(0), m_freeNodes(nullptr), m_chunks(nullptr), m_byte_allocator(), m_node_allocator(), m_chunk_allocator()
    {
        m_freeNodes.m_ptr = reserve(initialCapacity).first;
    }
    ~pool_buffer()
    {
        chunk_type* chunk = m_chunks.load(std::memory_order_relaxed);
        while (chunk)
        {
            chunk_type* next = chunk->m_next;
            deallocate_chunk(chunk);
            chunk = next;
        }
    }

    T* allocate()
    {
        // pop node
        bool success = false;
        node_type* node;

        do
        {
            abaptr<node_type> old_val = m_freeNodes;
            node = old_val.m_ptr;
            if (!node)
            {
                auto headtail = reserve(size());

                node = headtail.first;
                node_type* head = node->m_next;
                node_type* tail = headtail.second;
                atomic_push(m_freeNodes, head, tail);
                break;
            }
            else
            {
                abaptr<node_type> new_val =
                { node->m_next, old_val.m_counter + 1 };
                success = m_freeNodes.atomic_cas(old_val, new_val);
            }
        } while (!success);
        return &node->m_data;
    }
    void deallocate(T* p)
    {
        node_type* node = node_type::recover(p);
        atomic_push(m_freeNodes, node);
    }
    size_type size() const
    {
        return m_reserved.load(std::memory_order_relaxed);
    }
private:
    std::pair<node_type*, node_type*> reserve(size_type size)
    {
        static constexpr size_type min_size = MIN_SIZE;
        size_type chunk_size = std::max(size, min_size);
        chunk_type* chunk = allocate_chunk(chunk_size);

        node_type* data = chunk->m_data;
        node_type* head = data;
        head->m_next = nullptr;
        for (size_type i = 1; i < chunk->m_size; ++i)
        {
            node_type* node = &data[i];
            node->m_next = head;
            head = node;
        }
        atomic_push(m_chunks, chunk);
        m_reserved.fetch_add(chunk_size, std::memory_order_relaxed);
        return std::make_pair(head, data);
    }

    chunk_type* allocate_chunk(size_type chunk_size)
    {
        size_type byte_size = chunk_type::getByteSize(chunk_size);
        char* raw_ptr = m_byte_allocator.allocate(byte_size);
        chunk_type* chunk = reinterpret_cast<chunk_type*>(raw_ptr);
        m_chunk_allocator.construct(chunk, chunk_size);
        chunk->construct(m_node_allocator);
        return chunk;
    }

    void deallocate_chunk(chunk_type* chunk)
    {
        size_type byte_size = chunk_type::getByteSize(chunk->m_size);
        char* raw_ptr = reinterpret_cast<char*>(chunk);

        chunk->destroy(m_node_allocator);
        m_chunk_allocator.destroy(chunk);

        m_byte_allocator.deallocate(raw_ptr, byte_size);
    }
private:
    std::atomic<size_type> m_reserved;
    volatile abaptr<node_type> m_freeNodes;
    std::atomic<chunk_type*> m_chunks;
    byte_allocator_type m_byte_allocator;
    node_allocator_type m_node_allocator;
    chunk_allocator_type m_chunk_allocator;
};
}

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


<commit_before>#ifndef __RANK_FILTER__
#define __RANK_FILTER__

#include <deque>
#include <cassert>
#include <functional>
#include <iostream>
#include <iterator>

#include <boost/array.hpp>
#include <boost/container/set.hpp>
#include <boost/container/node_allocator.hpp>
#include <boost/math/special_functions/round.hpp>
#include <boost/static_assert.hpp>
#include <boost/type_traits.hpp>

namespace rank_filter
{

template<class I1,
         class I2>
inline void lineRankOrderFilter1D(const I1& src_begin, const I1& src_end,
        I2& dest_begin, I2& dest_end,
        size_t half_length, double rank)
{
    // Types in use.
    typedef typename std::iterator_traits<I1>::value_type T1;
    typedef typename std::iterator_traits<I2>::value_type T2;
    typedef typename std::iterator_traits<I1>::difference_type I1_diff_t;
    typedef typename std::iterator_traits<I2>::difference_type I2_diff_t;

    // Establish common types to work with source and destination values.
    BOOST_STATIC_ASSERT((boost::is_same<T1, T2>::value));
    typedef T1 T;
    typedef typename boost::common_type<I1_diff_t, I2_diff_t>::type I_diff_t;

    // Define container types that will be used.
    typedef boost::container::multiset< T,
            std::less<T>,
            boost::container::node_allocator<T>,
            boost::container::tree_assoc_options< boost::container::tree_type<boost::container::scapegoat_tree> >::type> multiset;
    typedef std::deque< typename multiset::iterator > deque;

    // Lengths.
    const I_diff_t src_size = std::distance(src_begin, src_end);
    const I_diff_t dest_size = std::distance(dest_begin, dest_end);

    // Ensure the result will fit.
    assert(src_size <= dest_size);

    // Window length cannot exceed input data with reflection.
    assert((half_length + 1) <= src_size);

    // Rank must be in the range 0 to 1.
    assert((0 <= rank) && (rank <= 1));

    // The position of the window.
    I_diff_t window_begin = 0;

    // Find window offset corresponding to this rank.
    const I_diff_t rank_pos = static_cast<I_diff_t>(boost::math::round(rank * (2 * half_length)));
    typename multiset::iterator rank_point;

    // Track values in window both in sorted and sequential order.
    multiset sorted_window;
    deque window_iters(2 * half_length + 1);

    // Get the initial sorted window.
    // Include the reflection.
    for (I_diff_t j = 0; j < half_length; j++)
    {
        window_iters[j] = sorted_window.insert(src_begin[window_begin + half_length - j]);
    }
    for (I_diff_t j = half_length; j < (2 * half_length + 1); j++)
    {
        window_iters[j] = sorted_window.insert(src_begin[window_begin + j - half_length]);
    }

    rank_point = sorted_window.begin();
    for (I_diff_t i = 0; i < rank_pos; i++)
    {
        rank_point++;
    }

    typename multiset::iterator prev_iter;
    T prev_value;
    T next_value;
    while ( window_begin < src_size )
    {
        dest_begin[window_begin] = *rank_point;

        prev_iter = window_iters.front();
        prev_value = *prev_iter;
        window_iters.pop_front();

        window_begin++;

        if ( window_begin == src_size )
        {
            next_value = prev_value;
        }
        else if ( window_begin < (src_size - half_length) )
        {
            next_value = src_begin[window_begin + half_length];
        }
        else
        {
            next_value = *(window_iters[(2 * (src_size - (window_begin + 1)))]);
        }

        if ( ( *rank_point < prev_value ) && ( *rank_point <= next_value ) )
        {
            sorted_window.erase(prev_iter);
            window_iters.push_back(sorted_window.insert(next_value));
        }
        else if ( ( *rank_point >= prev_value ) && ( *rank_point > next_value ) )
        {
            if ( rank_point == prev_iter )
            {
                window_iters.push_back(sorted_window.insert(next_value));
                rank_point--;

                sorted_window.erase(prev_iter);
            }
            else
            {
                sorted_window.erase(prev_iter);
                window_iters.push_back(sorted_window.insert(next_value));
            }
        }
        else if ( ( *rank_point < prev_value ) && ( *rank_point > next_value ) )
        {
            sorted_window.erase(prev_iter);
            window_iters.push_back(sorted_window.insert(next_value));

            rank_point--;
        }
        else if ( ( *rank_point >= prev_value ) && ( *rank_point <= next_value ) )
        {
            if (rank_point == prev_iter)
            {
                window_iters.push_back(sorted_window.insert(next_value));
                rank_point++;

                sorted_window.erase(prev_iter);
            }
            else
            {
                sorted_window.erase(prev_iter);
                window_iters.push_back(sorted_window.insert(next_value));

                rank_point++;
            }
        }
    }
}

}

namespace std
{
    template <class T, size_t N>
    ostream& operator<<(ostream& out, const boost::array<T, N>& that)
    {
        out << "{ ";
        for (unsigned int i = 0; i < (N - 1); i++)
        {
            out << that[i] << ", ";
        }
        out << that[N - 1] << " }";

        return(out);
    }
}

#endif //__RANK_FILTER__
<commit_msg>Adjust window rank comment<commit_after>#ifndef __RANK_FILTER__
#define __RANK_FILTER__

#include <deque>
#include <cassert>
#include <functional>
#include <iostream>
#include <iterator>

#include <boost/array.hpp>
#include <boost/container/set.hpp>
#include <boost/container/node_allocator.hpp>
#include <boost/math/special_functions/round.hpp>
#include <boost/static_assert.hpp>
#include <boost/type_traits.hpp>

namespace rank_filter
{

template<class I1,
         class I2>
inline void lineRankOrderFilter1D(const I1& src_begin, const I1& src_end,
        I2& dest_begin, I2& dest_end,
        size_t half_length, double rank)
{
    // Types in use.
    typedef typename std::iterator_traits<I1>::value_type T1;
    typedef typename std::iterator_traits<I2>::value_type T2;
    typedef typename std::iterator_traits<I1>::difference_type I1_diff_t;
    typedef typename std::iterator_traits<I2>::difference_type I2_diff_t;

    // Establish common types to work with source and destination values.
    BOOST_STATIC_ASSERT((boost::is_same<T1, T2>::value));
    typedef T1 T;
    typedef typename boost::common_type<I1_diff_t, I2_diff_t>::type I_diff_t;

    // Define container types that will be used.
    typedef boost::container::multiset< T,
            std::less<T>,
            boost::container::node_allocator<T>,
            boost::container::tree_assoc_options< boost::container::tree_type<boost::container::scapegoat_tree> >::type> multiset;
    typedef std::deque< typename multiset::iterator > deque;

    // Lengths.
    const I_diff_t src_size = std::distance(src_begin, src_end);
    const I_diff_t dest_size = std::distance(dest_begin, dest_end);

    // Ensure the result will fit.
    assert(src_size <= dest_size);

    // Window length cannot exceed input data with reflection.
    assert((half_length + 1) <= src_size);

    // Rank must be in the range 0 to 1.
    assert((0 <= rank) && (rank <= 1));

    // The position of the window.
    I_diff_t window_begin = 0;

    // Window position corresponding to this rank.
    const I_diff_t rank_pos = static_cast<I_diff_t>(boost::math::round(rank * (2 * half_length)));
    typename multiset::iterator rank_point;

    // Track values in window both in sorted and sequential order.
    multiset sorted_window;
    deque window_iters(2 * half_length + 1);

    // Get the initial sorted window.
    // Include the reflection.
    for (I_diff_t j = 0; j < half_length; j++)
    {
        window_iters[j] = sorted_window.insert(src_begin[window_begin + half_length - j]);
    }
    for (I_diff_t j = half_length; j < (2 * half_length + 1); j++)
    {
        window_iters[j] = sorted_window.insert(src_begin[window_begin + j - half_length]);
    }

    rank_point = sorted_window.begin();
    for (I_diff_t i = 0; i < rank_pos; i++)
    {
        rank_point++;
    }

    typename multiset::iterator prev_iter;
    T prev_value;
    T next_value;
    while ( window_begin < src_size )
    {
        dest_begin[window_begin] = *rank_point;

        prev_iter = window_iters.front();
        prev_value = *prev_iter;
        window_iters.pop_front();

        window_begin++;

        if ( window_begin == src_size )
        {
            next_value = prev_value;
        }
        else if ( window_begin < (src_size - half_length) )
        {
            next_value = src_begin[window_begin + half_length];
        }
        else
        {
            next_value = *(window_iters[(2 * (src_size - (window_begin + 1)))]);
        }

        if ( ( *rank_point < prev_value ) && ( *rank_point <= next_value ) )
        {
            sorted_window.erase(prev_iter);
            window_iters.push_back(sorted_window.insert(next_value));
        }
        else if ( ( *rank_point >= prev_value ) && ( *rank_point > next_value ) )
        {
            if ( rank_point == prev_iter )
            {
                window_iters.push_back(sorted_window.insert(next_value));
                rank_point--;

                sorted_window.erase(prev_iter);
            }
            else
            {
                sorted_window.erase(prev_iter);
                window_iters.push_back(sorted_window.insert(next_value));
            }
        }
        else if ( ( *rank_point < prev_value ) && ( *rank_point > next_value ) )
        {
            sorted_window.erase(prev_iter);
            window_iters.push_back(sorted_window.insert(next_value));

            rank_point--;
        }
        else if ( ( *rank_point >= prev_value ) && ( *rank_point <= next_value ) )
        {
            if (rank_point == prev_iter)
            {
                window_iters.push_back(sorted_window.insert(next_value));
                rank_point++;

                sorted_window.erase(prev_iter);
            }
            else
            {
                sorted_window.erase(prev_iter);
                window_iters.push_back(sorted_window.insert(next_value));

                rank_point++;
            }
        }
    }
}

}

namespace std
{
    template <class T, size_t N>
    ostream& operator<<(ostream& out, const boost::array<T, N>& that)
    {
        out << "{ ";
        for (unsigned int i = 0; i < (N - 1); i++)
        {
            out << that[i] << ", ";
        }
        out << that[N - 1] << " }";

        return(out);
    }
}

#endif //__RANK_FILTER__
<|endoftext|>


<commit_before>/*
 * Copyright 2016-2017 deepstreamHub GmbH
 *
 * 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.
 */
#ifndef DEEPSTREAM_SCOPEGUARD_HPP
#define DEEPSTREAM_SCOPEGUARD_HPP

#include <functional>

#include <boost/preprocessor/cat.hpp>

#include <use.hpp>

namespace deepstream
{
	// A. Alexandrescu, P. Marginean:
	// "Generic: Change the Way You Write Exception-Safe Code -- Forever"
	// Dr. Dobbs Journal, 2000
	// www.drdobbs.com/cpp/generic-change-the-way-you-write-excepti/184403758
	struct ScopeGuard
	{
		typedef std::function<void(void)> FunT;

		ScopeGuard(FunT f) : f_(f) {};
		~ScopeGuard() { f_(); }

		FunT f_;
	};
}

#define DEEPSTREAM_ON_EXIT(...) \
	const ::deepstream::ScopeGuard BOOST_PP_CAT(deepstream_guard,__LINE__)(__VA_ARGS__); \
	::deepstream::use( BOOST_PP_CAT(deepstream_guard, __LINE__) )

#endif
<commit_msg>Src: fix a Clang warning<commit_after>/*
 * Copyright 2016-2017 deepstreamHub GmbH
 *
 * 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.
 */
#ifndef DEEPSTREAM_SCOPEGUARD_HPP
#define DEEPSTREAM_SCOPEGUARD_HPP

#include <functional>

#include <boost/preprocessor/cat.hpp>

#include <use.hpp>

namespace deepstream
{
	// A. Alexandrescu, P. Marginean:
	// "Generic: Change the Way You Write Exception-Safe Code -- Forever"
	// Dr. Dobbs Journal, 2000
	// www.drdobbs.com/cpp/generic-change-the-way-you-write-excepti/184403758
	struct ScopeGuard
	{
		typedef std::function<void(void)> FunT;

		ScopeGuard(FunT f) : f_(f) {}
		~ScopeGuard() { f_(); }

		FunT f_;
	};
}

#define DEEPSTREAM_ON_EXIT(...) \
	const ::deepstream::ScopeGuard BOOST_PP_CAT(deepstream_guard,__LINE__)(__VA_ARGS__); \
	::deepstream::use( BOOST_PP_CAT(deepstream_guard, __LINE__) )

#endif
<|endoftext|>


<commit_before><commit_msg>These function members does not need to be virtual<commit_after><|endoftext|>


<commit_before>#pragma once

#include <xcb/xcb.h>

#include "common.hpp"
#include "config.hpp"
#include "utils/socket.hpp"
#include "utils/string.hpp"

LEMONBUDDY_NS

namespace bspwm_util {
  struct payload;
  using subscriber_t = unique_ptr<socket_util::unix_connection>;
  using payload_t = unique_ptr<payload>;

  /**
   * bspwm payload
   */
  struct payload {
    char data[BUFSIZ]{'\0'};
    size_t len = 0;
  };

  /**
   * Get path to the bspwm socket by the following order
   *
   * 1. Value of environment variable BSPWM_SOCKET
   * 2. Value built from the bspwm socket path template
   * 3. Value of the macro BSPWM_SOCKET_PATH
   */
  string get_socket_path() {
    string env_path{read_env("BSPWM_SOCKET")};
    if (!env_path.empty())
      return env_path;

    struct sockaddr_un sa;
    char* tpl_path = nullptr;
    char* host = nullptr;
    int dsp = 0;
    int scr = 0;

    if (xcb_parse_display(nullptr, &host, &dsp, &scr) != 0)
      std::snprintf(tpl_path, sizeof(sa.sun_path), "/tmp/bspwm%s_%i_%i-socket", host, dsp, scr);

    if (tpl_path != nullptr)
      return tpl_path;

    return BSPWM_SOCKET_PATH;
  }

  /**
   * Generate a payload object with properly formatted data
   * ready to be sent to the bspwm ipc controller
   */
  unique_ptr<payload> make_payload(string cmd) {
    auto pl = make_unique<payload>();
    auto size = sizeof(pl->data);
    int offset = 0;
    int chars = 0;

    for (auto&& word : string_util::split(cmd, ' ')) {
      chars = snprintf(pl->data + offset, size - offset, "%s%c", word.c_str(), 0);
      pl->len += chars;
      offset += chars;
    }

    return pl;
  }

  /**
   * Create a connection and subscribe to events
   * on the bspwm socket
   *
   * Example usage:
   * @code cpp
   *   auto ipc = bspwm_util::make_subscriber();
   *
   *   while (!ipc->poll(POLLHUP, 0)) {
   *     ssize_t bytes_received = 0;
   *     auto data = ipc->receive(BUFSIZ-1, bytes_received, 0);
   *     std::cout << data << std::endl;
   *   }
   * @endcode
   */
  subscriber_t make_subscriber() {
    auto conn = socket_util::make_unix_connection(BSPWM_SOCKET_PATH);
    auto payload = make_payload("subscribe report");
    if (conn->send(payload->data, payload->len, 0) == 0)
      throw system_error("Failed to initialize subscriber");
    return conn;
  }
}

LEMONBUDDY_NS_END
<commit_msg>refactor(bspwm): Use defined socket path for ipc connections<commit_after>#pragma once

#include <xcb/xcb.h>

#include "common.hpp"
#include "config.hpp"
#include "utils/socket.hpp"
#include "utils/string.hpp"

LEMONBUDDY_NS

namespace bspwm_util {
  struct payload;
  using connection_t = unique_ptr<socket_util::unix_connection>;
  using payload_t = unique_ptr<payload>;

  /**
   * bspwm payload
   */
  struct payload {
    char data[BUFSIZ]{'\0'};
    size_t len = 0;
  };

  /**
   * Get path to the bspwm socket by the following order
   *
   * 1. Value of environment variable BSPWM_SOCKET
   * 2. Value built from the bspwm socket path template
   * 3. Value of the macro BSPWM_SOCKET_PATH
   */
  string get_socket_path() {
    string env_path;

    if ((env_path = read_env("BSPWM_SOCKET")).empty() == false)
      return env_path;

    struct sockaddr_un sa;
    char* host = nullptr;
    int dsp = 0;
    int scr = 0;

    if (xcb_parse_display(nullptr, &host, &dsp, &scr) == 0)
      return BSPWM_SOCKET_PATH;

    snprintf(sa.sun_path, sizeof(sa.sun_path), "/tmp/bspwm%s_%i_%i-socket", host, dsp, scr);

    return sa.sun_path;
  }

  /**
   * Generate a payload object with properly formatted data
   * ready to be sent to the bspwm ipc controller
   */
  unique_ptr<payload> make_payload(string cmd) {
    auto pl = make_unique<payload>();
    auto size = sizeof(pl->data);
    int offset = 0;
    int chars = 0;

    for (auto&& word : string_util::split(cmd, ' ')) {
      chars = snprintf(pl->data + offset, size - offset, "%s%c", word.c_str(), 0);
      pl->len += chars;
      offset += chars;
    }

    return pl;
  }

  /**
   * Create an ipc socket connection
   *
   * Example usage:
   * @code cpp
   *   auto ipc = bspwm_util::make_connection();
   *   ipc->send(bspwm_util::make_payload("desktop -f eDP-1:^1"));
   * @endcode
   */
  connection_t make_connection() {
    return socket_util::make_unix_connection(get_socket_path());
  }

  /**
   * Create a connection and subscribe to events
   * on the bspwm socket
   *
   * Example usage:
   * @code cpp
   *   auto ipc = bspwm_util::make_subscriber();
   *
   *   while (!ipc->poll(POLLHUP, 0)) {
   *     ssize_t bytes_received = 0;
   *     auto data = ipc->receive(BUFSIZ-1, bytes_received, 0);
   *     std::cout << data << std::endl;
   *   }
   * @endcode
   */
  connection_t make_subscriber() {
    auto conn = make_connection();
    auto payload = make_payload("subscribe report");
    if (conn->send(payload->data, payload->len, 0) == 0)
      throw system_error("Failed to initialize subscriber");
    return conn;
  }
}

LEMONBUDDY_NS_END
<|endoftext|>


<commit_before>/************************************************************************/
/*                                                                      */
/*               Copyright 2001-2002 by Gunnar Kedenburg                */
/*       Cognitive Systems Group, University of Hamburg, Germany        */
/*                                                                      */
/*    This file is part of the VIGRA computer vision library.           */
/*    You may use, modify, and distribute this software according       */
/*    to the terms stated in the LICENSE file included in               */
/*    the VIGRA distribution.                                           */
/*                                                                      */
/*    The VIGRA Website is                                              */
/*        http://kogs-www.informatik.uni-hamburg.de/~koethe/vigra/      */
/*    Please direct questions, bug reports, and contributions to        */
/*        koethe@informatik.uni-hamburg.de                              */
/*                                                                      */
/*  THIS SOFTWARE IS PROVIDED AS IS AND WITHOUT ANY EXPRESS OR          */
/*  IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED      */
/*  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */
/*                                                                      */
/************************************************************************/

#ifndef VIGRA_CODEC_HXX
#define VIGRA_CODEC_HXX

#include <memory>
#include <string>
#include <vector>

// possible pixel types:
// "undefined", "UINT8", "INT16", "INT32", "FLOAT", "DOUBLE"

// possible compression types:
// "undefined", "RLE", "LZW", "LOSSLESS", "JPEG"

// possible file types:
// "undefined", "TIFF", "VIFF", "JPEG", "PNG", "PNM", "BMP", "SUN", "XPM"

// possible name extensions:
// "undefined", "tif", "tiff", "jpg", "jpeg", "png", "pnm", "bmp", "sun",
// "xpm" (also capital forms)

namespace vigra
{
    // codec description

    struct CodecDesc
    {
        std::string fileType;
        std::vector<std::string> pixelTypes;
        std::vector<std::string> compressionTypes;
        std::vector<std::vector<char> > magicStrings;
        std::vector<std::string> fileExtensions;
        std::vector<int> bandNumbers;
    };

    // Decoder and Encoder are pure virtual types that define a common
    // interface for all image file formats impex supports.

    struct Decoder
    {
        virtual ~Decoder() {};
        virtual void init( const std::string & ) = 0;
        virtual void close() = 0;
        virtual void abort() = 0;

        virtual std::string getFileType() const = 0;
        virtual std::string getPixelType() const = 0;

        virtual unsigned int getWidth() const = 0;
        virtual unsigned int getHeight() const = 0;
        virtual unsigned int getNumBands() const = 0;
        virtual unsigned int getOffset() const = 0;

        virtual const void * currentScanlineOfBand( unsigned int ) const = 0;
        virtual void nextScanline() = 0;
    };

    struct Encoder
    {
        virtual ~Encoder() {};
        virtual void init( const std::string & ) = 0;
        virtual void close() = 0;
        virtual void abort() = 0;

        virtual std::string getFileType() const = 0;
        virtual unsigned int getOffset() const = 0;

        virtual void setWidth( unsigned int ) = 0;
        virtual void setHeight( unsigned int ) = 0;
        virtual void setNumBands( unsigned int ) = 0;
        virtual void setCompressionType( const std::string &, int = -1 ) = 0;
        virtual void setPixelType( const std::string & ) = 0;
        virtual void finalizeSettings() = 0;

        virtual void * currentScanlineOfBand( unsigned int ) = 0;
        virtual void nextScanline() = 0;
    };

    // codec factory for registration at the codec manager

    struct CodecFactory
    {
        virtual CodecDesc getCodecDesc() const = 0;
        virtual std::auto_ptr<Decoder> getDecoder() const = 0;
        virtual std::auto_ptr<Encoder> getEncoder() const = 0;
    };

    // factory functions to encapsulate the codec managers
    //
    // codecs are selected according to the following order:
    // - (if provided) the FileType
    // - (in case of decoders) the file's magic string
    // - the filename extension

    std::auto_ptr<Decoder>
    getDecoder( const std::string &, const std::string & = "undefined" );

    std::auto_ptr<Encoder>
    getEncoder( const std::string &, const std::string & = "undefined" );

    // functions to query the capabilities of certain codecs

    std::vector<std::string> queryCodecPixelTypes( const std::string & );

    bool isPixelTypeSupported( const std::string &, const std::string & );

    bool isBandNumberSupported( const std::string &, int bands );
}

#endif // VIGRA_CODEC_HXX
<commit_msg>added TIFFNoLZWException<commit_after>/************************************************************************/
/*                                                                      */
/*               Copyright 2001-2002 by Gunnar Kedenburg                */
/*       Cognitive Systems Group, University of Hamburg, Germany        */
/*                                                                      */
/*    This file is part of the VIGRA computer vision library.           */
/*    You may use, modify, and distribute this software according       */
/*    to the terms stated in the LICENSE file included in               */
/*    the VIGRA distribution.                                           */
/*                                                                      */
/*    The VIGRA Website is                                              */
/*        http://kogs-www.informatik.uni-hamburg.de/~koethe/vigra/      */
/*    Please direct questions, bug reports, and contributions to        */
/*        koethe@informatik.uni-hamburg.de                              */
/*                                                                      */
/*  THIS SOFTWARE IS PROVIDED AS IS AND WITHOUT ANY EXPRESS OR          */
/*  IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED      */
/*  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */
/*                                                                      */
/************************************************************************/

#ifndef VIGRA_CODEC_HXX
#define VIGRA_CODEC_HXX

#include <memory>
#include <string>
#include <vector>

// possible pixel types:
// "undefined", "UINT8", "INT16", "INT32", "FLOAT", "DOUBLE"

// possible compression types:
// "undefined", "RLE", "LZW", "LOSSLESS", "JPEG"

// possible file types:
// "undefined", "TIFF", "VIFF", "JPEG", "PNG", "PNM", "BMP", "SUN", "XPM"

// possible name extensions:
// "undefined", "tif", "tiff", "jpg", "jpeg", "png", "pnm", "bmp", "sun",
// "xpm" (also capital forms)

namespace vigra
{
    // codec description

    struct CodecDesc
    {
        std::string fileType;
        std::vector<std::string> pixelTypes;
        std::vector<std::string> compressionTypes;
        std::vector<std::vector<char> > magicStrings;
        std::vector<std::string> fileExtensions;
        std::vector<int> bandNumbers;
    };

    // Decoder and Encoder are pure virtual types that define a common
    // interface for all image file formats impex supports.

    struct Decoder
    {
        virtual ~Decoder() {};
        virtual void init( const std::string & ) = 0;
        virtual void close() = 0;
        virtual void abort() = 0;

        virtual std::string getFileType() const = 0;
        virtual std::string getPixelType() const = 0;

        virtual unsigned int getWidth() const = 0;
        virtual unsigned int getHeight() const = 0;
        virtual unsigned int getNumBands() const = 0;
        virtual unsigned int getOffset() const = 0;

        virtual const void * currentScanlineOfBand( unsigned int ) const = 0;
        virtual void nextScanline() = 0;
    };

    struct Encoder
    {
        virtual ~Encoder() {};
        virtual void init( const std::string & ) = 0;
        virtual void close() = 0;
        virtual void abort() = 0;

        virtual std::string getFileType() const = 0;
        virtual unsigned int getOffset() const = 0;

        virtual void setWidth( unsigned int ) = 0;
        virtual void setHeight( unsigned int ) = 0;
        virtual void setNumBands( unsigned int ) = 0;
        virtual void setCompressionType( const std::string &, int = -1 ) = 0;
        virtual void setPixelType( const std::string & ) = 0;
        virtual void finalizeSettings() = 0;

        virtual void * currentScanlineOfBand( unsigned int ) = 0;
        virtual void nextScanline() = 0;

        struct TIFFNoLZWException {};
    };

    // codec factory for registration at the codec manager

    struct CodecFactory
    {
        virtual CodecDesc getCodecDesc() const = 0;
        virtual std::auto_ptr<Decoder> getDecoder() const = 0;
        virtual std::auto_ptr<Encoder> getEncoder() const = 0;
    };

    // factory functions to encapsulate the codec managers
    //
    // codecs are selected according to the following order:
    // - (if provided) the FileType
    // - (in case of decoders) the file's magic string
    // - the filename extension

    std::auto_ptr<Decoder>
    getDecoder( const std::string &, const std::string & = "undefined" );

    std::auto_ptr<Encoder>
    getEncoder( const std::string &, const std::string & = "undefined" );

    // functions to query the capabilities of certain codecs

    std::vector<std::string> queryCodecPixelTypes( const std::string & );

    bool isPixelTypeSupported( const std::string &, const std::string & );

    bool isBandNumberSupported( const std::string &, int bands );
}

#endif // VIGRA_CODEC_HXX
<|endoftext|>


<commit_before>#include <iostream>
#include <filesystem>
#include <vector>
#include <map>
#include <string>
#include <fstream>

using namespace std;

#if (__cplusplus >= 201703L && (!defined(__GNUC__) || (__GNUC__*100+__GNUC_MINOR__) >= 800))
#include <filesystem>
namespace fs = std::filesystem;
#define USE_FILESYSTEM
#elif !defined(__MINGW32__) && !defined(__ANDROID__) && (!defined(__GNUC__) || (__GNUC__*100+__GNUC_MINOR__) >= 503)
#define USE_FILESYSTEM
#ifdef WIN32
#include <filesystem>
namespace fs = std::experimental::filesystem;
#else
#include <experimental/filesystem>
namespace fs = std::experimental::filesystem;
#endif
#else
//for mac
#include <filesystem>
namespace fs = std::__fs::filesystem;
#endif

enum class Platform {
    platform_windows,    // platform_ prefix to avoid #define subsitutions on linux
    platform_osx,
    platform_linux,
};

constexpr Platform buildPlatform =
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__)
Platform::platform_windows
#elif __APPLE__
#include <TargetConditionals.h>
    #if TARGET_OS_MAC
Platform::platform_osx
    #endif
#elif __linux__
Platform::platform_linux
#endif
; // error here: platform not detected from supported list

bool build = false;
bool setup = false;
bool removeUnusedPorts = false;
bool noPkgConfig = false;
fs::path portsFile;
fs::path sdkRootPath;
fs::path patchPath;
string triplet;

map<string, string> ports;
map<string, fs::path> patches;

fs::path initialDir = fs::current_path();
fs::path vcpkgDir = fs::current_path() / "vcpkg";
fs::path cloneDir = fs::current_path() / "vcpkg_clone";

string platformToString(Platform p);
bool readCommandLine(int argc, char* argv[]);
void execute(string command);

int main(int argc, char* argv[])
try
{
    if (readCommandLine(argc, argv))
    {
        if (setup)
        {
            if (!fs::is_directory("vcpkg"))
            {
                execute("git clone https://github.com/microsoft/vcpkg.git");
                execute("git clone --progress -v vcpkg vcpkg_clone");
                fs::current_path("vcpkg");
                #ifdef WIN32
                    execute(".\\bootstrap-vcpkg.bat -disableMetrics");
                #else
                    execute("./bootstrap-vcpkg.sh -disableMetrics");
                #endif
            }
            else
            {
                fs::current_path("vcpkg");
            }

            if (fs::exists(sdkRootPath / "contrib" / "cmake" / "vcpkg_extra_triplets" / (triplet + ".cmake")))
            {
                if (fs::exists(vcpkgDir / "triplets" / (triplet + ".cmake")))
                {
                    fs::remove(vcpkgDir / "triplets" / (triplet + ".cmake"));
                }
                cout << "Copying triplet from SDK: " << triplet << endl;
                fs::copy(sdkRootPath / "contrib" / "cmake" / "vcpkg_extra_triplets" / (triplet+".cmake"), vcpkgDir / "triplets" / (triplet + ".cmake"));
            }
            else if (!fs::exists(vcpkgDir / "triplets" / (triplet + ".cmake")))
            {
                cout << "triplet not found in the SDK or in vcpkg: " << triplet << endl;
                exit(1);
            }

            for (auto portPair : ports)
            {
                const string& portname = portPair.first;
                const string& portversion = portPair.second;

                if (fs::is_directory(fs::path("ports") / portname))
                {
                    cout << "Removing " << (vcpkgDir / "ports" / portname).u8string() << endl;
                    fs::remove_all(vcpkgDir / "ports" / portname);
                }
                if (portversion.size() == 40)
                {
                    fs::current_path(cloneDir);
                    execute("git checkout --quiet " + portversion);
                    cout << "Copying port for " << portname << " from vcpkg commit " << portversion << endl;
                    fs::copy(cloneDir / "ports" / portname, vcpkgDir / "ports" / portname, fs::copy_options::recursive);
                    fs::current_path(vcpkgDir);

                    auto patch = patches.find(portname);
                    if (patch != patches.end()) {
                        cout << "Applying patch " << patch->second.u8string() << " for port " << portname << "\n";
                        execute("git apply " + (patchPath / patch->second).u8string());
                    }
                }
                else
                {
                    cout << "Copying port for " << portname << " from SDK customized port " << portversion << endl;
                    fs::copy(sdkRootPath / "contrib" / "cmake" / "vcpkg_extra_ports" / portname / portversion, vcpkgDir / "ports" / portname, fs::copy_options::recursive);
                }
            }

            if (removeUnusedPorts)
            {
                for (auto dir = fs::directory_iterator(vcpkgDir / "ports"); dir != fs::directory_iterator(); ++dir)
                {
                    if (ports.find(dir->path().filename().u8string()) == ports.end())
                    {
                        fs::remove_all(dir->path());
                    }
                }
            }

            if (noPkgConfig)
            {
                cout << "Performing no-op substitution of vcpkg_fixup_pkgconfig and PKGCONFIG to skip pkgconfig integration/checks\n";
                ofstream vcpkg_fixup_pkgconfig(vcpkgDir / "scripts" / "cmake" / "vcpkg_fixup_pkgconfig.cmake", std::ios::trunc);
                if (!vcpkg_fixup_pkgconfig)
                {
                    cout << "Could not open vcpkg script file to suppress pkgconfig\n";
                    return 1;
                }

                vcpkg_fixup_pkgconfig <<
                "function(vcpkg_fixup_pkgconfig)\n"
                "endfunction()\n"
                "set(PKGCONFIG \":\")\n"; // i.e., use no-op : operator
            }

        }
        else if (build)
        {

            if (!fs::is_directory("vcpkg"))
            {
                cout << "This command should be run from just outside 'vcpkg' folder - maybe it is not set up?" << endl;
                return 1;
            }
            else
            {
                fs::current_path("vcpkg");
            }

            for (auto portPair : ports)
            {
                #ifdef WIN32
                    execute("vcpkg install --triplet " + triplet + " " + portPair.first);
                #else
                    execute("./vcpkg install --triplet " + triplet + " " + portPair.first);
                #endif
            }
        }
    }

    return 0;
}
catch (exception& e)
{
    cout << "exception: " << e.what() << endl;
    return 1;
}

string platformToString(Platform p)
{
    switch (p) {
        case Platform::platform_windows:
        return "windows";
        case Platform::platform_osx:
        return "osx";
        case Platform::platform_linux:
        return "linux";
        default:
        throw std::logic_error("Unhandled platform enumerator");
    }
}

void execute(string command)
{
    cout << "Executing: " << command << endl;
    int result = system(command.c_str());
    if (result != 0)
    {
        cout << "Command failed with result code " << result << " ( command was " << command << ")" <<endl;
        exit(1);
    }
}

bool showSyntax()
{
    cout << "build3rdParty --setup [--removeunusedports] [--nopkgconfig] --ports <ports override file> --triplet <triplet> --sdkroot <path>" << endl;
    cout << "build3rdParty --build --ports <ports override file> --triplet <triplet>" << endl;
    return false;
}

bool readCommandLine(int argc, char* argv[])
{
    if (argc <= 1) return showSyntax();

    std::vector<char*> myargv1(argv + 1, argv + argc);
    std::vector<char*> myargv2;

    for (auto it = myargv1.begin(); it != myargv1.end(); ++it)
    {
        if (std::string(*it) == "--ports")
        {
            if (++it == myargv1.end()) return showSyntax();
            portsFile = *it;
        }
        else if (std::string(*it) == "--triplet")
        {
            if (++it == myargv1.end()) return showSyntax();
            triplet = *it;
        }
        else if (std::string(*it) == "--sdkroot")
        {
            if (++it == myargv1.end()) return showSyntax();
            sdkRootPath = *it;
        }
        else if (std::string(*it) == "--setup")
        {
            setup = true;
        }
        else if (std::string(*it) == "--removeunusedports" && setup)
        {
            removeUnusedPorts = true;
        }
        else if (std::string(*it) == "--nopkgconfig" && setup)
        {
            noPkgConfig = true;
        }
        else if (std::string(*it) == "--build")
        {
            build = true;
        }
        else
        {
            myargv2.push_back(*it);
        }
    }

    if (!myargv2.empty())
    {
        cout << "unknown parameter: " << myargv2[0] << endl;
        return false;
    }

    if (!(setup || build) || portsFile.empty() || triplet.empty())
    {
        return showSyntax();
    }

    if (setup && sdkRootPath.empty())
    {
        return showSyntax();
    }

    patchPath = sdkRootPath / "contrib" / "cmake" / "vcpkg_patches";

    ifstream portsIn(portsFile.string().c_str());
    while (portsIn)
    {
        string s;
        getline(portsIn, s);

        // remove comments
        auto hashpos = s.find("#");
        if (hashpos != string::npos) s.erase(hashpos);

        // remove whitespace
        while (!s.empty() && (s.front() == ' ' || s.front() == '\t')) s.erase(0, 1);
        while (!s.empty() && (s.back() == ' ' || s.back() == '\t')) s.pop_back();
        if (s.empty()) continue;

        // check if port should be skipped for this platform
        if (s.find(" ") != string::npos)
        {
            string platformTest = s.substr(s.find_last_of(' ') + 1);
            s.erase(s.find_first_of(' '));
            if (!platformTest.empty() && platformTest[0] == '!')
            {
                if (platformTest.substr(1) == platformToString(buildPlatform))
                {
                    cout << "Skipping " << s << " because " << platformTest <<"\n";
                    continue;
                }
            }
            else
            {
                if (platformTest != platformToString(buildPlatform))
                {
                    cout << "Skipping " << s << " because " << platformTest << "\n";
                    continue;
                }
            }
        }

        // if not, extract the exclude expressions so we don't have to worry about them
        s = s.substr(0, s.find("!"));

        // extract port/version map
        auto slashpos = s.find("/");
        if (slashpos == string::npos)
        {
            cout << "bad port: " << s << endl;
            return 1;
        }
        string portname = s.substr(0, slashpos);

        auto colonpos = s.find(':');
        string portversion = s.substr(slashpos + 1, colonpos - (slashpos + 1));

        auto existing = ports.find(portname);
        if (existing != ports.end() && existing->second != portversion)
        {
            cout << "conflicting port versions: " << portname << " " << existing->second << " " << portversion << endl;
            return 1;
        }
        ports[portname] = portversion;

        if (build) continue;

        if (colonpos != string::npos)
        {
            fs::path patch = s.substr(colonpos + 1);
            auto existingPatch = patches.find(patch.u8string());
            if (existingPatch != patches.end() && existingPatch->second != patch)
            {
                cout << "Conflicting patch files: " << patch << " and " << existingPatch->second << " for " << portname << "\n";
                return 1;
            }
            if (!fs::exists(patchPath / patch))
            {
                cout << "Nonexistent patch " << patch << " for " << portname << ", patches must be in " << patchPath.u8string() << "\n";
            }
            cout << "Got patch " << patch << " for " << portname << "\n";
            patches[portname] = patch;
        }
    }

    return true;
}
<commit_msg>fix typo in check for existing patch<commit_after>#include <iostream>
#include <filesystem>
#include <vector>
#include <map>
#include <string>
#include <fstream>

using namespace std;

#if (__cplusplus >= 201703L && (!defined(__GNUC__) || (__GNUC__*100+__GNUC_MINOR__) >= 800))
#include <filesystem>
namespace fs = std::filesystem;
#define USE_FILESYSTEM
#elif !defined(__MINGW32__) && !defined(__ANDROID__) && (!defined(__GNUC__) || (__GNUC__*100+__GNUC_MINOR__) >= 503)
#define USE_FILESYSTEM
#ifdef WIN32
#include <filesystem>
namespace fs = std::experimental::filesystem;
#else
#include <experimental/filesystem>
namespace fs = std::experimental::filesystem;
#endif
#else
//for mac
#include <filesystem>
namespace fs = std::__fs::filesystem;
#endif

enum class Platform {
    platform_windows,    // platform_ prefix to avoid #define subsitutions on linux
    platform_osx,
    platform_linux,
};

constexpr Platform buildPlatform =
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__)
Platform::platform_windows
#elif __APPLE__
#include <TargetConditionals.h>
    #if TARGET_OS_MAC
Platform::platform_osx
    #endif
#elif __linux__
Platform::platform_linux
#endif
; // error here: platform not detected from supported list

bool build = false;
bool setup = false;
bool removeUnusedPorts = false;
bool noPkgConfig = false;
fs::path portsFile;
fs::path sdkRootPath;
fs::path patchPath;
string triplet;

map<string, string> ports;
map<string, fs::path> patches;

fs::path initialDir = fs::current_path();
fs::path vcpkgDir = fs::current_path() / "vcpkg";
fs::path cloneDir = fs::current_path() / "vcpkg_clone";

string platformToString(Platform p);
bool readCommandLine(int argc, char* argv[]);
void execute(string command);

int main(int argc, char* argv[])
try
{
    if (readCommandLine(argc, argv))
    {
        if (setup)
        {
            if (!fs::is_directory("vcpkg"))
            {
                execute("git clone https://github.com/microsoft/vcpkg.git");
                execute("git clone --progress -v vcpkg vcpkg_clone");
                fs::current_path("vcpkg");
                #ifdef WIN32
                    execute(".\\bootstrap-vcpkg.bat -disableMetrics");
                #else
                    execute("./bootstrap-vcpkg.sh -disableMetrics");
                #endif
            }
            else
            {
                fs::current_path("vcpkg");
            }

            if (fs::exists(sdkRootPath / "contrib" / "cmake" / "vcpkg_extra_triplets" / (triplet + ".cmake")))
            {
                if (fs::exists(vcpkgDir / "triplets" / (triplet + ".cmake")))
                {
                    fs::remove(vcpkgDir / "triplets" / (triplet + ".cmake"));
                }
                cout << "Copying triplet from SDK: " << triplet << endl;
                fs::copy(sdkRootPath / "contrib" / "cmake" / "vcpkg_extra_triplets" / (triplet+".cmake"), vcpkgDir / "triplets" / (triplet + ".cmake"));
            }
            else if (!fs::exists(vcpkgDir / "triplets" / (triplet + ".cmake")))
            {
                cout << "triplet not found in the SDK or in vcpkg: " << triplet << endl;
                exit(1);
            }

            for (auto portPair : ports)
            {
                const string& portname = portPair.first;
                const string& portversion = portPair.second;

                if (fs::is_directory(fs::path("ports") / portname))
                {
                    cout << "Removing " << (vcpkgDir / "ports" / portname).u8string() << endl;
                    fs::remove_all(vcpkgDir / "ports" / portname);
                }
                if (portversion.size() == 40)
                {
                    fs::current_path(cloneDir);
                    execute("git checkout --quiet " + portversion);
                    cout << "Copying port for " << portname << " from vcpkg commit " << portversion << endl;
                    fs::copy(cloneDir / "ports" / portname, vcpkgDir / "ports" / portname, fs::copy_options::recursive);
                    fs::current_path(vcpkgDir);

                    auto patch = patches.find(portname);
                    if (patch != patches.end()) {
                        cout << "Applying patch " << patch->second.u8string() << " for port " << portname << "\n";
                        execute("git apply " + (patchPath / patch->second).u8string());
                    }
                }
                else
                {
                    cout << "Copying port for " << portname << " from SDK customized port " << portversion << endl;
                    fs::copy(sdkRootPath / "contrib" / "cmake" / "vcpkg_extra_ports" / portname / portversion, vcpkgDir / "ports" / portname, fs::copy_options::recursive);
                }
            }

            if (removeUnusedPorts)
            {
                for (auto dir = fs::directory_iterator(vcpkgDir / "ports"); dir != fs::directory_iterator(); ++dir)
                {
                    if (ports.find(dir->path().filename().u8string()) == ports.end())
                    {
                        fs::remove_all(dir->path());
                    }
                }
            }

            if (noPkgConfig)
            {
                cout << "Performing no-op substitution of vcpkg_fixup_pkgconfig and PKGCONFIG to skip pkgconfig integration/checks\n";
                ofstream vcpkg_fixup_pkgconfig(vcpkgDir / "scripts" / "cmake" / "vcpkg_fixup_pkgconfig.cmake", std::ios::trunc);
                if (!vcpkg_fixup_pkgconfig)
                {
                    cout << "Could not open vcpkg script file to suppress pkgconfig\n";
                    return 1;
                }

                vcpkg_fixup_pkgconfig <<
                "function(vcpkg_fixup_pkgconfig)\n"
                "endfunction()\n"
                "set(PKGCONFIG \":\")\n"; // i.e., use no-op : operator
            }

        }
        else if (build)
        {

            if (!fs::is_directory("vcpkg"))
            {
                cout << "This command should be run from just outside 'vcpkg' folder - maybe it is not set up?" << endl;
                return 1;
            }
            else
            {
                fs::current_path("vcpkg");
            }

            for (auto portPair : ports)
            {
                #ifdef WIN32
                    execute("vcpkg install --triplet " + triplet + " " + portPair.first);
                #else
                    execute("./vcpkg install --triplet " + triplet + " " + portPair.first);
                #endif
            }
        }
    }

    return 0;
}
catch (exception& e)
{
    cout << "exception: " << e.what() << endl;
    return 1;
}

string platformToString(Platform p)
{
    switch (p) {
        case Platform::platform_windows:
        return "windows";
        case Platform::platform_osx:
        return "osx";
        case Platform::platform_linux:
        return "linux";
        default:
        throw std::logic_error("Unhandled platform enumerator");
    }
}

void execute(string command)
{
    cout << "Executing: " << command << endl;
    int result = system(command.c_str());
    if (result != 0)
    {
        cout << "Command failed with result code " << result << " ( command was " << command << ")" <<endl;
        exit(1);
    }
}

bool showSyntax()
{
    cout << "build3rdParty --setup [--removeunusedports] [--nopkgconfig] --ports <ports override file> --triplet <triplet> --sdkroot <path>" << endl;
    cout << "build3rdParty --build --ports <ports override file> --triplet <triplet>" << endl;
    return false;
}

bool readCommandLine(int argc, char* argv[])
{
    if (argc <= 1) return showSyntax();

    std::vector<char*> myargv1(argv + 1, argv + argc);
    std::vector<char*> myargv2;

    for (auto it = myargv1.begin(); it != myargv1.end(); ++it)
    {
        if (std::string(*it) == "--ports")
        {
            if (++it == myargv1.end()) return showSyntax();
            portsFile = *it;
        }
        else if (std::string(*it) == "--triplet")
        {
            if (++it == myargv1.end()) return showSyntax();
            triplet = *it;
        }
        else if (std::string(*it) == "--sdkroot")
        {
            if (++it == myargv1.end()) return showSyntax();
            sdkRootPath = *it;
        }
        else if (std::string(*it) == "--setup")
        {
            setup = true;
        }
        else if (std::string(*it) == "--removeunusedports" && setup)
        {
            removeUnusedPorts = true;
        }
        else if (std::string(*it) == "--nopkgconfig" && setup)
        {
            noPkgConfig = true;
        }
        else if (std::string(*it) == "--build")
        {
            build = true;
        }
        else
        {
            myargv2.push_back(*it);
        }
    }

    if (!myargv2.empty())
    {
        cout << "unknown parameter: " << myargv2[0] << endl;
        return false;
    }

    if (!(setup || build) || portsFile.empty() || triplet.empty())
    {
        return showSyntax();
    }

    if (setup && sdkRootPath.empty())
    {
        return showSyntax();
    }

    patchPath = sdkRootPath / "contrib" / "cmake" / "vcpkg_patches";

    ifstream portsIn(portsFile.string().c_str());
    while (portsIn)
    {
        string s;
        getline(portsIn, s);

        // remove comments
        auto hashpos = s.find("#");
        if (hashpos != string::npos) s.erase(hashpos);

        // remove whitespace
        while (!s.empty() && (s.front() == ' ' || s.front() == '\t')) s.erase(0, 1);
        while (!s.empty() && (s.back() == ' ' || s.back() == '\t')) s.pop_back();
        if (s.empty()) continue;

        // check if port should be skipped for this platform
        if (s.find(" ") != string::npos)
        {
            string platformTest = s.substr(s.find_last_of(' ') + 1);
            s.erase(s.find_first_of(' '));
            if (!platformTest.empty() && platformTest[0] == '!')
            {
                if (platformTest.substr(1) == platformToString(buildPlatform))
                {
                    cout << "Skipping " << s << " because " << platformTest <<"\n";
                    continue;
                }
            }
            else
            {
                if (platformTest != platformToString(buildPlatform))
                {
                    cout << "Skipping " << s << " because " << platformTest << "\n";
                    continue;
                }
            }
        }

        // if not, extract the exclude expressions so we don't have to worry about them
        s = s.substr(0, s.find("!"));

        // extract port/version map
        auto slashpos = s.find("/");
        if (slashpos == string::npos)
        {
            cout << "bad port: " << s << endl;
            return 1;
        }
        string portname = s.substr(0, slashpos);

        auto colonpos = s.find(':');
        string portversion = s.substr(slashpos + 1, colonpos - (slashpos + 1));

        auto existing = ports.find(portname);
        if (existing != ports.end() && existing->second != portversion)
        {
            cout << "conflicting port versions: " << portname << " " << existing->second << " " << portversion << endl;
            return 1;
        }
        ports[portname] = portversion;

        if (build) continue;

        if (colonpos != string::npos)
        {
            fs::path patch = s.substr(colonpos + 1);
            auto existingPatch = patches.find(portname);
            if (existingPatch != patches.end() && existingPatch->second != patch)
            {
                cout << "Conflicting patch files: " << patch << " and " << existingPatch->second << " for " << portname << "\n";
                return 1;
            }
            if (!fs::exists(patchPath / patch))
            {
                cout << "Nonexistent patch " << patch << " for " << portname << ", patches must be in " << patchPath.u8string() << "\n";
            }
            cout << "Got patch " << patch << " for " << portname << "\n";
            patches[portname] = patch;
        }
    }

    return true;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: ik_singleton.hxx,v $
 *
 *  $Revision: 1.1 $
 *
 *  last change: $Author: np $ $Date: 2002-11-01 17:12:04 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#ifndef ARY_IDL_IK_SINGLETON_HXX
#define ARY_IDL_IK_SINGLETON_HXX

// USED SERVICES
    // BASE CLASSES
#include <ary/idl/ik_ce.hxx>
    // COMPONENTS
    // PARAMETERS

namespace ary
{
namespace idl
{

namespace ifc_singleton
{

using ifc_ce::Dyn_CeIterator;
using ifc_ce::DocText;

struct attr: public ifc_ce::attr
{
    static Type_id      AssociatedService(
                            const CodeEntity &  i_ce );
};

struct xref : public ifc_ce::xref
{
};

struct doc : public ifc_ce::doc
{
};

}   // namespace ifc_singleton

}   // namespace idl
}   // namespace ary

#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.1.132); FILE MERGED 2005/09/05 13:09:27 rt 1.1.132.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ik_singleton.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 16:17:13 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef ARY_IDL_IK_SINGLETON_HXX
#define ARY_IDL_IK_SINGLETON_HXX

// USED SERVICES
    // BASE CLASSES
#include <ary/idl/ik_ce.hxx>
    // COMPONENTS
    // PARAMETERS

namespace ary
{
namespace idl
{

namespace ifc_singleton
{

using ifc_ce::Dyn_CeIterator;
using ifc_ce::DocText;

struct attr: public ifc_ce::attr
{
    static Type_id      AssociatedService(
                            const CodeEntity &  i_ce );
};

struct xref : public ifc_ce::xref
{
};

struct doc : public ifc_ce::doc
{
};

}   // namespace ifc_singleton

}   // namespace idl
}   // namespace ary

#endif
<|endoftext|>