<commit_before>/*************************************************************************
 *
 *  $RCSfile: providerfactory.cxx,v $
 *
 *  $Revision: 1.21 $
 *
 *  last change: $Author: hr $ $Date: 2003-03-19 16:19:23 $
 *
 *  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 EXPRESS 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): _______________________________________
 *
 *
 ************************************************************************/
#include <stdio.h>

#include "providerfactory.hxx"

#ifndef CONFIGMGR_API_FACTORY_HXX_
#include "confapifactory.hxx"
#endif
#ifndef CONFIGMGR_BOOTSTRAP_HXX_
#include "bootstrap.hxx"
#endif
#ifndef CONFIGMGR_API_PROVIDERWRAPPER_HXX_
#include "providerwrapper.hxx"
#endif

#ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_
#include <com/sun/star/lang/IllegalArgumentException.hpp>
#endif
#ifndef _COM_SUN_STAR_CONFIGURATION_CANNOTLOADCONFIGURATIONEXCEPTION_HPP_
#include <com/sun/star/configuration/CannotLoadConfigurationException.hpp>
#endif

#ifndef _CPPUHELPER_EXC_HLP_HXX_
#include <cppuhelper/exc_hlp.hxx>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif

#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _RTL_LOGFILE_HXX_
#include <rtl/logfile.hxx>
#endif

//---------------------------------------------------------------------------------------
namespace configmgr
{
    //---------------------------------------------------------------------------------------
    //= OProviderFactory
    //---------------------------------------------------------------------------------------

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

    ProviderFactory::ProviderFactory(OUString const & aImplementationName, bool bAdmin)
    : m_aImplementationName(aImplementationName)
    , m_bAdmin(bAdmin)
    {
    }
    //---------------------------------------------------------------------------------------

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

    uno::Reference< uno::XInterface > ProviderFactory::getProviderAlways(Context const & xContext)
    {
        RTL_LOGFILE_CONTEXT_AUTHOR(aLog, "configmgr::ProviderFactory", "jb99855", "configmgr::ProviderFactory::getProviderAlways()");
        uno::Reference< uno::XInterface > xResult = getDefaultConfigProviderSingleton(xContext);

        // check for success
        OSL_ENSURE(xResult.is(), "Context could not create provider, but returned NULL instead of throwing an exception");
        if (!xResult.is())
        {
            using ::com::sun::star::configuration::CannotLoadConfigurationException;

            static sal_Char const sCannotCreate[] = "Cannot create ConfigurationProvider. Unknown backend or factory error.";

            throw CannotLoadConfigurationException( OUString(RTL_CONSTASCII_USTRINGPARAM(sCannotCreate)), *this );
        }

        return xResult;
    }
    //---------------------------------------------------------------------------------------
    uno::Reference< uno::XInterface > ProviderFactory::getProviderFromContext(Context const & xContext)
    {
        OSL_ENSURE(ContextReader::testAdminService(xContext, this->m_bAdmin),
                    "Creation context admin flag does not match service being created");

        try
        {
            return getProviderAlways(xContext);
        }
        catch(uno::Exception& e)
        {
            ContextReader aContext(xContext);

            uno::Any aError = aContext.getBootstrapError();
            if (aError.hasValue())
            {
                OSL_ASSERT(aError.getValueTypeClass() == uno::TypeClass_EXCEPTION);
                cppu::throwException(aError);
            }

            OSL_ASSERT(aContext.isBootstrapValid());

            static const sal_Char sErrContext[] = "Cannot open Configuration: ";
            OUString const sContext(RTL_CONSTASCII_USTRINGPARAM(sErrContext));
            e.Message = sContext.concat(e.Message);
            throw;
        }
    }
    //---------------------------------------------------------------------------------------
    uno::Reference< uno::XInterface > ProviderFactory::createProviderWithArguments(Context const & xContext, Arguments const & _aArguments)
    {
        RTL_LOGFILE_CONTEXT_AUTHOR(aLog, "configmgr::ProviderFactory", "jb99855", "configmgr::ProviderFactory::createProviderWithArguments()");

        ContextReader aContext(xContext);
        ArgumentHelper aParser(aContext.getBootstrapContext());

        NamedValues aValues(_aArguments.getLength() + 2);
        sal_Int32 nCount = parseArguments(aParser,aValues,_aArguments);

        bool bNeedNewBackend = aParser.hasBackendArguments();

        if (!aContext.testAdminService(aContext.getBaseContext(),m_bAdmin))
        {
            bNeedNewBackend = true;
            OSL_ASSERT( nCount+2  <= aValues.getLength());
            aValues[nCount++] = ArgumentHelper::makeAdminServiceOverride(m_bAdmin);
            aValues[nCount++] = BootstrapContext::makePassthroughMarker(sal_False);
        }

        OSL_ASSERT(nCount <= aValues.getLength());
        aValues.realloc(nCount);

        if (bNeedNewBackend)
        {
            Context xMergedContext = BootstrapContext::createWrapper(xContext,aValues);
            uno::Reference< uno::XInterface > xResult = getProviderFromContext(xMergedContext);

            return xResult;
        }
        else
        {
            uno::Reference< uno::XInterface > xBaseProvider = getProviderFromContext(xContext);
            uno::Reference< uno::XInterface > xResult = ProviderWrapper::create(xBaseProvider,aValues);

            return xResult;
        }
    }
    //---------------------------------------------------------------------------------------
    uno::Reference< uno::XInterface > ProviderFactory::createProvider(Context const & xContext, bool bAdmin)
    {
        RTL_LOGFILE_CONTEXT_AUTHOR(aLog, "configmgr::ProviderFactory", "jb99855", "configmgr::ProviderFactory::createProvider(bAdmin)");

        NamedValues aValues(2);
        aValues[0] = ArgumentHelper::makeAdminServiceOverride(bAdmin);
        aValues[1] = BootstrapContext::makePassthroughMarker(sal_False);

        Context xMergedContext = BootstrapContext::createWrapper(xContext,aValues);
        uno::Reference< uno::XInterface > xResult = getProviderFromContext(xMergedContext);

        return xResult;
    }
    //---------------------------------------------------------------------------------------
    uno::Reference< uno::XInterface > ProviderFactory::createProvider(Context const & xContext)
    {
        RTL_LOGFILE_CONTEXT_AUTHOR(aLog, "configmgr::ProviderFactory", "jb99855", "configmgr::ProviderFactory::createProvider()");

        if (BootstrapContext::isPassthrough(xContext))
        {
            // make sure this uses a new BootstrapContext !
            Context xPatchedContext = BootstrapContext::createWrapper(xContext,NamedValues());
            return getProviderFromContext(xPatchedContext);
        }
        else
            return getProviderFromContext(xContext);
    }
    //---------------------------------------------------------------------------------------

    sal_Int32 ProviderFactory::parseArguments(ArgumentHelper & aParser, NamedValues & rValues, Arguments const & _aArguments)
    {
        OSL_ASSERT(rValues.getLength() >= _aArguments.getLength());

        sal_Int32 nCount = 0;
        for (sal_Int32 i = 0; i < _aArguments.getLength(); ++i)
        {
            if (!aParser.extractArgument(rValues[nCount],_aArguments[i]))
            {
                rtl::OUStringBuffer sMsg;
                sMsg.appendAscii("ProviderFactory: Unexpected Argument Type. ");
                sMsg.appendAscii("Expected NamedValue or PropertyValue,  ");
                sMsg.appendAscii("found ").append(_aArguments[i].getValueTypeName()).appendAscii(". ");
                throw lang::IllegalArgumentException(sMsg.makeStringAndClear(),*this,static_cast<sal_Int16>(i));
            }

            if (aParser.filterAndAdjustArgument(rValues[nCount]))
            {
                aParser.checkBackendArgument(rValues[nCount]);
                ++nCount;
            }
        }
        return nCount;
    }
    //---------------------------------------------------------------------------------------

    uno::Reference< uno::XInterface >
        SAL_CALL ProviderFactory::createInstanceWithContext( const uno::Reference< uno::XComponentContext >& xContext )
            throw (uno::Exception, ::com::sun::star::uno::RuntimeException)
    {
        // default provider ?
        if (ContextReader::testAdminService(xContext,m_bAdmin))
            return createProvider( xContext );

        else
            return createProvider(xContext,m_bAdmin);
    }
    //---------------------------------------------------------------------------------------

    uno::Reference< uno::XInterface > SAL_CALL
        ProviderFactory::createInstanceWithArgumentsAndContext( const uno::Sequence< uno::Any >& aArguments, const uno::Reference< uno::XComponentContext >& xContext )
            throw (uno::Exception, uno::RuntimeException)
    {
        // default request
        return createProviderWithArguments(xContext, aArguments);
    }

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

    uno::Reference< lang::XSingleComponentFactory > SAL_CALL createProviderFactory(
            OUString const & aImplementationName,
            bool bAdmin
        )
    {
        return new ProviderFactory(aImplementationName, bAdmin);
    }
    //---------------------------------------------------------------------------------------
}   // namespace configmgr
//........................................................................

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

#include "providerfactory.hxx"

#ifndef CONFIGMGR_API_FACTORY_HXX_
#include "confapifactory.hxx"
#endif
#ifndef CONFIGMGR_BOOTSTRAP_HXX_
#include "bootstrap.hxx"
#endif
#ifndef CONFIGMGR_API_PROVIDERWRAPPER_HXX_
#include "providerwrapper.hxx"
#endif

#ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_
#include <com/sun/star/lang/IllegalArgumentException.hpp>
#endif
#ifndef _COM_SUN_STAR_CONFIGURATION_CANNOTLOADCONFIGURATIONEXCEPTION_HPP_
#include <com/sun/star/configuration/CannotLoadConfigurationException.hpp>
#endif

#ifndef _CPPUHELPER_EXC_HLP_HXX_
#include <cppuhelper/exc_hlp.hxx>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif

#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _RTL_LOGFILE_HXX_
#include <rtl/logfile.hxx>
#endif

//---------------------------------------------------------------------------------------
namespace configmgr
{
    //---------------------------------------------------------------------------------------
    //= OProviderFactory
    //---------------------------------------------------------------------------------------

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

    ProviderFactory::ProviderFactory(OUString const & aImplementationName, bool bAdmin)
    : m_aImplementationName(aImplementationName)
    , m_bAdmin(bAdmin)
    {
    }
    //---------------------------------------------------------------------------------------

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

    uno::Reference< uno::XInterface > ProviderFactory::getProviderAlways(Context const & xContext)
    {
        RTL_LOGFILE_CONTEXT_AUTHOR(aLog, "configmgr::ProviderFactory", "jb99855", "configmgr::ProviderFactory::getProviderAlways()");
        uno::Reference< uno::XInterface > xResult = getDefaultConfigProviderSingleton(xContext);

        // check for success
        OSL_ENSURE(xResult.is(), "Context could not create provider, but returned NULL instead of throwing an exception");
        if (!xResult.is())
        {
            using ::com::sun::star::configuration::CannotLoadConfigurationException;

            static sal_Char const sCannotCreate[] = "Cannot create ConfigurationProvider. Unknown backend or factory error.";

            throw CannotLoadConfigurationException( OUString(RTL_CONSTASCII_USTRINGPARAM(sCannotCreate)), *this );
        }

        return xResult;
    }
    //---------------------------------------------------------------------------------------
    uno::Reference< uno::XInterface > ProviderFactory::getProviderFromContext(Context const & xContext)
    {
        OSL_ENSURE(ContextReader::testAdminService(xContext, this->m_bAdmin),
                    "Creation context admin flag does not match service being created");

        try
        {
            return getProviderAlways(xContext);
        }
        catch(uno::Exception& e)
        {
            ContextReader aContext(xContext);

            uno::Any aError = aContext.getBootstrapError();
            if (aError.hasValue())
            {
                OSL_ASSERT(aError.getValueTypeClass() == uno::TypeClass_EXCEPTION);
                cppu::throwException(aError);
            }

            OSL_ASSERT(aContext.isBootstrapValid());

            static const sal_Char sErrContext[] = "Cannot open Configuration: ";
            OUString const sContext(RTL_CONSTASCII_USTRINGPARAM(sErrContext));
            e.Message = sContext.concat(e.Message);
            throw;
        }
    }
    //---------------------------------------------------------------------------------------
    uno::Reference< uno::XInterface > ProviderFactory::createProviderWithArguments(Context const & xContext, Arguments const & _aArguments)
    {
        RTL_LOGFILE_CONTEXT_AUTHOR(aLog, "configmgr::ProviderFactory", "jb99855", "configmgr::ProviderFactory::createProviderWithArguments()");

        ContextReader aContext(xContext);
        ArgumentHelper aParser(aContext.getBootstrapContext());

        NamedValues aValues(_aArguments.getLength() + 2);
        sal_Int32 nCount = parseArguments(aParser,aValues,_aArguments);

        bool bNeedNewBackend = aParser.hasBackendArguments();

        if (!aContext.testAdminService(aContext.getBaseContext(),m_bAdmin))
        {
            bNeedNewBackend = true;
            OSL_ASSERT( nCount+2  <= aValues.getLength());
            aValues[nCount++] = ArgumentHelper::makeAdminServiceOverride(m_bAdmin);
            aValues[nCount++] = BootstrapContext::makePassthroughMarker(sal_False);
        }

        OSL_ASSERT(nCount <= aValues.getLength());
        aValues.realloc(nCount);

        if (bNeedNewBackend)
        {
            Context xMergedContext = BootstrapContext::createWrapper(xContext,aValues);
            uno::Reference< uno::XInterface > xResult = getProviderFromContext(xMergedContext);

            return xResult;
        }
        else
        {
            uno::Reference< uno::XInterface > xBaseProvider = getProviderFromContext(xContext);
            uno::Reference< uno::XInterface > xResult = ProviderWrapper::create(xBaseProvider,aValues);

            return xResult;
        }
    }
    //---------------------------------------------------------------------------------------
    uno::Reference< uno::XInterface > ProviderFactory::createProvider(Context const & xContext, bool bAdmin)
    {
        RTL_LOGFILE_CONTEXT_AUTHOR(aLog, "configmgr::ProviderFactory", "jb99855", "configmgr::ProviderFactory::createProvider(bAdmin)");

        NamedValues aValues(2);
        aValues[0] = ArgumentHelper::makeAdminServiceOverride(bAdmin);
        aValues[1] = BootstrapContext::makePassthroughMarker(sal_False);

        Context xMergedContext = BootstrapContext::createWrapper(xContext,aValues);
        uno::Reference< uno::XInterface > xResult = getProviderFromContext(xMergedContext);

        return xResult;
    }
    //---------------------------------------------------------------------------------------
    uno::Reference< uno::XInterface > ProviderFactory::createProvider(Context const & xContext)
    {
        RTL_LOGFILE_CONTEXT_AUTHOR(aLog, "configmgr::ProviderFactory", "jb99855", "configmgr::ProviderFactory::createProvider()");

        if (BootstrapContext::isPassthrough(xContext))
        {
            // make sure this uses a new BootstrapContext !
            Context xPatchedContext = BootstrapContext::createWrapper(xContext,NamedValues());
            return getProviderFromContext(xPatchedContext);
        }
        else
            return getProviderFromContext(xContext);
    }
    //---------------------------------------------------------------------------------------

    sal_Int32 ProviderFactory::parseArguments(ArgumentHelper & aParser, NamedValues & rValues, Arguments const & _aArguments)
    {
        OSL_ASSERT(rValues.getLength() >= _aArguments.getLength());

        sal_Int32 nCount = 0;
        for (sal_Int32 i = 0; i < _aArguments.getLength(); ++i)
        {
            if (!aParser.extractArgument(rValues[nCount],_aArguments[i]))
            {
                rtl::OUStringBuffer sMsg;
                sMsg.appendAscii("ProviderFactory: Unexpected Argument Type. ");
                sMsg.appendAscii("Expected NamedValue or PropertyValue,  ");
                sMsg.appendAscii("found ").append(_aArguments[i].getValueTypeName()).appendAscii(". ");
                throw lang::IllegalArgumentException(sMsg.makeStringAndClear(),*this,static_cast<sal_Int16>(i));
            }

            if (aParser.filterAndAdjustArgument(rValues[nCount]))
            {
                aParser.checkBackendArgument(rValues[nCount]);
                ++nCount;
            }
        }
        return nCount;
    }
    //---------------------------------------------------------------------------------------

    uno::Reference< uno::XInterface >
        SAL_CALL ProviderFactory::createInstanceWithContext( const uno::Reference< uno::XComponentContext >& xContext )
            throw (uno::Exception, ::com::sun::star::uno::RuntimeException)
    {
        // default provider ?
        if (ContextReader::testAdminService(xContext,m_bAdmin))
            return createProvider( xContext );

        else
            return createProvider(xContext,m_bAdmin);
    }
    //---------------------------------------------------------------------------------------

    uno::Reference< uno::XInterface > SAL_CALL
        ProviderFactory::createInstanceWithArgumentsAndContext( const uno::Sequence< uno::Any >& aArguments, const uno::Reference< uno::XComponentContext >& xContext )
            throw (uno::Exception, uno::RuntimeException)
    {
        // default request
        return createProviderWithArguments(xContext, aArguments);
    }

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

    uno::Reference< lang::XSingleComponentFactory > SAL_CALL createProviderFactory(
            OUString const & aImplementationName,
            bool bAdmin
        )
    {
        return new ProviderFactory(aImplementationName, bAdmin);
    }
    //---------------------------------------------------------------------------------------
}   // namespace configmgr
//........................................................................

<|endoftext|>


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

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

#include "configexcept.hxx"
#include <osl/diagnose.h>

namespace configmgr
{
    namespace configuration
    {
//-----------------------------------------------------------------------------

        Exception::Exception()
        : m_sAsciiMessage()
        {
        }
        //---------------------------------------------------------------------
        Exception::Exception(char const* sAsciiMessage)
        : m_sAsciiMessage(sAsciiMessage)
        {
        }
        //---------------------------------------------------------------------
        Exception::Exception(rtl::OString const& sAsciiMessage)
        : m_sAsciiMessage(sAsciiMessage)
        {
        }
        //---------------------------------------------------------------------

        OUString Exception::message() const
        {

            return rtl::OStringToOUString( m_sAsciiMessage, RTL_TEXTENCODING_ASCII_US );
        }
        //---------------------------------------------------------------------
        char const* Exception::what() const
        {
            return m_sAsciiMessage.getLength() ? m_sAsciiMessage.getStr() : "FAILURE in CONFIGURATION: No description available";
        }
        //---------------------------------------------------------------------

        static const char c_sInvalidNamePre[] = "CONFIGURATION: Invalid Path or Name: ";
        static const char c_sInvalidName[] = "CONFIGURATION: <Invalid Path or Name>";
//-----------------------------------------------------------------------------

        InvalidName::InvalidName(OUString const& sName)
        : Exception( rtl::OString(RTL_CONSTASCII_STRINGPARAM(c_sInvalidName)) )
        , m_sName(sName)
        {
        }
        //---------------------------------------------------------------------

        InvalidName::InvalidName(OUString const& sName, char const* sAsciiDescription)
        : Exception( rtl::OString(RTL_CONSTASCII_STRINGPARAM(c_sInvalidName)) += sAsciiDescription )
        , m_sName( sName.concat(OUString::createFromAscii(sAsciiDescription)) )
        {
        }
        //---------------------------------------------------------------------

        OUString InvalidName::message() const
        {
            return rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(c_sInvalidNamePre)).concat( m_sName );
        }
//-----------------------------------------------------------------------------

        static const char c_sViolation[] = "CONFIGURATION: Update Violates Constraint: ";
    //---------------------------------------------------------------------
        ConstraintViolation::ConstraintViolation()
        : Exception( rtl::OString(RTL_CONSTASCII_STRINGPARAM(c_sViolation)) )
        {
        }
        //---------------------------------------------------------------------

        ConstraintViolation::ConstraintViolation(char const* sConstraint)
        : Exception( rtl::OString(RTL_CONSTASCII_STRINGPARAM(c_sViolation)) += sConstraint)
        {
        }

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

        static const char c_sTypeMismatch[] = "CONFIGURATION: Data Types do not match: ";
    //---------------------------------------------------------------------
        OUString TypeMismatch::describe(OUString const& sFoundType, OUString const& sExpectedType)
        {
            OUString sRet = OUString(RTL_CONSTASCII_USTRINGPARAM("Found Type: '"));
            sRet += sFoundType;
            if (sExpectedType.getLength() != 0)
            {
                sRet += OUString(RTL_CONSTASCII_USTRINGPARAM("' - Expected Type: '"));
                sRet += sExpectedType;
                sRet += OUString(RTL_CONSTASCII_USTRINGPARAM("'"));
            }
            else
            {
                sRet += OUString(RTL_CONSTASCII_USTRINGPARAM("' is not valid in this context"));
            }
            return sRet;
        }
    //---------------------------------------------------------------------

        TypeMismatch::TypeMismatch()
        : Exception( rtl::OString(RTL_CONSTASCII_STRINGPARAM(c_sTypeMismatch)) )
        {
        }
    //---------------------------------------------------------------------

        TypeMismatch::TypeMismatch(OUString const& sType1, OUString const& sType2)
        : Exception( rtl::OString(RTL_CONSTASCII_STRINGPARAM(c_sTypeMismatch)) )
        , m_sTypes( describe(sType1,sType2) )
        {
        }
    //---------------------------------------------------------------------

        TypeMismatch::TypeMismatch(OUString const& sType1)
        : Exception( rtl::OString(RTL_CONSTASCII_STRINGPARAM(c_sTypeMismatch)) )
        , m_sTypes( describe(sType1,OUString()) )
        {
        }
    //---------------------------------------------------------------------
        TypeMismatch::TypeMismatch(OUString const& sType1, OUString const& sType2, char const* sAsciiDescription)
        : Exception( rtl::OString(RTL_CONSTASCII_STRINGPARAM(c_sTypeMismatch)) += sAsciiDescription)
        , m_sTypes( describe(sType1,sType2).concat(OUString::createFromAscii(sAsciiDescription)) )
        {
        }
     //---------------------------------------------------------------------

        OUString TypeMismatch::message() const
        {
            return rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(c_sTypeMismatch)).concat( m_sTypes );
        }
//-----------------------------------------------------------------------------

        WrappedUnoException::WrappedUnoException(uno::Any const& aUnoException)
        : Exception("UNO Service failed")
        , m_aUnoException(aUnoException)
        {
            OSL_ENSURE( m_aUnoException.getValueTypeClass() == uno::TypeClass_EXCEPTION,
                        "ERROR: Wrapping a non-exception into a WrappedUnoException !");

        }
        //---------------------------------------------------------------------

        OUString WrappedUnoException::extractMessage() const
        {
            return extractUnoException().Message;
        }
        //---------------------------------------------------------------------

        uno::Exception WrappedUnoException::extractUnoException() const
        {
            uno::Exception e;
            OSL_VERIFY( m_aUnoException >>= e );
            return e;
        }
        //---------------------------------------------------------------------

        uno::Any const& WrappedUnoException::getAnyUnoException() const
        {
            return m_aUnoException;
        }
        //---------------------------------------------------------------------

        OUString WrappedUnoException::message() const
        {
            return OUString(RTL_CONSTASCII_USTRINGPARAM("CONFIGMGR: Used Service failed with a"))
                    += m_aUnoException.getValueType().getTypeName()
                    += OUString(RTL_CONSTASCII_USTRINGPARAM(": "))
                    += extractMessage();
        }
//-----------------------------------------------------------------------------
    }

    namespace configapi
    {
//-----------------------------------------------------------------------------
        ExceptionMapper::ExceptionMapper(configuration::Exception& e)
        : m_eOriginal(e)
        , m_xContext()
        , m_sMessage(e.message())
        {
        }
        //---------------------------------------------------------------------

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

        void ExceptionMapper::setContext(uno::XInterface* pContext)
        {
            m_xContext = pContext;
        }
        //---------------------------------------------------------------------

        OUString ExceptionMapper::message() const
        {
            return OUString(RTL_CONSTASCII_USTRINGPARAM("FAILURE in CONFIGMGR: ")).concat( m_sMessage );
        }
        //---------------------------------------------------------------------

        uno::Reference<uno::XInterface> ExceptionMapper::context() const
        {
            return m_xContext;
        }
        //---------------------------------------------------------------------

        void ExceptionMapper::illegalArgument(sal_Int16 nArgument) throw(lang::IllegalArgumentException)
        {
            throw lang::IllegalArgumentException(message(),context(),nArgument);
        }
        //---------------------------------------------------------------------

        void ExceptionMapper::unhandled() throw(uno::RuntimeException)
        {
            throw uno::RuntimeException(message(),context());
        }
//-----------------------------------------------------------------------------
    }
}
<commit_msg>INTEGRATION: CWS changefileheader (1.5.72); FILE MERGED 2008/03/31 12:22:55 rt 1.5.72.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: configexcept.cxx,v $
 * $Revision: 1.6 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

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

#include "configexcept.hxx"
#include <osl/diagnose.h>

namespace configmgr
{
    namespace configuration
    {
//-----------------------------------------------------------------------------

        Exception::Exception()
        : m_sAsciiMessage()
        {
        }
        //---------------------------------------------------------------------
        Exception::Exception(char const* sAsciiMessage)
        : m_sAsciiMessage(sAsciiMessage)
        {
        }
        //---------------------------------------------------------------------
        Exception::Exception(rtl::OString const& sAsciiMessage)
        : m_sAsciiMessage(sAsciiMessage)
        {
        }
        //---------------------------------------------------------------------

        OUString Exception::message() const
        {

            return rtl::OStringToOUString( m_sAsciiMessage, RTL_TEXTENCODING_ASCII_US );
        }
        //---------------------------------------------------------------------
        char const* Exception::what() const
        {
            return m_sAsciiMessage.getLength() ? m_sAsciiMessage.getStr() : "FAILURE in CONFIGURATION: No description available";
        }
        //---------------------------------------------------------------------

        static const char c_sInvalidNamePre[] = "CONFIGURATION: Invalid Path or Name: ";
        static const char c_sInvalidName[] = "CONFIGURATION: <Invalid Path or Name>";
//-----------------------------------------------------------------------------

        InvalidName::InvalidName(OUString const& sName)
        : Exception( rtl::OString(RTL_CONSTASCII_STRINGPARAM(c_sInvalidName)) )
        , m_sName(sName)
        {
        }
        //---------------------------------------------------------------------

        InvalidName::InvalidName(OUString const& sName, char const* sAsciiDescription)
        : Exception( rtl::OString(RTL_CONSTASCII_STRINGPARAM(c_sInvalidName)) += sAsciiDescription )
        , m_sName( sName.concat(OUString::createFromAscii(sAsciiDescription)) )
        {
        }
        //---------------------------------------------------------------------

        OUString InvalidName::message() const
        {
            return rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(c_sInvalidNamePre)).concat( m_sName );
        }
//-----------------------------------------------------------------------------

        static const char c_sViolation[] = "CONFIGURATION: Update Violates Constraint: ";
    //---------------------------------------------------------------------
        ConstraintViolation::ConstraintViolation()
        : Exception( rtl::OString(RTL_CONSTASCII_STRINGPARAM(c_sViolation)) )
        {
        }
        //---------------------------------------------------------------------

        ConstraintViolation::ConstraintViolation(char const* sConstraint)
        : Exception( rtl::OString(RTL_CONSTASCII_STRINGPARAM(c_sViolation)) += sConstraint)
        {
        }

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

        static const char c_sTypeMismatch[] = "CONFIGURATION: Data Types do not match: ";
    //---------------------------------------------------------------------
        OUString TypeMismatch::describe(OUString const& sFoundType, OUString const& sExpectedType)
        {
            OUString sRet = OUString(RTL_CONSTASCII_USTRINGPARAM("Found Type: '"));
            sRet += sFoundType;
            if (sExpectedType.getLength() != 0)
            {
                sRet += OUString(RTL_CONSTASCII_USTRINGPARAM("' - Expected Type: '"));
                sRet += sExpectedType;
                sRet += OUString(RTL_CONSTASCII_USTRINGPARAM("'"));
            }
            else
            {
                sRet += OUString(RTL_CONSTASCII_USTRINGPARAM("' is not valid in this context"));
            }
            return sRet;
        }
    //---------------------------------------------------------------------

        TypeMismatch::TypeMismatch()
        : Exception( rtl::OString(RTL_CONSTASCII_STRINGPARAM(c_sTypeMismatch)) )
        {
        }
    //---------------------------------------------------------------------

        TypeMismatch::TypeMismatch(OUString const& sType1, OUString const& sType2)
        : Exception( rtl::OString(RTL_CONSTASCII_STRINGPARAM(c_sTypeMismatch)) )
        , m_sTypes( describe(sType1,sType2) )
        {
        }
    //---------------------------------------------------------------------

        TypeMismatch::TypeMismatch(OUString const& sType1)
        : Exception( rtl::OString(RTL_CONSTASCII_STRINGPARAM(c_sTypeMismatch)) )
        , m_sTypes( describe(sType1,OUString()) )
        {
        }
    //---------------------------------------------------------------------
        TypeMismatch::TypeMismatch(OUString const& sType1, OUString const& sType2, char const* sAsciiDescription)
        : Exception( rtl::OString(RTL_CONSTASCII_STRINGPARAM(c_sTypeMismatch)) += sAsciiDescription)
        , m_sTypes( describe(sType1,sType2).concat(OUString::createFromAscii(sAsciiDescription)) )
        {
        }
     //---------------------------------------------------------------------

        OUString TypeMismatch::message() const
        {
            return rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(c_sTypeMismatch)).concat( m_sTypes );
        }
//-----------------------------------------------------------------------------

        WrappedUnoException::WrappedUnoException(uno::Any const& aUnoException)
        : Exception("UNO Service failed")
        , m_aUnoException(aUnoException)
        {
            OSL_ENSURE( m_aUnoException.getValueTypeClass() == uno::TypeClass_EXCEPTION,
                        "ERROR: Wrapping a non-exception into a WrappedUnoException !");

        }
        //---------------------------------------------------------------------

        OUString WrappedUnoException::extractMessage() const
        {
            return extractUnoException().Message;
        }
        //---------------------------------------------------------------------

        uno::Exception WrappedUnoException::extractUnoException() const
        {
            uno::Exception e;
            OSL_VERIFY( m_aUnoException >>= e );
            return e;
        }
        //---------------------------------------------------------------------

        uno::Any const& WrappedUnoException::getAnyUnoException() const
        {
            return m_aUnoException;
        }
        //---------------------------------------------------------------------

        OUString WrappedUnoException::message() const
        {
            return OUString(RTL_CONSTASCII_USTRINGPARAM("CONFIGMGR: Used Service failed with a"))
                    += m_aUnoException.getValueType().getTypeName()
                    += OUString(RTL_CONSTASCII_USTRINGPARAM(": "))
                    += extractMessage();
        }
//-----------------------------------------------------------------------------
    }

    namespace configapi
    {
//-----------------------------------------------------------------------------
        ExceptionMapper::ExceptionMapper(configuration::Exception& e)
        : m_eOriginal(e)
        , m_xContext()
        , m_sMessage(e.message())
        {
        }
        //---------------------------------------------------------------------

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

        void ExceptionMapper::setContext(uno::XInterface* pContext)
        {
            m_xContext = pContext;
        }
        //---------------------------------------------------------------------

        OUString ExceptionMapper::message() const
        {
            return OUString(RTL_CONSTASCII_USTRINGPARAM("FAILURE in CONFIGMGR: ")).concat( m_sMessage );
        }
        //---------------------------------------------------------------------

        uno::Reference<uno::XInterface> ExceptionMapper::context() const
        {
            return m_xContext;
        }
        //---------------------------------------------------------------------

        void ExceptionMapper::illegalArgument(sal_Int16 nArgument) throw(lang::IllegalArgumentException)
        {
            throw lang::IllegalArgumentException(message(),context(),nArgument);
        }
        //---------------------------------------------------------------------

        void ExceptionMapper::unhandled() throw(uno::RuntimeException)
        {
            throw uno::RuntimeException(message(),context());
        }
//-----------------------------------------------------------------------------
    }
}
<|endoftext|>


<commit_before>/* LiteSQL
 *
 * The list of contributors at http://litesql.sf.net/
 *
 * See LICENSE for copyright information. */

/** \file mysql.hpp
 * MySQL MySQL::Cursor MySQL::Backend */
#ifndef litesql_mysql_hpp
#define litesql_mysql_hpp

#ifdef HAVE_LIBMYSQLCLIENT

#include "litesql/except.hpp"
#include "litesql/types.hpp"
#include "litesql/string.hpp"
#include "litesql/backend.hpp"

typedef struct st_mysql MYSQL;

namespace litesql {

/** MySQL - backend */
class MySQL : public Backend {
    MYSQL* conn;
  std::string host, user, passwd, database;
    int port;
public:
  class Cursor;
  class Result;

  MySQL(const std::string& connInfo);
    virtual ~MySQL();

    virtual bool supportsSequences() const;
    virtual string getRowIDType() const;
    virtual string getInsertID() const;
    virtual void begin() const;
    virtual void commit() const;
    virtual void rollback() const;
  Backend::Result* execute(const std::string& query) const;
  Backend::Cursor* cursor(const std::string& query) const;
};
}
#endif // #ifndef litesql_mysql_hpp
#endif // #ifdef HAVE_LIBMYSQLCLIENT
<commit_msg>prefixed string with std::<commit_after>/* LiteSQL
 *
 * The list of contributors at http://litesql.sf.net/
 *
 * See LICENSE for copyright information. */

/** \file mysql.hpp
 * MySQL MySQL::Cursor MySQL::Backend */
#ifndef litesql_mysql_hpp
#define litesql_mysql_hpp

#ifdef HAVE_LIBMYSQLCLIENT

#include "litesql/except.hpp"
#include "litesql/types.hpp"
#include "litesql/string.hpp"
#include "litesql/backend.hpp"

typedef struct st_mysql MYSQL;

namespace litesql {

/** MySQL - backend */
class MySQL : public Backend {
    MYSQL* conn;
  std::string host, user, passwd, database;
    int port;
public:
  class Cursor;
  class Result;

  MySQL(const std::string& connInfo);
    virtual ~MySQL();

    virtual bool supportsSequences() const;
    virtual std::string getRowIDType() const;
    virtual std::string getInsertID() const;
    virtual void begin() const;
    virtual void commit() const;
    virtual void rollback() const;
  Backend::Result* execute(const std::string& query) const;
  Backend::Cursor* cursor(const std::string& query) const;
};
}
#endif // #ifndef litesql_mysql_hpp
#endif // #ifdef HAVE_LIBMYSQLCLIENT
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: PColumn.hxx,v $
 *
 *  $Revision: 1.11 $
 *
 *  last change: $Author: rt $ $Date: 2004-10-22 08:40:26 $
 *
 *  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_PCOLUMN_HXX_
#define _CONNECTIVITY_PCOLUMN_HXX_

#ifndef _CONNECTIVITY_SDBCX_COLUMN_HXX_
#include "connectivity/sdbcx/VColumn.hxx"
#endif

namespace connectivity
{
    namespace parse
    {
        class OParseColumn;

        typedef sdbcx::OColumn OParseColumn_BASE;
        typedef ::comphelper::OIdPropertyArrayUsageHelper<OParseColumn> OParseColumn_PROP;

        class OParseColumn :    public OParseColumn_BASE,
                                public OParseColumn_PROP
        {
            ::rtl::OUString m_aRealName;
            ::rtl::OUString m_aTableName;
            sal_Bool        m_bFunction;
            sal_Bool        m_bDbasePrecisionChanged;
            sal_Bool        m_bAggregateFunction;
        protected:
            virtual ::cppu::IPropertyArrayHelper* createArrayHelper( sal_Int32 _nId) const;
            virtual ::cppu::IPropertyArrayHelper & SAL_CALL getInfoHelper();

            virtual ~OParseColumn();
        public:
            OParseColumn(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _xColumn,sal_Bool _bCase);
            OParseColumn(const ::rtl::OUString& _Name,
                    const ::rtl::OUString& _TypeName,
                    const ::rtl::OUString& _DefaultValue,
                    sal_Int32       _IsNullable,
                    sal_Int32       _Precision,
                    sal_Int32       _Scale,
                    sal_Int32       _Type,
                    sal_Bool        _IsAutoIncrement,
                    sal_Bool        _IsCurrency,
                    sal_Bool        _bCase);

            virtual void construct();

            void setRealName(const ::rtl::OUString& _rName)  { m_aRealName  = _rName; }
            void setTableName(const ::rtl::OUString& _rName) { m_aTableName = _rName; }
            void setFunction(sal_Bool _bFunction)            { m_bFunction  = _bFunction; }
            void setAggregateFunction(sal_Bool _bFunction)   { m_bAggregateFunction = _bFunction; }
            void setDbasePrecisionChanged(sal_Bool _bDbasePrecisionChanged) { m_bDbasePrecisionChanged = _bDbasePrecisionChanged; }

            ::rtl::OUString getRealName() const { return  m_aRealName; }
            ::rtl::OUString getTableName() const { return  m_aTableName; }
            sal_Bool        getFunction() const { return  m_bFunction; }
            sal_Bool        getDbasePrecisionChanged()  const { return  m_bDbasePrecisionChanged; }
        };

        class OOrderColumn;

        typedef sdbcx::OColumn OOrderColumn_BASE;
        typedef ::comphelper::OIdPropertyArrayUsageHelper<OOrderColumn> OOrderColumn_PROP;

        class OOrderColumn :    public OOrderColumn_BASE,
                                public OOrderColumn_PROP
        {
            sal_Bool        m_bAscending;
            sal_Bool        m_bOrder;
        protected:
            virtual ::cppu::IPropertyArrayHelper* createArrayHelper( sal_Int32 _nId) const;
            virtual ::cppu::IPropertyArrayHelper & SAL_CALL getInfoHelper();

            virtual ~OOrderColumn();
        public:
            OOrderColumn(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _xColumn,sal_Bool _bCase,sal_Bool _bAscending);
            OOrderColumn(const ::rtl::OUString& _Name,
                    const ::rtl::OUString& _TypeName,
                    const ::rtl::OUString& _DefaultValue,
                    sal_Int32       _IsNullable,
                    sal_Int32       _Precision,
                    sal_Int32       _Scale,
                    sal_Int32       _Type,
                    sal_Bool        _IsAutoIncrement,
                    sal_Bool        _IsCurrency,
                    sal_Bool        _bCase
                    ,sal_Bool _bAscending);

            virtual void construct();

            virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames(  ) throw(::com::sun::star::uno::RuntimeException);
        };
    }
}

#endif //_CONNECTIVITY_PCOLUMN_HXX_

<commit_msg>INTEGRATION: CWS ooo19126 (1.11.112); FILE MERGED 2005/09/05 17:22:36 rt 1.11.112.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: PColumn.hxx,v $
 *
 *  $Revision: 1.12 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 04:57:57 $
 *
 *  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 _CONNECTIVITY_PCOLUMN_HXX_
#define _CONNECTIVITY_PCOLUMN_HXX_

#ifndef _CONNECTIVITY_SDBCX_COLUMN_HXX_
#include "connectivity/sdbcx/VColumn.hxx"
#endif

namespace connectivity
{
    namespace parse
    {
        class OParseColumn;

        typedef sdbcx::OColumn OParseColumn_BASE;
        typedef ::comphelper::OIdPropertyArrayUsageHelper<OParseColumn> OParseColumn_PROP;

        class OParseColumn :    public OParseColumn_BASE,
                                public OParseColumn_PROP
        {
            ::rtl::OUString m_aRealName;
            ::rtl::OUString m_aTableName;
            sal_Bool        m_bFunction;
            sal_Bool        m_bDbasePrecisionChanged;
            sal_Bool        m_bAggregateFunction;
        protected:
            virtual ::cppu::IPropertyArrayHelper* createArrayHelper( sal_Int32 _nId) const;
            virtual ::cppu::IPropertyArrayHelper & SAL_CALL getInfoHelper();

            virtual ~OParseColumn();
        public:
            OParseColumn(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _xColumn,sal_Bool _bCase);
            OParseColumn(const ::rtl::OUString& _Name,
                    const ::rtl::OUString& _TypeName,
                    const ::rtl::OUString& _DefaultValue,
                    sal_Int32       _IsNullable,
                    sal_Int32       _Precision,
                    sal_Int32       _Scale,
                    sal_Int32       _Type,
                    sal_Bool        _IsAutoIncrement,
                    sal_Bool        _IsCurrency,
                    sal_Bool        _bCase);

            virtual void construct();

            void setRealName(const ::rtl::OUString& _rName)  { m_aRealName  = _rName; }
            void setTableName(const ::rtl::OUString& _rName) { m_aTableName = _rName; }
            void setFunction(sal_Bool _bFunction)            { m_bFunction  = _bFunction; }
            void setAggregateFunction(sal_Bool _bFunction)   { m_bAggregateFunction = _bFunction; }
            void setDbasePrecisionChanged(sal_Bool _bDbasePrecisionChanged) { m_bDbasePrecisionChanged = _bDbasePrecisionChanged; }

            ::rtl::OUString getRealName() const { return  m_aRealName; }
            ::rtl::OUString getTableName() const { return  m_aTableName; }
            sal_Bool        getFunction() const { return  m_bFunction; }
            sal_Bool        getDbasePrecisionChanged()  const { return  m_bDbasePrecisionChanged; }
        };

        class OOrderColumn;

        typedef sdbcx::OColumn OOrderColumn_BASE;
        typedef ::comphelper::OIdPropertyArrayUsageHelper<OOrderColumn> OOrderColumn_PROP;

        class OOrderColumn :    public OOrderColumn_BASE,
                                public OOrderColumn_PROP
        {
            sal_Bool        m_bAscending;
            sal_Bool        m_bOrder;
        protected:
            virtual ::cppu::IPropertyArrayHelper* createArrayHelper( sal_Int32 _nId) const;
            virtual ::cppu::IPropertyArrayHelper & SAL_CALL getInfoHelper();

            virtual ~OOrderColumn();
        public:
            OOrderColumn(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _xColumn,sal_Bool _bCase,sal_Bool _bAscending);
            OOrderColumn(const ::rtl::OUString& _Name,
                    const ::rtl::OUString& _TypeName,
                    const ::rtl::OUString& _DefaultValue,
                    sal_Int32       _IsNullable,
                    sal_Int32       _Precision,
                    sal_Int32       _Scale,
                    sal_Int32       _Type,
                    sal_Bool        _IsAutoIncrement,
                    sal_Bool        _IsCurrency,
                    sal_Bool        _bCase
                    ,sal_Bool _bAscending);

            virtual void construct();

            virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames(  ) throw(::com::sun::star::uno::RuntimeException);
        };
    }
}

#endif //_CONNECTIVITY_PCOLUMN_HXX_

<|endoftext|>


<commit_before>// Copyright (c) 2010-2022, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.

#ifndef MFEM_MESH_OPERATORS
#define MFEM_MESH_OPERATORS

#include "../config/config.hpp"
#include "../general/array.hpp"
#include "mesh.hpp"
#include "../fem/estimators.hpp"

#include <limits>

namespace mfem
{

/** @brief The MeshOperator class serves as base for mesh manipulation classes.

    The purpose of the class is to provide a common abstraction for various
    AMR mesh control schemes. The typical use in an AMR loop is illustrated
    in examples 6/6p and 15/15p.

    A more general loop that also supports sequences of mesh operators with
    multiple updates looks like this:
    \code
       for (...)
       {
          // computations on the current mesh ...
          while (mesh_operator->Apply(mesh))
          {
             // update FiniteElementSpaces and interpolate GridFunctions ...
             if (mesh_operator->Continue()) { break; }
          }
          if (mesh_operator->Stop()) { break; }
       }
    \endcode
 */
class MeshOperator
{
private:
   int mod;

protected:
   friend class MeshOperatorSequence;

   /** @brief Implementation of the mesh operation. Invoked by the Apply()
              public method.
       @return Combination of ActionInfo constants. */
   virtual int ApplyImpl(Mesh &mesh) = 0;

   /// Constructor to be used by derived classes.
   MeshOperator() : mod(NONE) { }

public:
   /** @brief Action and information constants and masks.

       Combinations of constants are returned by the Apply() virtual method and
       can be accessed directly with GetActionInfo() or indirectly with methods
       like Stop(), Continue(), etc. The information bits (MASK_INFO) can be set
       only when the update bit is set (see MASK_UPDATE). */
   enum Action
   {
      NONE        = 0, /**< continue with computations without updating spaces
                            or grid-functions, i.e. the mesh was not modified */
      CONTINUE    = 1, /**< update spaces and grid-functions and continue
                            computations with the new mesh */
      STOP        = 2, ///< a stopping criterion was satisfied
      REPEAT      = 3, /**< update spaces and grid-functions and call the
                            operator Apply() method again */
      MASK_UPDATE = 1, ///< bit mask for the "update" bit
      MASK_ACTION = 3  ///< bit mask for all "action" bits
   };

   enum Info
   {
      REFINED     = 4*1, ///< the mesh was refined
      DEREFINED   = 4*2, ///< the mesh was de-refined
      REBALANCED  = 4*3, ///< the mesh was rebalanced
      MASK_INFO   = ~3   ///< bit mask for all "info" bits
   };

   /** @brief Perform the mesh operation.
       @return true if FiniteElementSpaces and GridFunctions need to be updated.
   */
   bool Apply(Mesh &mesh) { return ((mod = ApplyImpl(mesh)) & MASK_UPDATE); }

   /** @brief Check if STOP action is requested, e.g. stopping criterion is
       satisfied. */
   bool Stop() const { return ((mod & MASK_ACTION) == STOP); }
   /** @brief Check if REPEAT action is requested, i.e. FiniteElementSpaces and
       GridFunctions need to be updated, and Apply() must be called again. */
   bool Repeat() const { return ((mod & MASK_ACTION) == REPEAT); }
   /** @brief Check if CONTINUE action is requested, i.e. FiniteElementSpaces
       and GridFunctions need to be updated and computations should continue. */
   bool Continue() const { return ((mod & MASK_ACTION) == CONTINUE); }

   /// Check if the mesh was refined.
   bool Refined() const { return ((mod & MASK_INFO) == REFINED); }
   /// Check if the mesh was de-refined.
   bool Derefined() const { return ((mod & MASK_INFO) == DEREFINED); }
   /// Check if the mesh was rebalanced.
   bool Rebalanced() const { return ((mod & MASK_INFO) == REBALANCED); }

   /** @brief Get the full ActionInfo value generated by the last call to
       Apply(). */
   int GetActionInfo() const { return mod; }

   /// Reset the MeshOperator.
   virtual void Reset() = 0;

   /// The destructor is virtual.
   virtual ~MeshOperator() { }
};

/** Composition of MeshOperators into a sequence. Use the Append() method to
    create the sequence. */
class MeshOperatorSequence : public MeshOperator
{
protected:
   int step;
   Array<MeshOperator*> sequence; ///< MeshOperators sequence, owned by us.

   /// Do not allow copy construction, due to assumed ownership.
   MeshOperatorSequence(const MeshOperatorSequence &) { }

   /// Do not allow copy assignment, due to assumed ownership.
   MeshOperatorSequence& operator=(const MeshOperatorSequence &s) = delete;

   /** @brief Apply the MeshOperatorSequence.
       @return ActionInfo value corresponding to the last applied operator from
       the sequence. */
   virtual int ApplyImpl(Mesh &mesh);

public:
   /// Constructor. Use the Append() method to create the sequence.
   MeshOperatorSequence() : step(-1) { }

   /// Delete all operators from the sequence.
   virtual ~MeshOperatorSequence();

   /** @brief Add an operator to the end of the sequence.
       The MeshOperatorSequence assumes ownership of the operator. */
   void Append(MeshOperator *mc) { sequence.Append(mc); }

   /// Access the underlying sequence.
   Array<MeshOperator*> &GetSequence() { return sequence; }

   /// Reset all MeshOperators in the sequence.
   virtual void Reset();
};

/** @brief Mesh refinement operator using an error threshold.

    This class uses the given ErrorEstimator to estimate local element errors
    and then marks for refinement all elements i such that loc_err_i > threshold.
    The threshold is computed as
    \code
       threshold = max(total_err * total_fraction * pow(num_elements,-1.0/p),
                       local_err_goal);
    \endcode
    where p (=total_norm_p), total_fraction, and local_err_goal are settable
    parameters, total_err = (sum_i local_err_i^p)^{1/p}, when p < inf,
    or total_err = max_i local_err_i, when p = inf.
*/
class ThresholdRefiner : public MeshOperator
{
protected:
   ErrorEstimator &estimator;
   AnisotropicErrorEstimator *aniso_estimator;

   double total_norm_p;
   double total_err_goal;
   double total_fraction;
   double local_err_goal;
   long   max_elements;

   double threshold;
   long num_marked_elements;

   Array<Refinement> marked_elements;
   long current_sequence;

   int non_conforming;
   int nc_limit;

   double GetNorm(const Vector &local_err, Mesh &mesh) const;

   /** @brief Apply the operator to the mesh.
       @return STOP if a stopping criterion is satisfied or no elements were
       marked for refinement; REFINED + CONTINUE otherwise. */
   virtual int ApplyImpl(Mesh &mesh);

public:
   /// Construct a ThresholdRefiner using the given ErrorEstimator.
   ThresholdRefiner(ErrorEstimator &est);

   // default destructor (virtual)

   /** @brief Set the exponent, p, of the discrete p-norm used to compute the
       total error from the local element errors. */
   void SetTotalErrorNormP(double norm_p = infinity())
   { total_norm_p = norm_p; }

   /** @brief Set the total error stopping criterion: stop when
       total_err <= total_err_goal. The default value is zero. */
   void SetTotalErrorGoal(double err_goal) { total_err_goal = err_goal; }

   /** @brief Set the total fraction used in the computation of the threshold.
       The default value is 1/2.
       @note If fraction == 0, total_err is essentially ignored in the threshold
       computation, i.e. threshold = local error goal. */
   void SetTotalErrorFraction(double fraction) { total_fraction = fraction; }

   /** @brief Set the local stopping criterion: stop when
       local_err_i <= local_err_goal. The default value is zero.
       @note If local_err_goal == 0, it is essentially ignored in the threshold
       computation. */
   void SetLocalErrorGoal(double err_goal) { local_err_goal = err_goal; }

   /** @brief Set the maximum number of elements stopping criterion: stop when
       the input mesh has num_elements >= max_elem. The default value is
       LONG_MAX. */
   void SetMaxElements(long max_elem) { max_elements = max_elem; }

   /// Use nonconforming refinement, if possible (triangles, quads, hexes).
   void PreferNonconformingRefinement() { non_conforming = 1; }

   /** @brief Use conforming refinement, if possible (triangles, tetrahedra)
       -- this is the default. */
   void PreferConformingRefinement() { non_conforming = -1; }

   /** @brief Set the maximum ratio of refinement levels of adjacent elements
       (0 = unlimited). */
   void SetNCLimit(int nc_limit_)
   {
      MFEM_ASSERT(nc_limit_ >= 0, "Invalid NC limit");
      nc_limit = nc_limit_;
   }

   /// Get the number of marked elements in the last Apply() call.
   long GetNumMarkedElements() const { return num_marked_elements; }

   /// Get the threshold used in the last Apply() call.
   double GetThreshold() const { return threshold; }

   /// Reset the associated estimator.
   virtual void Reset();
};

// TODO: BulkRefiner to refine a portion of the global error

/** @brief De-refinement operator using an error threshold.

    This de-refinement operator marks elements in the hierarchy whose children
    are leaves and their combined error is below a given threshold. The
    errors of the children are combined by one of the following operations:
    - op = 0: minimum of the errors
    - op = 1: sum of the errors (default)
    - op = 2: maximum of the errors. */
class ThresholdDerefiner : public MeshOperator
{
protected:
   ErrorEstimator &estimator;

   double threshold;
   int nc_limit, op;

   /** @brief Apply the operator to the mesh.
       @return DEREFINED + CONTINUE if some elements were de-refined; NONE
       otherwise. */
   virtual int ApplyImpl(Mesh &mesh);

public:
   /// Construct a ThresholdDerefiner using the given ErrorEstimator.
   ThresholdDerefiner(ErrorEstimator &est)
      : estimator(est)
   {
      threshold = 0.0;
      nc_limit = 0;
      op = 1;
   }

   // default destructor (virtual)

   /// Set the de-refinement threshold. The default value is zero.
   void SetThreshold(double thresh) { threshold = thresh; }

   void SetOp(int oper) { op = oper; }

   /** @brief Set the maximum ratio of refinement levels of adjacent elements
       (0 = unlimited). */
   void SetNCLimit(int nc_limit_)
   {
      MFEM_ASSERT(nc_limit_ >= 0, "Invalid NC limit");
      nc_limit = nc_limit_;
   }

   /// Reset the associated estimator.
   virtual void Reset() { estimator.Reset(); }
};

/** @brief Refinement operator to control data oscillation.

    This class computes osc_K(f) := || h ⋅ (I - Π) f ||_K  at each element K.
    Here, Π is the L2-projection and ||⋅||_K is the L2-norm, restricted to the
    element K. All elements satisfying the inequality
    \code
       osc_K(f) > threshold ⋅ ||f|| / sqrt(n_el),
    \endcode
    are refined. Here, threshold is a positive parameter, ||⋅|| is the L2-norm
    over the entire domain Ω, and n_el is the number of elements in the mesh.

    Note that if osc(f) = threshold ⋅ ||f|| / sqrt(n_el) for each K, then
    \code
       osc(f) = sqrt(sum_K osc_K^2(f)) = threshold ⋅ ||f||.
    \endcode
    This is the reason for the 1/sqrt(n_el) factor.
*/
class CoefficientRefiner : public MeshOperator
{
protected:
   bool print_level = false;
   int nc_limit = 1;
   int nonconforming = -1;
   int order;
   long max_elements = std::numeric_limits<long>::max();
   double threshold = 1.0e-2;
   double global_osc = NAN;
   Array<int> mesh_refinements;
   Vector element_oscs;
   Coefficient *coeff = NULL;
   const IntegrationRule *ir_default[Geometry::NumGeom];
   const IntegrationRule **irs = NULL;

   /** @brief Apply the operator to the mesh once.
       @return STOP if a stopping criterion is satisfied or no elements were
       marked for refinement; REFINED + CONTINUE otherwise. */
   virtual int ApplyImpl(Mesh &mesh);

public:
   /// Constructor
   CoefficientRefiner(Coefficient &coeff_, int order_)
   {
      // function f
      coeff = &coeff_;

      // order of the projection Π
      order = order_;
   }

   /** @brief Apply the operator to the mesh max_it times or until tolerance
    *  achieved.
       @return STOP if a stopping criterion is satisfied or no elements were
       marked for refinement; REFINED + CONTINUE otherwise. */
   virtual int PreprocessMesh(Mesh &mesh, int max_it);

   int PreprocessMesh(Mesh &mesh)
   {
      int max_it = 10;
      return PreprocessMesh(mesh, max_it);
   }

   /// Set the refinement threshold. The default value is 1.0e-2.
   void SetThreshold(double threshold_) { threshold = threshold_; }

   /** @brief Set the maximum number of elements stopping criterion: stop when
       the input mesh has num_elements >= max_elem. The default value is
       LONG_MAX. */
   void SetMaxElements(long max_elements_) { max_elements = max_elements_; }

   /// Reset the function f
   void ResetCoefficient(Coefficient &coeff_)
   {
      element_oscs.Destroy();
      global_osc = NAN;
      coeff = &coeff_;
   }

   /// Reset the oscillation order
   void SetOrder(double order_) { order = order_; }

   /** @brief Set the maximum ratio of refinement levels of adjacent elements
       (0 = unlimited). The default value is 1, which helps ensure appropriate
       refinements in pathological situations where the default quadrature
       order is too low.  */
   void SetNCLimit(int nc_limit_)
   {
      MFEM_ASSERT(nc_limit_ >= 0, "Invalid NC limit");
      nc_limit = nc_limit_;
   }

   // Set a custom integration rule
   void SetIntRule(const IntegrationRule *irs_[]) { irs = irs_; }

   // Set print level
   void PrintWarnings() { print_level = true; }

   // Return the value of the global relative data oscillation
   double GetOsc() const { return global_osc; }

   // Return the local relative data oscillation errors
   const Vector & GetLocalOscs() const
   {
      MFEM_ASSERT(element_oscs.Size() > 0,
                  "Local oscillations have not been computed yet")
      return element_oscs;
   }

   /// Reset
   virtual void Reset();
};

/** @brief ParMesh rebalancing operator.

    If the mesh is a parallel mesh, perform rebalancing; otherwise, do nothing.
*/
class Rebalancer : public MeshOperator
{
protected:
   /** @brief Rebalance a parallel mesh (only non-conforming parallel meshes are
       supported).
       @return CONTINUE + REBALANCE on success, NONE otherwise. */
   virtual int ApplyImpl(Mesh &mesh);

public:
   /// Empty.
   virtual void Reset() { }
};

} // namespace mfem

#endif // MFEM_MESH_OPERATORS
<commit_msg>Remove convertion warning from `double` to `int`.<commit_after>// Copyright (c) 2010-2022, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.

#ifndef MFEM_MESH_OPERATORS
#define MFEM_MESH_OPERATORS

#include "../config/config.hpp"
#include "../general/array.hpp"
#include "mesh.hpp"
#include "../fem/estimators.hpp"

#include <limits>

namespace mfem
{

/** @brief The MeshOperator class serves as base for mesh manipulation classes.

    The purpose of the class is to provide a common abstraction for various
    AMR mesh control schemes. The typical use in an AMR loop is illustrated
    in examples 6/6p and 15/15p.

    A more general loop that also supports sequences of mesh operators with
    multiple updates looks like this:
    \code
       for (...)
       {
          // computations on the current mesh ...
          while (mesh_operator->Apply(mesh))
          {
             // update FiniteElementSpaces and interpolate GridFunctions ...
             if (mesh_operator->Continue()) { break; }
          }
          if (mesh_operator->Stop()) { break; }
       }
    \endcode
 */
class MeshOperator
{
private:
   int mod;

protected:
   friend class MeshOperatorSequence;

   /** @brief Implementation of the mesh operation. Invoked by the Apply()
              public method.
       @return Combination of ActionInfo constants. */
   virtual int ApplyImpl(Mesh &mesh) = 0;

   /// Constructor to be used by derived classes.
   MeshOperator() : mod(NONE) { }

public:
   /** @brief Action and information constants and masks.

       Combinations of constants are returned by the Apply() virtual method and
       can be accessed directly with GetActionInfo() or indirectly with methods
       like Stop(), Continue(), etc. The information bits (MASK_INFO) can be set
       only when the update bit is set (see MASK_UPDATE). */
   enum Action
   {
      NONE        = 0, /**< continue with computations without updating spaces
                            or grid-functions, i.e. the mesh was not modified */
      CONTINUE    = 1, /**< update spaces and grid-functions and continue
                            computations with the new mesh */
      STOP        = 2, ///< a stopping criterion was satisfied
      REPEAT      = 3, /**< update spaces and grid-functions and call the
                            operator Apply() method again */
      MASK_UPDATE = 1, ///< bit mask for the "update" bit
      MASK_ACTION = 3  ///< bit mask for all "action" bits
   };

   enum Info
   {
      REFINED     = 4*1, ///< the mesh was refined
      DEREFINED   = 4*2, ///< the mesh was de-refined
      REBALANCED  = 4*3, ///< the mesh was rebalanced
      MASK_INFO   = ~3   ///< bit mask for all "info" bits
   };

   /** @brief Perform the mesh operation.
       @return true if FiniteElementSpaces and GridFunctions need to be updated.
   */
   bool Apply(Mesh &mesh) { return ((mod = ApplyImpl(mesh)) & MASK_UPDATE); }

   /** @brief Check if STOP action is requested, e.g. stopping criterion is
       satisfied. */
   bool Stop() const { return ((mod & MASK_ACTION) == STOP); }
   /** @brief Check if REPEAT action is requested, i.e. FiniteElementSpaces and
       GridFunctions need to be updated, and Apply() must be called again. */
   bool Repeat() const { return ((mod & MASK_ACTION) == REPEAT); }
   /** @brief Check if CONTINUE action is requested, i.e. FiniteElementSpaces
       and GridFunctions need to be updated and computations should continue. */
   bool Continue() const { return ((mod & MASK_ACTION) == CONTINUE); }

   /// Check if the mesh was refined.
   bool Refined() const { return ((mod & MASK_INFO) == REFINED); }
   /// Check if the mesh was de-refined.
   bool Derefined() const { return ((mod & MASK_INFO) == DEREFINED); }
   /// Check if the mesh was rebalanced.
   bool Rebalanced() const { return ((mod & MASK_INFO) == REBALANCED); }

   /** @brief Get the full ActionInfo value generated by the last call to
       Apply(). */
   int GetActionInfo() const { return mod; }

   /// Reset the MeshOperator.
   virtual void Reset() = 0;

   /// The destructor is virtual.
   virtual ~MeshOperator() { }
};

/** Composition of MeshOperators into a sequence. Use the Append() method to
    create the sequence. */
class MeshOperatorSequence : public MeshOperator
{
protected:
   int step;
   Array<MeshOperator*> sequence; ///< MeshOperators sequence, owned by us.

   /// Do not allow copy construction, due to assumed ownership.
   MeshOperatorSequence(const MeshOperatorSequence &) { }

   /// Do not allow copy assignment, due to assumed ownership.
   MeshOperatorSequence& operator=(const MeshOperatorSequence &s) = delete;

   /** @brief Apply the MeshOperatorSequence.
       @return ActionInfo value corresponding to the last applied operator from
       the sequence. */
   virtual int ApplyImpl(Mesh &mesh);

public:
   /// Constructor. Use the Append() method to create the sequence.
   MeshOperatorSequence() : step(-1) { }

   /// Delete all operators from the sequence.
   virtual ~MeshOperatorSequence();

   /** @brief Add an operator to the end of the sequence.
       The MeshOperatorSequence assumes ownership of the operator. */
   void Append(MeshOperator *mc) { sequence.Append(mc); }

   /// Access the underlying sequence.
   Array<MeshOperator*> &GetSequence() { return sequence; }

   /// Reset all MeshOperators in the sequence.
   virtual void Reset();
};

/** @brief Mesh refinement operator using an error threshold.

    This class uses the given ErrorEstimator to estimate local element errors
    and then marks for refinement all elements i such that loc_err_i > threshold.
    The threshold is computed as
    \code
       threshold = max(total_err * total_fraction * pow(num_elements,-1.0/p),
                       local_err_goal);
    \endcode
    where p (=total_norm_p), total_fraction, and local_err_goal are settable
    parameters, total_err = (sum_i local_err_i^p)^{1/p}, when p < inf,
    or total_err = max_i local_err_i, when p = inf.
*/
class ThresholdRefiner : public MeshOperator
{
protected:
   ErrorEstimator &estimator;
   AnisotropicErrorEstimator *aniso_estimator;

   double total_norm_p;
   double total_err_goal;
   double total_fraction;
   double local_err_goal;
   long   max_elements;

   double threshold;
   long num_marked_elements;

   Array<Refinement> marked_elements;
   long current_sequence;

   int non_conforming;
   int nc_limit;

   double GetNorm(const Vector &local_err, Mesh &mesh) const;

   /** @brief Apply the operator to the mesh.
       @return STOP if a stopping criterion is satisfied or no elements were
       marked for refinement; REFINED + CONTINUE otherwise. */
   virtual int ApplyImpl(Mesh &mesh);

public:
   /// Construct a ThresholdRefiner using the given ErrorEstimator.
   ThresholdRefiner(ErrorEstimator &est);

   // default destructor (virtual)

   /** @brief Set the exponent, p, of the discrete p-norm used to compute the
       total error from the local element errors. */
   void SetTotalErrorNormP(double norm_p = infinity())
   { total_norm_p = norm_p; }

   /** @brief Set the total error stopping criterion: stop when
       total_err <= total_err_goal. The default value is zero. */
   void SetTotalErrorGoal(double err_goal) { total_err_goal = err_goal; }

   /** @brief Set the total fraction used in the computation of the threshold.
       The default value is 1/2.
       @note If fraction == 0, total_err is essentially ignored in the threshold
       computation, i.e. threshold = local error goal. */
   void SetTotalErrorFraction(double fraction) { total_fraction = fraction; }

   /** @brief Set the local stopping criterion: stop when
       local_err_i <= local_err_goal. The default value is zero.
       @note If local_err_goal == 0, it is essentially ignored in the threshold
       computation. */
   void SetLocalErrorGoal(double err_goal) { local_err_goal = err_goal; }

   /** @brief Set the maximum number of elements stopping criterion: stop when
       the input mesh has num_elements >= max_elem. The default value is
       LONG_MAX. */
   void SetMaxElements(long max_elem) { max_elements = max_elem; }

   /// Use nonconforming refinement, if possible (triangles, quads, hexes).
   void PreferNonconformingRefinement() { non_conforming = 1; }

   /** @brief Use conforming refinement, if possible (triangles, tetrahedra)
       -- this is the default. */
   void PreferConformingRefinement() { non_conforming = -1; }

   /** @brief Set the maximum ratio of refinement levels of adjacent elements
       (0 = unlimited). */
   void SetNCLimit(int nc_limit_)
   {
      MFEM_ASSERT(nc_limit_ >= 0, "Invalid NC limit");
      nc_limit = nc_limit_;
   }

   /// Get the number of marked elements in the last Apply() call.
   long GetNumMarkedElements() const { return num_marked_elements; }

   /// Get the threshold used in the last Apply() call.
   double GetThreshold() const { return threshold; }

   /// Reset the associated estimator.
   virtual void Reset();
};

// TODO: BulkRefiner to refine a portion of the global error

/** @brief De-refinement operator using an error threshold.

    This de-refinement operator marks elements in the hierarchy whose children
    are leaves and their combined error is below a given threshold. The
    errors of the children are combined by one of the following operations:
    - op = 0: minimum of the errors
    - op = 1: sum of the errors (default)
    - op = 2: maximum of the errors. */
class ThresholdDerefiner : public MeshOperator
{
protected:
   ErrorEstimator &estimator;

   double threshold;
   int nc_limit, op;

   /** @brief Apply the operator to the mesh.
       @return DEREFINED + CONTINUE if some elements were de-refined; NONE
       otherwise. */
   virtual int ApplyImpl(Mesh &mesh);

public:
   /// Construct a ThresholdDerefiner using the given ErrorEstimator.
   ThresholdDerefiner(ErrorEstimator &est)
      : estimator(est)
   {
      threshold = 0.0;
      nc_limit = 0;
      op = 1;
   }

   // default destructor (virtual)

   /// Set the de-refinement threshold. The default value is zero.
   void SetThreshold(double thresh) { threshold = thresh; }

   void SetOp(int oper) { op = oper; }

   /** @brief Set the maximum ratio of refinement levels of adjacent elements
       (0 = unlimited). */
   void SetNCLimit(int nc_limit_)
   {
      MFEM_ASSERT(nc_limit_ >= 0, "Invalid NC limit");
      nc_limit = nc_limit_;
   }

   /// Reset the associated estimator.
   virtual void Reset() { estimator.Reset(); }
};

/** @brief Refinement operator to control data oscillation.

    This class computes osc_K(f) := || h ⋅ (I - Π) f ||_K  at each element K.
    Here, Π is the L2-projection and ||⋅||_K is the L2-norm, restricted to the
    element K. All elements satisfying the inequality
    \code
       osc_K(f) > threshold ⋅ ||f|| / sqrt(n_el),
    \endcode
    are refined. Here, threshold is a positive parameter, ||⋅|| is the L2-norm
    over the entire domain Ω, and n_el is the number of elements in the mesh.

    Note that if osc(f) = threshold ⋅ ||f|| / sqrt(n_el) for each K, then
    \code
       osc(f) = sqrt(sum_K osc_K^2(f)) = threshold ⋅ ||f||.
    \endcode
    This is the reason for the 1/sqrt(n_el) factor.
*/
class CoefficientRefiner : public MeshOperator
{
protected:
   bool print_level = false;
   int nc_limit = 1;
   int nonconforming = -1;
   int order;
   long max_elements = std::numeric_limits<long>::max();
   double threshold = 1.0e-2;
   double global_osc = NAN;
   Array<int> mesh_refinements;
   Vector element_oscs;
   Coefficient *coeff = NULL;
   const IntegrationRule *ir_default[Geometry::NumGeom];
   const IntegrationRule **irs = NULL;

   /** @brief Apply the operator to the mesh once.
       @return STOP if a stopping criterion is satisfied or no elements were
       marked for refinement; REFINED + CONTINUE otherwise. */
   virtual int ApplyImpl(Mesh &mesh);

public:
   /// Constructor
   CoefficientRefiner(Coefficient &coeff_, int order_)
   {
      // function f
      coeff = &coeff_;

      // order of the projection Π
      order = order_;
   }

   /** @brief Apply the operator to the mesh max_it times or until tolerance
    *  achieved.
       @return STOP if a stopping criterion is satisfied or no elements were
       marked for refinement; REFINED + CONTINUE otherwise. */
   virtual int PreprocessMesh(Mesh &mesh, int max_it);

   int PreprocessMesh(Mesh &mesh)
   {
      int max_it = 10;
      return PreprocessMesh(mesh, max_it);
   }

   /// Set the refinement threshold. The default value is 1.0e-2.
   void SetThreshold(double threshold_) { threshold = threshold_; }

   /** @brief Set the maximum number of elements stopping criterion: stop when
       the input mesh has num_elements >= max_elem. The default value is
       LONG_MAX. */
   void SetMaxElements(long max_elements_) { max_elements = max_elements_; }

   /// Reset the function f
   void ResetCoefficient(Coefficient &coeff_)
   {
      element_oscs.Destroy();
      global_osc = NAN;
      coeff = &coeff_;
   }

   /// Reset the oscillation order
   void SetOrder(int order_) { order = order_; }

   /** @brief Set the maximum ratio of refinement levels of adjacent elements
       (0 = unlimited). The default value is 1, which helps ensure appropriate
       refinements in pathological situations where the default quadrature
       order is too low.  */
   void SetNCLimit(int nc_limit_)
   {
      MFEM_ASSERT(nc_limit_ >= 0, "Invalid NC limit");
      nc_limit = nc_limit_;
   }

   // Set a custom integration rule
   void SetIntRule(const IntegrationRule *irs_[]) { irs = irs_; }

   // Set print level
   void PrintWarnings() { print_level = true; }

   // Return the value of the global relative data oscillation
   double GetOsc() const { return global_osc; }

   // Return the local relative data oscillation errors
   const Vector & GetLocalOscs() const
   {
      MFEM_ASSERT(element_oscs.Size() > 0,
                  "Local oscillations have not been computed yet")
      return element_oscs;
   }

   /// Reset
   virtual void Reset();
};

/** @brief ParMesh rebalancing operator.

    If the mesh is a parallel mesh, perform rebalancing; otherwise, do nothing.
*/
class Rebalancer : public MeshOperator
{
protected:
   /** @brief Rebalance a parallel mesh (only non-conforming parallel meshes are
       supported).
       @return CONTINUE + REBALANCE on success, NONE otherwise. */
   virtual int ApplyImpl(Mesh &mesh);

public:
   /// Empty.
   virtual void Reset() { }
};

} // namespace mfem

#endif // MFEM_MESH_OPERATORS
<|endoftext|>