<commit_before>// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-

/* This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2
 * as published by the Free Software Foundation.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 *
 * Authors:
 * Caner Candan <caner.candan@univ-angers.fr>
 */

#include <boost/mpi.hpp>
#include <eo>
#include <dim/dim>
#include <dim/algo/Easy.h>
#include <dim/evolver/Easy.h>
#include <dim/feedbacker/Easy.h>
#include <dim/migrator/Easy.h>
#include <dim/vectorupdater/Easy.h>

using namespace std;
using namespace boost::mpi;
using namespace boost;

typedef dim::core::Bit<double> EOT;

class SimulatedOp : public eoMonOp<EOT>
{
public:
    SimulatedOp(size_t timeout) : _timeout(timeout) {}

    /// The class name.
    virtual std::string className() const { return "SimulatedOp"; }

    bool operator()(EOT&)
    {
	std::this_thread::sleep_for(std::chrono::milliseconds( _timeout ));
	return true;
    }

private:
    size_t _timeout;
};

class SimulatedEval : public eoEvalFunc<EOT>
{
public:
    SimulatedEval(typename EOT::Fitness fit) : _fit(fit) {}

    /// The class name.
    virtual string className() const { return "SimulatedEval"; }

    void operator()(EOT& sol)
    {
	sol.fitness( sol.fitness() + _fit );
    }

private:
    typename EOT::Fitness _fit;
};

class FitnessInit : public eoUF<EOT&, void>
{
public:
    void operator()(EOT& sol)
    {
	sol.fitness( 0 );
    }
};

int main (int argc, char *argv[])
{
    /*************************
     * Initialisation de MPI *
     *************************/

    environment env(argc, argv, MPI_THREAD_MULTIPLE, true);
    communicator world;

    /****************************
     * Il faut au moins 4 nœuds *
     ****************************/

    const size_t ALL = world.size();
    const size_t RANK = world.rank();

    // if ( ALL < 4 )
    // 	{
    // 	    if ( 0 == RANK )
    // 		{
    // 		    cerr << "Needs at least 4 processes to be launched!" << endl;
    // 		}
    // 	    return 0;
    // 	}

    /************************
     * Initialisation de EO *
     ************************/

    eoParser parser(argc, argv);
    eoState state;    // keeps all things allocated

    /*****************************
     * Definition des paramètres *
     *****************************/

    // a
    double alpha = parser.createParam(double(0.8), "alpha", "Alpha", 'a', "Islands Model").value();
    // b
    double beta = parser.createParam(double(0.99), "beta", "Beta", 'b', "Islands Model").value();
    // p
    /*size_t probaMin = */parser.createParam(size_t(10), "probaMin", "Minimum probability to stay in the same island", 'p', "Islands Model").value();
    // d
    size_t probaSame = parser.createParam(size_t(100/ALL), "probaSame", "Probability for an individual to stay in the same island", 'd', "Islands Model").value();
    // r
    /*size_t reward = */parser.createParam(size_t(2), "reward", "reward", 'r', "Islands Model")/*.value()*/;
    /*size_t penalty = */parser.createParam(size_t(1), "penalty", "penalty", 0, "Islands Model")/*.value()*/;
    // I
    bool initG = parser.createParam(bool(true), "initG", "initG", 'I', "Islands Model").value();

    /*********************************
     * Déclaration des composants EO *
     *********************************/

    /*unsigned chromSize = */parser.getORcreateParam(unsigned(0), "chromSize", "The length of the bitstrings", 'n',"Problem")/*.value()*/;
    eoInit<EOT>& init = dim::do_make::genotype(parser, state, EOT(), 0);

    size_t timeout = pow(10, RANK);
    // size_t timeout = 10000;

    eoEvalFunc<EOT>* ptEval = NULL;
    ptEval = new SimulatedEval(1);
    state.storeFunctor(ptEval);

    // eoEvalFunc<EOT>* ptEval = NULL;
    // if ( 0 == RANK )
    // 	{
    // 	    ptEval = new SimulatedEval(1);
    // 	}
    // else if ( 1 == RANK )
    // 	{
    // 	    ptEval = new SimulatedEval(5);
    // 	}
    // else if ( 2 == RANK )
    // 	{
    // 	    ptEval = new SimulatedEval(10);
    // 	}
    // else if ( 3 == RANK )
    // 	{
    // 	    ptEval = new SimulatedEval(15);
    // 	}
    // state.storeFunctor(ptEval);

    eoEvalFuncCounter<EOT> eval(*ptEval);

    /*unsigned popSize = */parser.getORcreateParam(unsigned(100), "popSize", "Population Size", 'P', "Evolution Engine")/*.value()*/;
    dim::core::Pop<EOT>& pop = dim::do_make::detail::pop(parser, state, init);

    /*double targetFitness = */parser.getORcreateParam(double(1000), "targetFitness", "Stop when fitness reaches",'T', "Stopping criterion")/*.value()*/;
    /*unsigned maxGen = */parser.getORcreateParam(unsigned(0), "maxGen", "Maximum number of generations () = none)",'G',"Stopping criterion")/*.value()*/;
    dim::continuator::Base<EOT>& continuator = dim::do_make::continuator<EOT>(parser, state, eval);

    dim::core::IslandData<EOT> data;

    dim::utils::CheckPoint<EOT>& checkpoint = dim::do_make::checkpoint(parser, state, continuator, data);

    /**************
     * EO routine *
     **************/

    make_parallel(parser);
    make_verbose(parser);
    make_help(parser);

    /****************************************
     * Distribution des opérateurs aux iles *
     ****************************************/

    eoMonOp<EOT>* ptMon = NULL;
    ptMon = new SimulatedOp(timeout);
    state.storeFunctor(ptMon);

    // if ( 0 == RANK )
    // 	{
    // 	    ptMon = new SimulatedOp(1);
    // 	}
    // else if ( 1 == RANK )
    // 	{
    // 	    ptMon = new SimulatedOp(5);
    // 	}
    // else if ( 2 == RANK )
    // 	{
    // 	    ptMon = new SimulatedOp(10);
    // 	}
    // else if ( 3 == RANK )
    // 	{
    // 	    ptMon = new SimulatedOp(15);
    // 	}
    // state.storeFunctor(ptMon);

    // /**********************************
    //  * Déclaration des composants DIM *
    //  **********************************/

    dim::core::ThreadsRunner< dim::core::Pop<EOT>&, dim::core::IslandData<EOT>& > tr;

    dim::evolver::Easy<EOT> evolver( /*eval*/*ptEval, *ptMon );
    dim::feedbacker::async::Easy<EOT> feedbacker;
    dim::vectorupdater::Easy<EOT> updater(alpha, beta);
    dim::memorizer::Easy<EOT> memorizer;
    dim::migrator::async::Easy<EOT> migrator;
    dim::algo::Easy<EOT> island( evolver, feedbacker, updater, memorizer, migrator, checkpoint );

    tr.addHandler(feedbacker).addHandler(migrator).add(island);

    /***************
     * Rock & Roll *
     ***************/

    /******************************************************************************
     * Création de la matrice de transition et distribution aux iles des vecteurs *
     ******************************************************************************/

    dim::core::MigrationMatrix<EOT> probabilities( ALL );
    dim::core::InitMatrix<EOT> initmatrix( initG, probaSame );

    if ( 0 == RANK )
    	{
    	    initmatrix( probabilities );
    	    std::cout << probabilities;
    	    data.proba = probabilities(RANK);

    	    for (size_t i = 1; i < ALL; ++i)
    		{
    		    world.send( i, 100, probabilities(i) );
    		}
    	}
    else
    	{
    	    world.recv( 0, 100, data.proba );
    	}

    /******************************************
     * Get the population size of all islands *
     ******************************************/

    world.barrier();
    dim::utils::print_sum(pop);

    FitnessInit fitInit;

    apply<EOT>(fitInit, pop);

    tr( pop, data );

    world.abort(0);

    return 0 ;
}
<commit_msg>* ../../../application/simulation/threaded.cpp: replaced default value of alpha and beta + changed reward values and temporisation to a uniform way for test purpose<commit_after>// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-

/* This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2
 * as published by the Free Software Foundation.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 *
 * Authors:
 * Caner Candan <caner.candan@univ-angers.fr>
 */

#include <boost/mpi.hpp>
#include <eo>
#include <dim/dim>
#include <dim/algo/Easy.h>
#include <dim/evolver/Easy.h>
#include <dim/feedbacker/Easy.h>
#include <dim/migrator/Easy.h>
#include <dim/vectorupdater/Easy.h>

using namespace std;
using namespace boost::mpi;
using namespace boost;

typedef dim::core::Bit<double> EOT;

class SimulatedOp : public eoMonOp<EOT>
{
public:
    SimulatedOp(size_t timeout) : _timeout(timeout) {}

    /// The class name.
    virtual std::string className() const { return "SimulatedOp"; }

    bool operator()(EOT&)
    {
	std::this_thread::sleep_for(std::chrono::milliseconds( _timeout ));
	return true;
    }

private:
    size_t _timeout;
};

class SimulatedEval : public eoEvalFunc<EOT>
{
public:
    SimulatedEval(typename EOT::Fitness fit) : _fit(fit) {}

    /// The class name.
    virtual string className() const { return "SimulatedEval"; }

    void operator()(EOT& sol)
    {
	sol.fitness( sol.fitness() + _fit );
    }

private:
    typename EOT::Fitness _fit;
};

class FitnessInit : public eoUF<EOT&, void>
{
public:
    void operator()(EOT& sol)
    {
	sol.fitness( 0 );
    }
};

int main (int argc, char *argv[])
{
    /*************************
     * Initialisation de MPI *
     *************************/

    environment env(argc, argv, MPI_THREAD_MULTIPLE, true);
    communicator world;

    /****************************
     * Il faut au moins 4 nœuds *
     ****************************/

    const size_t ALL = world.size();
    const size_t RANK = world.rank();

    // if ( ALL < 4 )
    // 	{
    // 	    if ( 0 == RANK )
    // 		{
    // 		    cerr << "Needs at least 4 processes to be launched!" << endl;
    // 		}
    // 	    return 0;
    // 	}

    /************************
     * Initialisation de EO *
     ************************/

    eoParser parser(argc, argv);
    eoState state;    // keeps all things allocated

    /*****************************
     * Definition des paramètres *
     *****************************/

    // a
    // double alpha = parser.createParam(double(0.8), "alpha", "Alpha", 'a', "Islands Model").value();
    double alpha = parser.createParam(double(0.2), "alpha", "Alpha", 'a', "Islands Model").value();
    // b
    // double beta = parser.createParam(double(0.99), "beta", "Beta", 'b', "Islands Model").value();
    double beta = parser.createParam(double(0.01), "beta", "Beta", 'b', "Islands Model").value();
    // p
    /*size_t probaMin = */parser.createParam(size_t(10), "probaMin", "Minimum probability to stay in the same island", 'p', "Islands Model").value();
    // d
    size_t probaSame = parser.createParam(size_t(100/ALL), "probaSame", "Probability for an individual to stay in the same island", 'd', "Islands Model").value();
    // r
    /*size_t reward = */parser.createParam(size_t(2), "reward", "reward", 'r', "Islands Model")/*.value()*/;
    /*size_t penalty = */parser.createParam(size_t(1), "penalty", "penalty", 0, "Islands Model")/*.value()*/;
    // I
    bool initG = parser.createParam(bool(true), "initG", "initG", 'I', "Islands Model").value();

    /*********************************
     * Déclaration des composants EO *
     *********************************/

    /*unsigned chromSize = */parser.getORcreateParam(unsigned(0), "chromSize", "The length of the bitstrings", 'n',"Problem")/*.value()*/;
    eoInit<EOT>& init = dim::do_make::genotype(parser, state, EOT(), 0);

    // size_t timeout = pow(10, RANK);
    // size_t timeout = RANK+1;
    // size_t timeout = 1;

    // eoEvalFunc<EOT>* ptEval = NULL;
    // ptEval = new SimulatedEval(1);
    // state.storeFunctor(ptEval);

    eoEvalFunc<EOT>* ptEval = NULL;
    if ( 0 == RANK )
    	{
    	    ptEval = new SimulatedEval(1);
    	}
    else if ( 1 == RANK )
    	{
    	    ptEval = new SimulatedEval(1);
    	}
    else if ( 2 == RANK )
    	{
    	    ptEval = new SimulatedEval(1);
    	}
    else if ( 3 == RANK )
    	{
    	    ptEval = new SimulatedEval(1);
    	}
    state.storeFunctor(ptEval);

    eoEvalFuncCounter<EOT> eval(*ptEval);

    /*unsigned popSize = */parser.getORcreateParam(unsigned(100), "popSize", "Population Size", 'P', "Evolution Engine")/*.value()*/;
    dim::core::Pop<EOT>& pop = dim::do_make::detail::pop(parser, state, init);

    /*double targetFitness = */parser.getORcreateParam(double(1000), "targetFitness", "Stop when fitness reaches",'T', "Stopping criterion")/*.value()*/;
    /*unsigned maxGen = */parser.getORcreateParam(unsigned(0), "maxGen", "Maximum number of generations () = none)",'G',"Stopping criterion")/*.value()*/;
    dim::continuator::Base<EOT>& continuator = dim::do_make::continuator<EOT>(parser, state, eval);

    dim::core::IslandData<EOT> data;

    dim::utils::CheckPoint<EOT>& checkpoint = dim::do_make::checkpoint(parser, state, continuator, data);

    /**************
     * EO routine *
     **************/

    make_parallel(parser);
    make_verbose(parser);
    make_help(parser);

    /****************************************
     * Distribution des opérateurs aux iles *
     ****************************************/

    eoMonOp<EOT>* ptMon = NULL;
    // ptMon = new SimulatedOp(timeout);
    // state.storeFunctor(ptMon);

    if ( 0 == RANK )
    	{
    	    ptMon = new SimulatedOp(1);
    	}
    else if ( 1 == RANK )
    	{
    	    ptMon = new SimulatedOp(1);
    	}
    else if ( 2 == RANK )
    	{
    	    ptMon = new SimulatedOp(1);
    	}
    else if ( 3 == RANK )
    	{
    	    ptMon = new SimulatedOp(1);
    	}
    state.storeFunctor(ptMon);

    // /**********************************
    //  * Déclaration des composants DIM *
    //  **********************************/

    dim::core::ThreadsRunner< dim::core::Pop<EOT>&, dim::core::IslandData<EOT>& > tr;

    dim::evolver::Easy<EOT> evolver( /*eval*/*ptEval, *ptMon );
    dim::feedbacker::async::Easy<EOT> feedbacker;
    dim::vectorupdater::Easy<EOT> updater(alpha, beta);
    dim::memorizer::Easy<EOT> memorizer;
    dim::migrator::async::Easy<EOT> migrator;
    dim::algo::Easy<EOT> island( evolver, feedbacker, updater, memorizer, migrator, checkpoint );

    tr.addHandler(feedbacker).addHandler(migrator).add(island);

    /***************
     * Rock & Roll *
     ***************/

    /******************************************************************************
     * Création de la matrice de transition et distribution aux iles des vecteurs *
     ******************************************************************************/

    dim::core::MigrationMatrix<EOT> probabilities( ALL );
    dim::core::InitMatrix<EOT> initmatrix( initG, probaSame );

    if ( 0 == RANK )
    	{
    	    initmatrix( probabilities );
    	    std::cout << probabilities;
    	    data.proba = probabilities(RANK);

    	    for (size_t i = 1; i < ALL; ++i)
    		{
    		    world.send( i, 100, probabilities(i) );
    		}
    	}
    else
    	{
    	    world.recv( 0, 100, data.proba );
    	}

    /******************************************
     * Get the population size of all islands *
     ******************************************/

    world.barrier();
    dim::utils::print_sum(pop);

    FitnessInit fitInit;

    apply<EOT>(fitInit, pop);

    tr( pop, data );

    world.abort(0);

    return 0 ;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ReportComponentHandler.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: kz $ $Date: 2008-03-05 18:10:38 $
 *
 *  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 "precompiled_reportdesign.hxx"

#ifndef RPT_REPORTCOMPONENTHANDLER_HXX
#include "ReportComponentHandler.hxx"
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _COMPHELPER_SEQUENCE_HXX_
#include <comphelper/sequence.hxx>
#endif
#ifndef REPORTDESIGN_SHARED_UISTRINGS_HRC
#include "uistrings.hrc"
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef _TOOLKIT_HELPER_VCLUNOHELPER_HXX_
#include <toolkit/helper/vclunohelper.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_SYSLOCALE_HXX
#include <svtools/syslocale.hxx>
#endif
#ifndef _COM_SUN_STAR_INSPECTION_PROPERTYCONTROLTYPE_HPP_
#include <com/sun/star/inspection/PropertyControlType.hpp>
#endif
#ifndef _COM_SUN_STAR_REPORT_XREPORTDEFINITION_HPP_
#include <com/sun/star/report/XReportDefinition.hpp>
#endif
#ifndef _COM_SUN_STAR_REPORT_XSECTION_HPP_
#include <com/sun/star/report/XSection.hpp>
#endif
#ifndef _COM_SUN_STAR_INSPECTION_XNUMERICCONTROL_HPP_
#include <com/sun/star/inspection/XNumericControl.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_
#include <com/sun/star/container/XNameContainer.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_MEASUREUNIT_HPP_
#include <com/sun/star/util/MeasureUnit.hpp>
#endif
#ifndef _VCL_FLDUNIT_HXX
#include <vcl/fldunit.hxx>
#endif
#ifndef RPTUI_METADATA_HXX_
#include "metadata.hxx"
#endif

//........................................................................
namespace rptui
{
//........................................................................
using namespace ::com::sun::star;
// using namespace comphelper;

ReportComponentHandler::ReportComponentHandler(uno::Reference< uno::XComponentContext > const & context)
    :ReportComponentHandler_Base(m_aMutex)
    ,m_xContext(context)
    ,m_pInfoService( new OPropertyInfoService() )
{
    try
    {
        m_xFormComponentHandler.set(m_xContext->getServiceManager()->createInstanceWithContext(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.form.inspection.FormComponentPropertyHandler")),m_xContext),uno::UNO_QUERY_THROW);

    }catch(uno::Exception)
    {
    }
}

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

//------------------------------------------------------------------------
sal_Bool SAL_CALL ReportComponentHandler::supportsService( const ::rtl::OUString& ServiceName ) throw(uno::RuntimeException)
{
    return ::comphelper::existsValue(ServiceName,getSupportedServiceNames_static());
}

//------------------------------------------------------------------------
uno::Sequence< ::rtl::OUString > SAL_CALL ReportComponentHandler::getSupportedServiceNames(  ) throw(uno::RuntimeException)
{
    return getSupportedServiceNames_static();
}

//------------------------------------------------------------------------
::rtl::OUString ReportComponentHandler::getImplementationName_Static(  ) throw(uno::RuntimeException)
{
    return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.comp.report.ReportComponentHandler"));
}

//------------------------------------------------------------------------
uno::Sequence< ::rtl::OUString > ReportComponentHandler::getSupportedServiceNames_static(  ) throw(uno::RuntimeException)
{
    uno::Sequence< ::rtl::OUString > aSupported(1);
    aSupported[0] = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.report.inspection.ReportComponentHandler"));
    return aSupported;
}

//------------------------------------------------------------------------
uno::Reference< uno::XInterface > SAL_CALL ReportComponentHandler::create( const uno::Reference< uno::XComponentContext >& _rxContext )
{
    return *(new ReportComponentHandler( _rxContext ));
}
// overload WeakComponentImplHelperBase::disposing()
// This function is called upon disposing the component,
// if your component needs special work when it becomes
// disposed, do it here.
void SAL_CALL ReportComponentHandler::disposing()
{
    ::comphelper::disposeComponent(m_xFormComponentHandler);
}
void SAL_CALL ReportComponentHandler::addEventListener(const uno::Reference< lang::XEventListener > & xListener) throw (uno::RuntimeException)
{
    m_xFormComponentHandler->addEventListener(xListener);
}

void SAL_CALL ReportComponentHandler::removeEventListener(const uno::Reference< lang::XEventListener > & aListener) throw (uno::RuntimeException)
{
    m_xFormComponentHandler->removeEventListener(aListener);
}

// inspection::XPropertyHandler:

/********************************************************************************/
void SAL_CALL ReportComponentHandler::inspect(const uno::Reference< uno::XInterface > & Component) throw (uno::RuntimeException, lang::NullPointerException)
{
    try
    {
        uno::Reference< container::XNameContainer > xNameCont(Component,uno::UNO_QUERY);
        const ::rtl::OUString sFormComponent(RTL_CONSTASCII_USTRINGPARAM("FormComponent"));
        if ( xNameCont->hasByName(sFormComponent) )
            xNameCont->getByName(sFormComponent) >>= m_xFormComponent;
        const ::rtl::OUString sRowSet(RTL_CONSTASCII_USTRINGPARAM("RowSet"));
        if ( xNameCont->hasByName(sRowSet) )
        {
            uno::Reference<beans::XPropertySet> xProp(m_xFormComponentHandler,uno::UNO_QUERY);
            xProp->setPropertyValue(sRowSet,xNameCont->getByName(sRowSet));
        }
    }
    catch(uno::Exception)
    {
        throw lang::NullPointerException();
    }
    if ( m_xFormComponent.is() )
    {
        m_xFormComponentHandler->inspect(m_xFormComponent);
    }
}

uno::Any SAL_CALL ReportComponentHandler::getPropertyValue(const ::rtl::OUString & PropertyName) throw (uno::RuntimeException, beans::UnknownPropertyException)
{
    return m_xFormComponentHandler->getPropertyValue(PropertyName);
}

void SAL_CALL ReportComponentHandler::setPropertyValue(const ::rtl::OUString & PropertyName, const uno::Any & Value) throw (uno::RuntimeException, beans::UnknownPropertyException)
{
    m_xFormComponentHandler->setPropertyValue(PropertyName, Value);
}

beans::PropertyState SAL_CALL ReportComponentHandler::getPropertyState(const ::rtl::OUString & PropertyName) throw (uno::RuntimeException, beans::UnknownPropertyException)
{
    return m_xFormComponentHandler->getPropertyState(PropertyName);
}

inspection::LineDescriptor SAL_CALL ReportComponentHandler::describePropertyLine(const ::rtl::OUString & PropertyName,  const uno::Reference< inspection::XPropertyControlFactory > & ControlFactory) throw (beans::UnknownPropertyException, lang::NullPointerException,uno::RuntimeException)
{
    return m_xFormComponentHandler->describePropertyLine(PropertyName, ControlFactory);
}

uno::Any SAL_CALL ReportComponentHandler::convertToPropertyValue(const ::rtl::OUString & PropertyName, const uno::Any & ControlValue) throw (uno::RuntimeException, beans::UnknownPropertyException)
{
    return m_xFormComponentHandler->convertToPropertyValue(PropertyName, ControlValue);
}

uno::Any SAL_CALL ReportComponentHandler::convertToControlValue(const ::rtl::OUString & PropertyName, const uno::Any & PropertyValue, const uno::Type & ControlValueType) throw (uno::RuntimeException, beans::UnknownPropertyException)
{
    return m_xFormComponentHandler->convertToControlValue(PropertyName, PropertyValue, ControlValueType);
}

void SAL_CALL ReportComponentHandler::addPropertyChangeListener(const uno::Reference< beans::XPropertyChangeListener > & Listener) throw (uno::RuntimeException, lang::NullPointerException)
{
    m_xFormComponentHandler->addPropertyChangeListener(Listener);
}

void SAL_CALL ReportComponentHandler::removePropertyChangeListener(const uno::Reference< beans::XPropertyChangeListener > & _rxListener) throw (uno::RuntimeException)
{
    m_xFormComponentHandler->removePropertyChangeListener(_rxListener);
}

uno::Sequence< beans::Property > SAL_CALL ReportComponentHandler::getSupportedProperties() throw (uno::RuntimeException)
{
    ::std::vector< beans::Property > aNewProps;
    m_pInfoService->getExcludeProperties( aNewProps, m_xFormComponentHandler );

    return aNewProps.empty() ? uno::Sequence< beans::Property > () : uno::Sequence< beans::Property > (&(*aNewProps.begin()),aNewProps.size());
}

uno::Sequence< ::rtl::OUString > SAL_CALL ReportComponentHandler::getSupersededProperties() throw (uno::RuntimeException)
{
    uno::Sequence< ::rtl::OUString > aRet;
    return aRet;
}

uno::Sequence< ::rtl::OUString > SAL_CALL ReportComponentHandler::getActuatingProperties() throw (uno::RuntimeException)
{
    return m_xFormComponentHandler->getActuatingProperties();
}

::sal_Bool SAL_CALL ReportComponentHandler::isComposable( const ::rtl::OUString& _rPropertyName ) throw (uno::RuntimeException, beans::UnknownPropertyException)
{
    return m_pInfoService->isComposable( _rPropertyName, m_xFormComponentHandler );
}

inspection::InteractiveSelectionResult SAL_CALL ReportComponentHandler::onInteractivePropertySelection(const ::rtl::OUString & PropertyName, ::sal_Bool Primary, uno::Any & out_Data, const uno::Reference< inspection::XObjectInspectorUI > & InspectorUI) throw (uno::RuntimeException, beans::UnknownPropertyException, lang::NullPointerException)
{
    return m_xFormComponentHandler->onInteractivePropertySelection(PropertyName, Primary, out_Data, InspectorUI);
}

void SAL_CALL ReportComponentHandler::actuatingPropertyChanged(const ::rtl::OUString & ActuatingPropertyName, const uno::Any & NewValue, const uno::Any & OldValue, const uno::Reference< inspection::XObjectInspectorUI > & InspectorUI, ::sal_Bool FirstTimeInit) throw (uno::RuntimeException, lang::NullPointerException)
{
    m_xFormComponentHandler->actuatingPropertyChanged(ActuatingPropertyName, NewValue, OldValue, InspectorUI, FirstTimeInit);
}

::sal_Bool SAL_CALL ReportComponentHandler::suspend(::sal_Bool Suspend) throw (uno::RuntimeException)
{
    return m_xFormComponentHandler->suspend(Suspend);
}

//........................................................................
} // namespace rptui
//........................................................................

<commit_msg>INTEGRATION: CWS changefileheader (1.3.8); FILE MERGED 2008/04/01 15:23:44 thb 1.3.8.3: #i85898# Stripping all external header guards 2008/04/01 12:33:15 thb 1.3.8.2: #i85898# Stripping all external header guards 2008/03/31 13:32:19 rt 1.3.8.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: ReportComponentHandler.cxx,v $
 * $Revision: 1.4 $
 *
 * 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.
 *
 ************************************************************************/
#include "precompiled_reportdesign.hxx"
#include "ReportComponentHandler.hxx"
#include <com/sun/star/lang/XInitialization.hpp>
#include <comphelper/sequence.hxx>
#ifndef REPORTDESIGN_SHARED_UISTRINGS_HRC
#include "uistrings.hrc"
#endif
#include <comphelper/types.hxx>
#include <toolkit/helper/vclunohelper.hxx>
#include <svtools/syslocale.hxx>
#include <com/sun/star/inspection/PropertyControlType.hpp>
#include <com/sun/star/report/XReportDefinition.hpp>
#include <com/sun/star/report/XSection.hpp>
#include <com/sun/star/inspection/XNumericControl.hpp>
#include <com/sun/star/container/XNameContainer.hpp>
#include <com/sun/star/util/MeasureUnit.hpp>
#include <vcl/fldunit.hxx>
#include "metadata.hxx"

//........................................................................
namespace rptui
{
//........................................................................
using namespace ::com::sun::star;
// using namespace comphelper;

ReportComponentHandler::ReportComponentHandler(uno::Reference< uno::XComponentContext > const & context)
    :ReportComponentHandler_Base(m_aMutex)
    ,m_xContext(context)
    ,m_pInfoService( new OPropertyInfoService() )
{
    try
    {
        m_xFormComponentHandler.set(m_xContext->getServiceManager()->createInstanceWithContext(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.form.inspection.FormComponentPropertyHandler")),m_xContext),uno::UNO_QUERY_THROW);

    }catch(uno::Exception)
    {
    }
}

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

//------------------------------------------------------------------------
sal_Bool SAL_CALL ReportComponentHandler::supportsService( const ::rtl::OUString& ServiceName ) throw(uno::RuntimeException)
{
    return ::comphelper::existsValue(ServiceName,getSupportedServiceNames_static());
}

//------------------------------------------------------------------------
uno::Sequence< ::rtl::OUString > SAL_CALL ReportComponentHandler::getSupportedServiceNames(  ) throw(uno::RuntimeException)
{
    return getSupportedServiceNames_static();
}

//------------------------------------------------------------------------
::rtl::OUString ReportComponentHandler::getImplementationName_Static(  ) throw(uno::RuntimeException)
{
    return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.comp.report.ReportComponentHandler"));
}

//------------------------------------------------------------------------
uno::Sequence< ::rtl::OUString > ReportComponentHandler::getSupportedServiceNames_static(  ) throw(uno::RuntimeException)
{
    uno::Sequence< ::rtl::OUString > aSupported(1);
    aSupported[0] = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.report.inspection.ReportComponentHandler"));
    return aSupported;
}

//------------------------------------------------------------------------
uno::Reference< uno::XInterface > SAL_CALL ReportComponentHandler::create( const uno::Reference< uno::XComponentContext >& _rxContext )
{
    return *(new ReportComponentHandler( _rxContext ));
}
// overload WeakComponentImplHelperBase::disposing()
// This function is called upon disposing the component,
// if your component needs special work when it becomes
// disposed, do it here.
void SAL_CALL ReportComponentHandler::disposing()
{
    ::comphelper::disposeComponent(m_xFormComponentHandler);
}
void SAL_CALL ReportComponentHandler::addEventListener(const uno::Reference< lang::XEventListener > & xListener) throw (uno::RuntimeException)
{
    m_xFormComponentHandler->addEventListener(xListener);
}

void SAL_CALL ReportComponentHandler::removeEventListener(const uno::Reference< lang::XEventListener > & aListener) throw (uno::RuntimeException)
{
    m_xFormComponentHandler->removeEventListener(aListener);
}

// inspection::XPropertyHandler:

/********************************************************************************/
void SAL_CALL ReportComponentHandler::inspect(const uno::Reference< uno::XInterface > & Component) throw (uno::RuntimeException, lang::NullPointerException)
{
    try
    {
        uno::Reference< container::XNameContainer > xNameCont(Component,uno::UNO_QUERY);
        const ::rtl::OUString sFormComponent(RTL_CONSTASCII_USTRINGPARAM("FormComponent"));
        if ( xNameCont->hasByName(sFormComponent) )
            xNameCont->getByName(sFormComponent) >>= m_xFormComponent;
        const ::rtl::OUString sRowSet(RTL_CONSTASCII_USTRINGPARAM("RowSet"));
        if ( xNameCont->hasByName(sRowSet) )
        {
            uno::Reference<beans::XPropertySet> xProp(m_xFormComponentHandler,uno::UNO_QUERY);
            xProp->setPropertyValue(sRowSet,xNameCont->getByName(sRowSet));
        }
    }
    catch(uno::Exception)
    {
        throw lang::NullPointerException();
    }
    if ( m_xFormComponent.is() )
    {
        m_xFormComponentHandler->inspect(m_xFormComponent);
    }
}

uno::Any SAL_CALL ReportComponentHandler::getPropertyValue(const ::rtl::OUString & PropertyName) throw (uno::RuntimeException, beans::UnknownPropertyException)
{
    return m_xFormComponentHandler->getPropertyValue(PropertyName);
}

void SAL_CALL ReportComponentHandler::setPropertyValue(const ::rtl::OUString & PropertyName, const uno::Any & Value) throw (uno::RuntimeException, beans::UnknownPropertyException)
{
    m_xFormComponentHandler->setPropertyValue(PropertyName, Value);
}

beans::PropertyState SAL_CALL ReportComponentHandler::getPropertyState(const ::rtl::OUString & PropertyName) throw (uno::RuntimeException, beans::UnknownPropertyException)
{
    return m_xFormComponentHandler->getPropertyState(PropertyName);
}

inspection::LineDescriptor SAL_CALL ReportComponentHandler::describePropertyLine(const ::rtl::OUString & PropertyName,  const uno::Reference< inspection::XPropertyControlFactory > & ControlFactory) throw (beans::UnknownPropertyException, lang::NullPointerException,uno::RuntimeException)
{
    return m_xFormComponentHandler->describePropertyLine(PropertyName, ControlFactory);
}

uno::Any SAL_CALL ReportComponentHandler::convertToPropertyValue(const ::rtl::OUString & PropertyName, const uno::Any & ControlValue) throw (uno::RuntimeException, beans::UnknownPropertyException)
{
    return m_xFormComponentHandler->convertToPropertyValue(PropertyName, ControlValue);
}

uno::Any SAL_CALL ReportComponentHandler::convertToControlValue(const ::rtl::OUString & PropertyName, const uno::Any & PropertyValue, const uno::Type & ControlValueType) throw (uno::RuntimeException, beans::UnknownPropertyException)
{
    return m_xFormComponentHandler->convertToControlValue(PropertyName, PropertyValue, ControlValueType);
}

void SAL_CALL ReportComponentHandler::addPropertyChangeListener(const uno::Reference< beans::XPropertyChangeListener > & Listener) throw (uno::RuntimeException, lang::NullPointerException)
{
    m_xFormComponentHandler->addPropertyChangeListener(Listener);
}

void SAL_CALL ReportComponentHandler::removePropertyChangeListener(const uno::Reference< beans::XPropertyChangeListener > & _rxListener) throw (uno::RuntimeException)
{
    m_xFormComponentHandler->removePropertyChangeListener(_rxListener);
}

uno::Sequence< beans::Property > SAL_CALL ReportComponentHandler::getSupportedProperties() throw (uno::RuntimeException)
{
    ::std::vector< beans::Property > aNewProps;
    m_pInfoService->getExcludeProperties( aNewProps, m_xFormComponentHandler );

    return aNewProps.empty() ? uno::Sequence< beans::Property > () : uno::Sequence< beans::Property > (&(*aNewProps.begin()),aNewProps.size());
}

uno::Sequence< ::rtl::OUString > SAL_CALL ReportComponentHandler::getSupersededProperties() throw (uno::RuntimeException)
{
    uno::Sequence< ::rtl::OUString > aRet;
    return aRet;
}

uno::Sequence< ::rtl::OUString > SAL_CALL ReportComponentHandler::getActuatingProperties() throw (uno::RuntimeException)
{
    return m_xFormComponentHandler->getActuatingProperties();
}

::sal_Bool SAL_CALL ReportComponentHandler::isComposable( const ::rtl::OUString& _rPropertyName ) throw (uno::RuntimeException, beans::UnknownPropertyException)
{
    return m_pInfoService->isComposable( _rPropertyName, m_xFormComponentHandler );
}

inspection::InteractiveSelectionResult SAL_CALL ReportComponentHandler::onInteractivePropertySelection(const ::rtl::OUString & PropertyName, ::sal_Bool Primary, uno::Any & out_Data, const uno::Reference< inspection::XObjectInspectorUI > & InspectorUI) throw (uno::RuntimeException, beans::UnknownPropertyException, lang::NullPointerException)
{
    return m_xFormComponentHandler->onInteractivePropertySelection(PropertyName, Primary, out_Data, InspectorUI);
}

void SAL_CALL ReportComponentHandler::actuatingPropertyChanged(const ::rtl::OUString & ActuatingPropertyName, const uno::Any & NewValue, const uno::Any & OldValue, const uno::Reference< inspection::XObjectInspectorUI > & InspectorUI, ::sal_Bool FirstTimeInit) throw (uno::RuntimeException, lang::NullPointerException)
{
    m_xFormComponentHandler->actuatingPropertyChanged(ActuatingPropertyName, NewValue, OldValue, InspectorUI, FirstTimeInit);
}

::sal_Bool SAL_CALL ReportComponentHandler::suspend(::sal_Bool Suspend) throw (uno::RuntimeException)
{
    return m_xFormComponentHandler->suspend(Suspend);
}

//........................................................................
} // namespace rptui
//........................................................................

<|endoftext|>


<commit_before>#ifndef SOLAIRE_CONTAINER_HPP
#define SOLAIRE_CONTAINER_HPP

//Copyright 2015 Adam Smith
//
//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.

// Contact :
// Email             : solairelibrary@mail.com
// GitHub repository : https://github.com/SolaireLibrary/SolaireCPP

/*!
	\file Container.hpp
	\brief
	\author
	Created			: Adam Smith
	Last modified	: Adam Smith
	\date
	Created			: 3rd December 2015
	Last Modified	: 10th January 2016
*/

#include <cstring>
#include "Solaire/Core/Iterator.hpp"
#include "Solaire/Core/Allocator.hpp"

namespace Solaire {

	template<class T>
	SOLAIRE_EXPORT_INTERFACE StaticContainer {
    public:
        template<class T2>
        friend class StaticContainer;

        typedef T Type;
        typedef T* Pointer;
        typedef T& Reference;
    protected:
        virtual Pointer SOLAIRE_EXPORT_CALL getPtr(int32_t) throw() = 0;
        virtual SharedAllocation<Iterator<T>> SOLAIRE_EXPORT_CALL begin_() throw() = 0;
        virtual SharedAllocation<Iterator<T>> SOLAIRE_EXPORT_CALL end_() throw() = 0;
        virtual SharedAllocation<Iterator<T>> SOLAIRE_EXPORT_CALL rbegin_() throw() = 0;
        virtual SharedAllocation<Iterator<T>> SOLAIRE_EXPORT_CALL rend_() throw() = 0;

        SOLAIRE_FORCE_INLINE const Type* getPtr(const int32_t aIndex) const throw() {
            return const_cast<StaticContainer<T>*>(this)->getPtr(aIndex);
        }
    public:
        virtual SOLAIRE_EXPORT_CALL ~StaticContainer() throw() {}

        virtual bool SOLAIRE_EXPORT_CALL isContiguous() const throw() = 0;
        virtual int32_t SOLAIRE_EXPORT_CALL size() const throw() = 0;
        virtual Allocator& SOLAIRE_EXPORT_CALL getAllocator() const throw() = 0;

        SOLAIRE_FORCE_INLINE Reference operator[](const int32_t aIndex) throw() {
            return *getPtr(aIndex);
        }

        SOLAIRE_FORCE_INLINE const Reference operator[](const int32_t aIndex) const throw() {
            return *const_cast<StaticContainer<T>*>(this)->getPtr(aIndex);
        }

        SOLAIRE_FORCE_INLINE STLIterator<T> begin() throw() {
            return STLIterator<T>(begin_());
        }

        SOLAIRE_FORCE_INLINE STLIterator<T> end() throw() {
            return STLIterator<T>(end_());
        }

        SOLAIRE_FORCE_INLINE STLIterator<const T> begin() const throw() {
            return STLIterator<T>(const_cast<StaticContainer<T>*>(this)->begin_());
        }

        SOLAIRE_FORCE_INLINE STLIterator<const T> end() const throw() {
            return STLIterator<T>(const_cast<StaticContainer<T>*>(this)->end_());
        }

        SOLAIRE_FORCE_INLINE STLIterator<T> rbegin() throw() {
            return STLIterator<T>(rbegin_());
        }

        SOLAIRE_FORCE_INLINE STLIterator<T> rend() throw() {
            return STLIterator<T>(rend_());
        }

        SOLAIRE_FORCE_INLINE STLIterator<const T> rbegin() const throw() {
            return STLIterator<T>(const_cast<StaticContainer<T>*>(this)->rbegin_());
        }

        SOLAIRE_FORCE_INLINE STLIterator<const T> rend() const throw() {
            return STLIterator<T>(const_cast<StaticContainer<T>*>(this)->rend_());
        }

        SOLAIRE_FORCE_INLINE operator StaticContainer<const T>&() throw() {
            return *reinterpret_cast<StaticContainer<const T>*>(this);
        }

        SOLAIRE_FORCE_INLINE operator const StaticContainer<const T>&() const throw() {
            return *reinterpret_cast<const StaticContainer<const T>*>(this);
        }

        inline bool operator==(const StaticContainer<const T>& aOther) const throw() {
            const int32_t length = size();
            if(length != aOther.size()) return false;
            if(std::is_fundamental<T>::value && isContiguous() && aOther.isContiguous()) {
                return std::memcmp(getPtr(0), aOther.getPtr(0), sizeof(T) * length) == 0;
            }else {
                for(int32_t i = 0; i < length; ++i) {
                    if(getPtr(i) != aOther.getPtr(i)) return false;
                }
                return true;
            }
        }

        inline bool operator!=(const StaticContainer<const T>& aOther) const throw() {
            const int32_t length = size();
            if(length != aOther.size()) return true;
            if(std::is_fundamental<T>::value && isContiguous() && aOther.isContiguous()) {
                return std::memcmp(getPtr(0), aOther.getPtr(0), sizeof(T) * length) != 0;
            }else {
                for(int32_t i = 0; i < length; ++i) {
                    if(getPtr(i) != aOther.getPtr(i)) return true;
                }
                return false;
            }
        }

        SOLAIRE_FORCE_INLINE int32_t findFirstOf(const T& aValue) const throw() {
            return findNextOf(0, aValue);
        }

        inline int32_t findNextOf(const int32_t aIndex, const T& aValue) const throw() {
            const int32_t length = size();
            if(isContiguous()) {
                const T* const ptr = const_cast<StaticContainer<T>*>(this)->getPtr(0);
                for(int32_t i = aIndex; i < length; ++i) {
                    if(ptr[i] == aValue) return i;
                }
            }else {
                for(int32_t i = aIndex; i < length; ++i) {
                    if(*const_cast<StaticContainer<T>*>(this)->getPtr(i) == aValue) return i;
                }
            }

            return length;
        }

        inline int32_t findLastOf(const T& aValue) const throw() {
            const int32_t end = size();
            int32_t i = findFirstOf(aValue);
            int32_t j = i;

            while(i != end) {
                j = i;
                i = findNextOf(i + 1, aValue);
            }

            return j;
        }

        template<class F>
        SOLAIRE_FORCE_INLINE int32_t findFirstIf(const F aCondition) const throw() {
            return findNextIf(0, aCondition);
        }

        template<class F>
        inline int32_t findNextIf(const int32_t aIndex, const F aCondition) const throw() {
            const int32_t length = size();
            if(isContiguous()) {
                const T* const ptr = const_cast<StaticContainer<T>*>(this)->getPtr(0);
                for(int32_t i = aIndex; i < length; ++i) {
                    if(aCondition(ptr[i])) return i;
                }
            }else {
                for(int32_t i = aIndex; i < length; ++i) {
                    if(aCondition(*const_cast<StaticContainer<T>*>(this)->getPtr(i))) return i;
                }
            }

            return length;
        }

        template<class F>
        inline int32_t findLastIf(const F aCondition) const throw() {
            const int32_t end = size();
            int32_t i = findFirstIf(aCondition);
            int32_t j = i;

            while(i != end) {
                j = i;
                i = findNextIf(i + 1, aCondition);
            }

            return j;
        }
	};

	template<class T>
	SOLAIRE_EXPORT_INTERFACE Stack : public StaticContainer<T> {
	public:
		virtual  SOLAIRE_EXPORT_CALL ~Stack() throw() {}
		virtual T& SOLAIRE_EXPORT_CALL pushBack(const T&) throw() = 0;
		virtual T SOLAIRE_EXPORT_CALL popBack() throw() = 0;
		virtual void SOLAIRE_EXPORT_CALL clear() throw() = 0;

		SOLAIRE_FORCE_INLINE T& SOLAIRE_DEFAULT_CALL back() throw() {
			return StaticContainer<T>::operator[](StaticContainer<T>::size() - 1);
		}

		SOLAIRE_FORCE_INLINE const T& SOLAIRE_DEFAULT_CALL back() const throw() {
			return StaticContainer<T>::operator[](StaticContainer<T>::size() - 1);
		}

        SOLAIRE_FORCE_INLINE operator Stack<const T>&() throw() {
            return *reinterpret_cast<Stack<const T>*>(this);
        }

        SOLAIRE_FORCE_INLINE operator const Stack<const T>&() const throw() {
            return *reinterpret_cast<Stack<const T>*>(this);
        }
	};

	template<class T>
	SOLAIRE_EXPORT_INTERFACE Deque : public Stack<T> {
	public:
		virtual SOLAIRE_EXPORT_CALL ~Deque() throw() {}

		virtual T& SOLAIRE_EXPORT_CALL pushFront(const T&) throw() = 0;
		virtual T SOLAIRE_EXPORT_CALL popFront() throw() = 0;

		SOLAIRE_FORCE_INLINE T& SOLAIRE_DEFAULT_CALL front() throw() {
			return StaticContainer<T>::operator[](0);
		}

		SOLAIRE_FORCE_INLINE const T& SOLAIRE_DEFAULT_CALL front() const throw() {
			return StaticContainer<T>::operator[](0);
		}

        SOLAIRE_FORCE_INLINE operator Deque<const T>&() throw() {
            return *reinterpret_cast<Deque<const T>*>(this);
        }

        SOLAIRE_FORCE_INLINE operator const Deque<const T>&() const throw() {
            return *reinterpret_cast<Deque<const T>*>(this);
        }
	};

	template<class T>
	SOLAIRE_EXPORT_INTERFACE List : public Deque<T> {
	public:
		virtual SOLAIRE_EXPORT_CALL ~List() throw() {}

		virtual T& SOLAIRE_EXPORT_CALL insertBefore(const int32_t, const T&) throw() = 0;
		virtual T& SOLAIRE_EXPORT_CALL insertAfter(const int32_t, const T&) throw() = 0;
		virtual bool SOLAIRE_EXPORT_CALL erase(const int32_t) throw() = 0;

        SOLAIRE_FORCE_INLINE operator List<const T>&() throw() {
            return *reinterpret_cast<List<const T>*>(this);
        }

        SOLAIRE_FORCE_INLINE operator const List<const T>&() const throw() {
            return *reinterpret_cast<List<const T>*>(this);
        }
	};

	template<class K, class T>
	SOLAIRE_EXPORT_INTERFACE Map {
    public:
        typedef K KeyType;
        typedef K* KeyPointer;
        typedef K& KeyReference;
        typedef std::pair<K,T> Entry;
	public:
		virtual  SOLAIRE_EXPORT_CALL ~Map() throw() {}

		virtual T& SOLAIRE_EXPORT_CALL emplace(const K&, const T&) throw() = 0;
		virtual const T& SOLAIRE_EXPORT_CALL get(const K&) const throw() = 0;
		virtual T& SOLAIRE_EXPORT_CALL get(const K&) throw() = 0;
		virtual bool SOLAIRE_EXPORT_CALL contains(const K&) const throw() = 0;
		virtual bool SOLAIRE_EXPORT_CALL erase(const K&) throw() = 0;

		virtual void SOLAIRE_EXPORT_CALL clear() throw() = 0;
        virtual int32_t SOLAIRE_EXPORT_CALL size() const throw() = 0;
        virtual Allocator& SOLAIRE_EXPORT_CALL getAllocator() const throw() = 0;
        virtual SharedAllocation<StaticContainer<Entry>> getEntries() const throw() = 0;
	};

}

#endif
<commit_msg>Const Iterator fix<commit_after>#ifndef SOLAIRE_CONTAINER_HPP
#define SOLAIRE_CONTAINER_HPP

//Copyright 2015 Adam Smith
//
//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.

// Contact :
// Email             : solairelibrary@mail.com
// GitHub repository : https://github.com/SolaireLibrary/SolaireCPP

/*!
	\file Container.hpp
	\brief
	\author
	Created			: Adam Smith
	Last modified	: Adam Smith
	\date
	Created			: 3rd December 2015
	Last Modified	: 10th January 2016
*/

#include <cstring>
#include "Solaire/Core/Iterator.hpp"
#include "Solaire/Core/Allocator.hpp"

namespace Solaire {

	template<class T>
	SOLAIRE_EXPORT_INTERFACE StaticContainer {
    public:
        template<class T2>
        friend class StaticContainer;

        typedef T Type;
        typedef T* Pointer;
        typedef T& Reference;
    protected:
        virtual Pointer SOLAIRE_EXPORT_CALL getPtr(int32_t) throw() = 0;
        virtual SharedAllocation<Iterator<T>> SOLAIRE_EXPORT_CALL begin_() throw() = 0;
        virtual SharedAllocation<Iterator<T>> SOLAIRE_EXPORT_CALL end_() throw() = 0;
        virtual SharedAllocation<Iterator<T>> SOLAIRE_EXPORT_CALL rbegin_() throw() = 0;
        virtual SharedAllocation<Iterator<T>> SOLAIRE_EXPORT_CALL rend_() throw() = 0;

        SOLAIRE_FORCE_INLINE const Type* getPtr(const int32_t aIndex) const throw() {
            return const_cast<StaticContainer<T>*>(this)->getPtr(aIndex);
        }
    public:
        virtual SOLAIRE_EXPORT_CALL ~StaticContainer() throw() {}

        virtual bool SOLAIRE_EXPORT_CALL isContiguous() const throw() = 0;
        virtual int32_t SOLAIRE_EXPORT_CALL size() const throw() = 0;
        virtual Allocator& SOLAIRE_EXPORT_CALL getAllocator() const throw() = 0;

        SOLAIRE_FORCE_INLINE Reference operator[](const int32_t aIndex) throw() {
            return *getPtr(aIndex);
        }

        SOLAIRE_FORCE_INLINE const Reference operator[](const int32_t aIndex) const throw() {
            return *const_cast<StaticContainer<T>*>(this)->getPtr(aIndex);
        }

        SOLAIRE_FORCE_INLINE STLIterator<T> begin() throw() {
            return STLIterator<T>(begin_());
        }

        SOLAIRE_FORCE_INLINE STLIterator<T> end() throw() {
            return STLIterator<T>(end_());
        }

        SOLAIRE_FORCE_INLINE STLIterator<const T> begin() const throw() {
            StaticContainer<T>* const p1 = const_cast<StaticContainer<T>*>(this);
            StaticContainer<const T>* const p2 = reinterpret_cast<StaticContainer<const T>*>(p1);
            return STLIterator<const T>(p2->begin_());
        }

        SOLAIRE_FORCE_INLINE STLIterator<const T> end() const throw() {
            StaticContainer<T>* const p1 = const_cast<StaticContainer<T>*>(this);
            StaticContainer<const T>* const p2 = reinterpret_cast<StaticContainer<const T>*>(p1);
            return STLIterator<const T>(p2->end_());
        }

        SOLAIRE_FORCE_INLINE STLIterator<T> rbegin() throw() {
            return STLIterator<T>(rbegin_());
        }

        SOLAIRE_FORCE_INLINE STLIterator<T> rend() throw() {
            return STLIterator<T>(rend_());
        }

        SOLAIRE_FORCE_INLINE STLIterator<const T> rbegin() const throw() {
            return STLIterator<T>(const_cast<StaticContainer<T>*>(this)->rbegin_());
        }

        SOLAIRE_FORCE_INLINE STLIterator<const T> rend() const throw() {
            return STLIterator<T>(const_cast<StaticContainer<T>*>(this)->rend_());
        }

        SOLAIRE_FORCE_INLINE operator StaticContainer<const T>&() throw() {
            return *reinterpret_cast<StaticContainer<const T>*>(this);
        }

        SOLAIRE_FORCE_INLINE operator const StaticContainer<const T>&() const throw() {
            return *reinterpret_cast<const StaticContainer<const T>*>(this);
        }

        inline bool operator==(const StaticContainer<const T>& aOther) const throw() {
            const int32_t length = size();
            if(length != aOther.size()) return false;
            if(std::is_fundamental<T>::value && isContiguous() && aOther.isContiguous()) {
                return std::memcmp(getPtr(0), aOther.getPtr(0), sizeof(T) * length) == 0;
            }else {
                for(int32_t i = 0; i < length; ++i) {
                    if(getPtr(i) != aOther.getPtr(i)) return false;
                }
                return true;
            }
        }

        inline bool operator!=(const StaticContainer<const T>& aOther) const throw() {
            const int32_t length = size();
            if(length != aOther.size()) return true;
            if(std::is_fundamental<T>::value && isContiguous() && aOther.isContiguous()) {
                return std::memcmp(getPtr(0), aOther.getPtr(0), sizeof(T) * length) != 0;
            }else {
                for(int32_t i = 0; i < length; ++i) {
                    if(getPtr(i) != aOther.getPtr(i)) return true;
                }
                return false;
            }
        }

        SOLAIRE_FORCE_INLINE int32_t findFirstOf(const T& aValue) const throw() {
            return findNextOf(0, aValue);
        }

        inline int32_t findNextOf(const int32_t aIndex, const T& aValue) const throw() {
            const int32_t length = size();
            if(isContiguous()) {
                const T* const ptr = const_cast<StaticContainer<T>*>(this)->getPtr(0);
                for(int32_t i = aIndex; i < length; ++i) {
                    if(ptr[i] == aValue) return i;
                }
            }else {
                for(int32_t i = aIndex; i < length; ++i) {
                    if(*const_cast<StaticContainer<T>*>(this)->getPtr(i) == aValue) return i;
                }
            }

            return length;
        }

        inline int32_t findLastOf(const T& aValue) const throw() {
            const int32_t end = size();
            int32_t i = findFirstOf(aValue);
            int32_t j = i;

            while(i != end) {
                j = i;
                i = findNextOf(i + 1, aValue);
            }

            return j;
        }

        template<class F>
        SOLAIRE_FORCE_INLINE int32_t findFirstIf(const F aCondition) const throw() {
            return findNextIf(0, aCondition);
        }

        template<class F>
        inline int32_t findNextIf(const int32_t aIndex, const F aCondition) const throw() {
            const int32_t length = size();
            if(isContiguous()) {
                const T* const ptr = const_cast<StaticContainer<T>*>(this)->getPtr(0);
                for(int32_t i = aIndex; i < length; ++i) {
                    if(aCondition(ptr[i])) return i;
                }
            }else {
                for(int32_t i = aIndex; i < length; ++i) {
                    if(aCondition(*const_cast<StaticContainer<T>*>(this)->getPtr(i))) return i;
                }
            }

            return length;
        }

        template<class F>
        inline int32_t findLastIf(const F aCondition) const throw() {
            const int32_t end = size();
            int32_t i = findFirstIf(aCondition);
            int32_t j = i;

            while(i != end) {
                j = i;
                i = findNextIf(i + 1, aCondition);
            }

            return j;
        }
	};

	template<class T>
	SOLAIRE_EXPORT_INTERFACE Stack : public StaticContainer<T> {
	public:
		virtual  SOLAIRE_EXPORT_CALL ~Stack() throw() {}
		virtual T& SOLAIRE_EXPORT_CALL pushBack(const T&) throw() = 0;
		virtual T SOLAIRE_EXPORT_CALL popBack() throw() = 0;
		virtual void SOLAIRE_EXPORT_CALL clear() throw() = 0;

		SOLAIRE_FORCE_INLINE T& SOLAIRE_DEFAULT_CALL back() throw() {
			return StaticContainer<T>::operator[](StaticContainer<T>::size() - 1);
		}

		SOLAIRE_FORCE_INLINE const T& SOLAIRE_DEFAULT_CALL back() const throw() {
			return StaticContainer<T>::operator[](StaticContainer<T>::size() - 1);
		}

        SOLAIRE_FORCE_INLINE operator Stack<const T>&() throw() {
            return *reinterpret_cast<Stack<const T>*>(this);
        }

        SOLAIRE_FORCE_INLINE operator const Stack<const T>&() const throw() {
            return *reinterpret_cast<Stack<const T>*>(this);
        }
	};

	template<class T>
	SOLAIRE_EXPORT_INTERFACE Deque : public Stack<T> {
	public:
		virtual SOLAIRE_EXPORT_CALL ~Deque() throw() {}

		virtual T& SOLAIRE_EXPORT_CALL pushFront(const T&) throw() = 0;
		virtual T SOLAIRE_EXPORT_CALL popFront() throw() = 0;

		SOLAIRE_FORCE_INLINE T& SOLAIRE_DEFAULT_CALL front() throw() {
			return StaticContainer<T>::operator[](0);
		}

		SOLAIRE_FORCE_INLINE const T& SOLAIRE_DEFAULT_CALL front() const throw() {
			return StaticContainer<T>::operator[](0);
		}

        SOLAIRE_FORCE_INLINE operator Deque<const T>&() throw() {
            return *reinterpret_cast<Deque<const T>*>(this);
        }

        SOLAIRE_FORCE_INLINE operator const Deque<const T>&() const throw() {
            return *reinterpret_cast<Deque<const T>*>(this);
        }
	};

	template<class T>
	SOLAIRE_EXPORT_INTERFACE List : public Deque<T> {
	public:
		virtual SOLAIRE_EXPORT_CALL ~List() throw() {}

		virtual T& SOLAIRE_EXPORT_CALL insertBefore(const int32_t, const T&) throw() = 0;
		virtual T& SOLAIRE_EXPORT_CALL insertAfter(const int32_t, const T&) throw() = 0;
		virtual bool SOLAIRE_EXPORT_CALL erase(const int32_t) throw() = 0;

        SOLAIRE_FORCE_INLINE operator List<const T>&() throw() {
            return *reinterpret_cast<List<const T>*>(this);
        }

        SOLAIRE_FORCE_INLINE operator const List<const T>&() const throw() {
            return *reinterpret_cast<List<const T>*>(this);
        }
	};

	template<class K, class T>
	SOLAIRE_EXPORT_INTERFACE Map {
    public:
        typedef K KeyType;
        typedef K* KeyPointer;
        typedef K& KeyReference;
        typedef std::pair<K,T> Entry;
	public:
		virtual  SOLAIRE_EXPORT_CALL ~Map() throw() {}

		virtual T& SOLAIRE_EXPORT_CALL emplace(const K&, const T&) throw() = 0;
		virtual const T& SOLAIRE_EXPORT_CALL get(const K&) const throw() = 0;
		virtual T& SOLAIRE_EXPORT_CALL get(const K&) throw() = 0;
		virtual bool SOLAIRE_EXPORT_CALL contains(const K&) const throw() = 0;
		virtual bool SOLAIRE_EXPORT_CALL erase(const K&) throw() = 0;

		virtual void SOLAIRE_EXPORT_CALL clear() throw() = 0;
        virtual int32_t SOLAIRE_EXPORT_CALL size() const throw() = 0;
        virtual Allocator& SOLAIRE_EXPORT_CALL getAllocator() const throw() = 0;
        virtual SharedAllocation<StaticContainer<Entry>> getEntries() const throw() = 0;
	};

}

#endif
<|endoftext|>


<commit_before>#ifndef SOLAIRE_ENCODER_HPP
#define SOLAIRE_ENCODER_HPP

//Copyright 2015 Adam Smith
//
//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.

// Contact :
// Email             : solairelibrary@mail.com
// GitHub repository : https://github.com/SolaireLibrary/SolaireCPP

/*!
	\file Encoder.hpp
	\brief
	\author
	Created			: Adam Smith
	Last modified	: Adam Smith
	\version 1.0
	\date
	Created			: 16th January 2016
	Last Modified	: 16th January 2016
*/

#include "Solaire/Data/ArrayList.hpp"
#include "Solaire/Encode/GenericValue.hpp"

namespace Solaire {

	template<class T, typename ENABLE = void>
	struct Encoder {
	    typedef T DecodeType;

	    static DecodeType decode(Allocator&, const GenericValue&) throw();
	    static GenericValue encode(Allocator&, const T&) throw();
	};

	template<class T>
	static typename Encoder<T>::DecodeType decode(Allocator& aAllocator, const GenericValue& aValue) {
	    return Encoder<T>::decode(aAllocator, aValue);
	}

	template<class T>
	static GenericValue decode(Allocator& aAllocator, const T& aValue) {
	    return Encoder<T>::encode(aAllocator, aValue);
	}

	////

    template<>
	struct Encoder<char>{
	    typedef char DecodeType;

	    static DecodeType decode(Allocator& aAllocator, const GenericValue& aValue) throw() {
            return aValue.getChar();
	    }

	    static GenericValue encode(Allocator& aAllocator, const char aValue) throw() {
            return GenericValue(aValue);
	    }
	};

    template<>
	struct Encoder<bool>{
	    typedef bool DecodeType;

	    static DecodeType decode(Allocator& aAllocator, const GenericValue& aValue) throw() {
            return aValue.getBool();
	    }

	    static GenericValue encode(Allocator& aAllocator, const bool aValue) throw() {
            return GenericValue(aValue);
	    }
	};

    template<class T>
	struct Encoder<T, typename std::enable_if<
        std::is_same<T, uint8_t>::value ||
        std::is_same<T, uint16_t>::value ||
        std::is_same<T, uint32_t>::value ||
        std::is_same<T, uint64_t>::value
    >::type>{
	    typedef T DecodeType;

	    static DecodeType decode(Allocator& aAllocator, const GenericValue& aValue) throw() {
            return static_cast<T>(aValue.getUnsigned());
	    }

	    static GenericValue encode(Allocator& aAllocator, const T aValue) throw() {
            return GenericValue(static_cast<uint64_t>(aValue));
	    }
	};

    template<class T>
	struct Encoder<T, typename std::enable_if<
        std::is_same<T, int8_t>::value ||
        std::is_same<T, int16_t>::value ||
        std::is_same<T, int32_t>::value ||
        std::is_same<T, int64_t>::value
    >::type>{
	    typedef T DecodeType;

	    static DecodeType decode(Allocator& aAllocator, const GenericValue& aValue) throw() {
            return static_cast<T>(aValue.getSigned());
	    }

	    static GenericValue encode(Allocator& aAllocator, const T aValue) throw() {
            return GenericValue(static_cast<int64_t>(aValue));
	    }
	};

    template<class T>
	struct Encoder<T, typename std::enable_if<
        std::is_same<T, float>::value ||
        std::is_same<T, double>::value
    >::type>{
	    typedef T DecodeType;

	    static DecodeType decode(Allocator& aAllocator, const GenericValue& aValue) throw() {
            return static_cast<T>(aValue.getDouble());
	    }

	    static GenericValue encode(Allocator& aAllocator, const T aValue) throw() {
            return GenericValue(static_cast<double>(aValue));
	    }
	};

	////

	template<class T>
	struct Encoder<StaticContainer<T>>{
	    typedef ArrayList<T> DecodeType;

	    static DecodeType decode(Allocator& aAllocator, const GenericValue& aValue) throw() {
            ArrayList<T> container(aAllocator);
            if(aValue.isArray()){
                const GenericArray& array_ = aValue.getArray();
                const int32_t size = array_.size();
                for(int32_t i = 0; i < size; ++i) {
                    container.pushBack(Encoder<T>::decode(aAllocator, array_[i]));
                }
            }
            return container;
	    }

	    static GenericValue encode(Allocator& aAllocator, const StaticContainer<const T>& aContainer) throw() {
            GenericValue value;
            const GenericArray& array_ = value.setArray();
            const int32_t size = aContainer.size();
            for(int32_t i = 0; i < size; ++i) {
                array_.pushBack(Encoder<T>::encode(aAllocator, aContainer[i]));
            }
            return value;
	    }
	};
}

#endif
<commit_msg>String Encoder<commit_after>#ifndef SOLAIRE_ENCODER_HPP
#define SOLAIRE_ENCODER_HPP

//Copyright 2015 Adam Smith
//
//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.

// Contact :
// Email             : solairelibrary@mail.com
// GitHub repository : https://github.com/SolaireLibrary/SolaireCPP

/*!
	\file Encoder.hpp
	\brief
	\author
	Created			: Adam Smith
	Last modified	: Adam Smith
	\version 1.0
	\date
	Created			: 16th January 2016
	Last Modified	: 16th January 2016
*/

#include "Solaire/Data/ArrayList.hpp"
#include "Solaire/Encode/GenericValue.hpp"

namespace Solaire {

	template<class T, typename ENABLE = void>
	struct Encoder {
	    typedef T DecodeType;

	    static DecodeType decode(Allocator&, const GenericValue&) throw();
	    static GenericValue encode(Allocator&, const T&) throw();
	};

	template<class T>
	static typename Encoder<T>::DecodeType decode(Allocator& aAllocator, const GenericValue& aValue) {
	    return Encoder<T>::decode(aAllocator, aValue);
	}

	template<class T>
	static GenericValue decode(Allocator& aAllocator, const T& aValue) {
	    return Encoder<T>::encode(aAllocator, aValue);
	}

	////

    template<>
	struct Encoder<char>{
	    typedef char DecodeType;

	    static DecodeType decode(Allocator& aAllocator, const GenericValue& aValue) throw() {
            return aValue.getChar();
	    }

	    static GenericValue encode(Allocator& aAllocator, const char aValue) throw() {
            return GenericValue(aValue);
	    }
	};

    template<>
	struct Encoder<bool>{
	    typedef bool DecodeType;

	    static DecodeType decode(Allocator& aAllocator, const GenericValue& aValue) throw() {
            return aValue.getBool();
	    }

	    static GenericValue encode(Allocator& aAllocator, const bool aValue) throw() {
            return GenericValue(aValue);
	    }
	};

    template<class T>
	struct Encoder<T, typename std::enable_if<
        std::is_same<T, uint8_t>::value ||
        std::is_same<T, uint16_t>::value ||
        std::is_same<T, uint32_t>::value ||
        std::is_same<T, uint64_t>::value
    >::type>{
	    typedef T DecodeType;

	    static DecodeType decode(Allocator& aAllocator, const GenericValue& aValue) throw() {
            return static_cast<T>(aValue.getUnsigned());
	    }

	    static GenericValue encode(Allocator& aAllocator, const T aValue) throw() {
            return GenericValue(static_cast<uint64_t>(aValue));
	    }
	};

    template<class T>
	struct Encoder<T, typename std::enable_if<
        std::is_same<T, int8_t>::value ||
        std::is_same<T, int16_t>::value ||
        std::is_same<T, int32_t>::value ||
        std::is_same<T, int64_t>::value
    >::type>{
	    typedef T DecodeType;

	    static DecodeType decode(Allocator& aAllocator, const GenericValue& aValue) throw() {
            return static_cast<T>(aValue.getSigned());
	    }

	    static GenericValue encode(Allocator& aAllocator, const T aValue) throw() {
            return GenericValue(static_cast<int64_t>(aValue));
	    }
	};

    template<class T>
	struct Encoder<T, typename std::enable_if<
        std::is_same<T, float>::value ||
        std::is_same<T, double>::value
    >::type>{
	    typedef T DecodeType;

	    static DecodeType decode(Allocator& aAllocator, const GenericValue& aValue) throw() {
            return static_cast<T>(aValue.getDouble());
	    }

	    static GenericValue encode(Allocator& aAllocator, const T aValue) throw() {
            return GenericValue(static_cast<double>(aValue));
	    }
	};

    template<>
	struct Encoder<String<char>>{
	    typedef CString DecodeType;

	    static DecodeType decode(Allocator& aAllocator, const GenericValue& aValue) throw() {
            return CString(aValue.getString());
	    }

	    static GenericValue encode(Allocator& aAllocator, const StringConstant<char>& aValue) throw() {
            GenericValue value;
            //! \todo Assign string
            //value.setString() = aValue;
            return value;
	    }
	};

	////

	template<class T>
	struct Encoder<StaticContainer<T>>{
	    typedef ArrayList<T> DecodeType;

	    static DecodeType decode(Allocator& aAllocator, const GenericValue& aValue) throw() {
            ArrayList<T> container(aAllocator);
            if(aValue.isArray()){
                const GenericArray& array_ = aValue.getArray();
                const int32_t size = array_.size();
                for(int32_t i = 0; i < size; ++i) {
                    container.pushBack(Encoder<T>::decode(aAllocator, array_[i]));
                }
            }
            return container;
	    }

	    static GenericValue encode(Allocator& aAllocator, const StaticContainer<T>& aContainer) throw() {
            GenericValue value;
            const GenericArray& array_ = value.setArray();
            const int32_t size = aContainer.size();
            for(int32_t i = 0; i < size; ++i) {
                array_.pushBack(Encoder<T>::encode(aAllocator, aContainer[i]));
            }
            return value;
	    }
	};
}

#endif
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * Version: MPL 1.1 / GPLv3+ / LGPLv3+
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License or as specified alternatively below. You may obtain a copy of
 * the License at http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * Major Contributor(s):
 * Copyright (C) 2010 Red Hat, Inc., Caolán McNamara <caolanm@redhat.com>
 *  (initial developer)
 * Copyright (C) 2011 Markus Mohrhard <markus.mohrhard@googlemail.com>
 *
 * All Rights Reserved.
 *
 * For minor contributions see the git repository.
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 3 or later (the "GPLv3+"), or
 * the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"),
 * in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable
 * instead of those above.
 */

#include <sal/config.h>
#include <test/bootstrapfixture.hxx>
#include <unotest/macros_test.hxx>
#include <rtl/strbuf.hxx>
#include <osl/file.hxx>

#include <sfx2/app.hxx>
#include <sfx2/docfilt.hxx>
#include <sfx2/docfile.hxx>
#include <sfx2/sfxmodelfactory.hxx>
#include <svl/intitem.hxx>

#include <basic/sbxdef.hxx>

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

class DBAccessTest : public test::BootstrapFixture, public unotest::MacrosTest
{
public:
    DBAccessTest();

    void createFileURL(const rtl::OUString& aFileBase, const rtl::OUString& aFileExtension, rtl::OUString& rFilePath);

    virtual void setUp();
    virtual void tearDown();

    void test();

    CPPUNIT_TEST_SUITE(DBAccessTest);
    CPPUNIT_TEST(test);
    CPPUNIT_TEST_SUITE_END();

private:
    rtl::OUString m_aBaseString;
};

void DBAccessTest::createFileURL(const rtl::OUString& aFileBase, const rtl::OUString& aFileExtension, rtl::OUString& rFilePath)
{
    rtl::OUString aSep(RTL_CONSTASCII_USTRINGPARAM("/"));
    rtl::OUStringBuffer aBuffer( getSrcRootURL() );
    aBuffer.append(m_aBaseString);
    aBuffer.append(aSep).append(aFileBase).append(aFileExtension);
    rFilePath = aBuffer.makeStringAndClear();
}

DBAccessTest::DBAccessTest()
      : m_aBaseString(RTL_CONSTASCII_USTRINGPARAM("/dbaccess/qa/extras/testdocuments"))
{
}

void DBAccessTest::test()
{
    const rtl::OUString aFileNameBase(RTL_CONSTASCII_USTRINGPARAM("testdb."));
    const rtl::OUString aFileExtension(RTL_CONSTASCII_USTRINGPARAM("odb"));
    rtl::OUString aFileName;
    createFileURL(aFileNameBase, aFileExtension, aFileName);
    uno::Reference< lang::XComponent > xComponent = loadFromDesktop(aFileName);
    CPPUNIT_ASSERT(xComponent.is());
}

void DBAccessTest::setUp()
{
    test::BootstrapFixture::setUp();

    // This is a bit of a fudge, we do this to ensure that ScGlobals::ensure,
    // which is a private symbol to us, gets called
    mxDesktop = Reference<com::sun::star::frame::XDesktop>( getMultiServiceFactory()->createInstance(
                rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.frame.Desktop" ))), UNO_QUERY );
    CPPUNIT_ASSERT(mxDesktop.is());
}

void DBAccessTest::tearDown()
{
    test::BootstrapFixture::tearDown();
}

CPPUNIT_TEST_SUITE_REGISTRATION(DBAccessTest);

CPPUNIT_PLUGIN_IMPLEMENT();

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>disable new test on win and mac since it is a test with UI<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * Version: MPL 1.1 / GPLv3+ / LGPLv3+
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License or as specified alternatively below. You may obtain a copy of
 * the License at http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * Major Contributor(s):
 * Copyright (C) 2010 Red Hat, Inc., Caolán McNamara <caolanm@redhat.com>
 *  (initial developer)
 * Copyright (C) 2011 Markus Mohrhard <markus.mohrhard@googlemail.com>
 *
 * All Rights Reserved.
 *
 * For minor contributions see the git repository.
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 3 or later (the "GPLv3+"), or
 * the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"),
 * in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable
 * instead of those above.
 */

#include <sal/config.h>
#include <test/bootstrapfixture.hxx>
#include <unotest/macros_test.hxx>
#include <rtl/strbuf.hxx>
#include <osl/file.hxx>

#include <sfx2/app.hxx>
#include <sfx2/docfilt.hxx>
#include <sfx2/docfile.hxx>
#include <sfx2/sfxmodelfactory.hxx>
#include <svl/intitem.hxx>

#include <basic/sbxdef.hxx>

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

class DBAccessTest : public test::BootstrapFixture, public unotest::MacrosTest
{
public:
    DBAccessTest();

    void createFileURL(const rtl::OUString& aFileBase, const rtl::OUString& aFileExtension, rtl::OUString& rFilePath);

    virtual void setUp();
    virtual void tearDown();

    void test();

    CPPUNIT_TEST_SUITE(DBAccessTest);
#if !defined(MACOSX) && !defined(WNT)
    CPPUNIT_TEST(test);
#endif
    CPPUNIT_TEST_SUITE_END();

private:
    rtl::OUString m_aBaseString;
};

void DBAccessTest::createFileURL(const rtl::OUString& aFileBase, const rtl::OUString& aFileExtension, rtl::OUString& rFilePath)
{
    rtl::OUString aSep(RTL_CONSTASCII_USTRINGPARAM("/"));
    rtl::OUStringBuffer aBuffer( getSrcRootURL() );
    aBuffer.append(m_aBaseString);
    aBuffer.append(aSep).append(aFileBase).append(aFileExtension);
    rFilePath = aBuffer.makeStringAndClear();
}

DBAccessTest::DBAccessTest()
      : m_aBaseString(RTL_CONSTASCII_USTRINGPARAM("/dbaccess/qa/extras/testdocuments"))
{
}

void DBAccessTest::test()
{
    const rtl::OUString aFileNameBase(RTL_CONSTASCII_USTRINGPARAM("testdb."));
    const rtl::OUString aFileExtension(RTL_CONSTASCII_USTRINGPARAM("odb"));
    rtl::OUString aFileName;
    createFileURL(aFileNameBase, aFileExtension, aFileName);
    uno::Reference< lang::XComponent > xComponent = loadFromDesktop(aFileName);
    CPPUNIT_ASSERT(xComponent.is());
}

void DBAccessTest::setUp()
{
    test::BootstrapFixture::setUp();

    // This is a bit of a fudge, we do this to ensure that ScGlobals::ensure,
    // which is a private symbol to us, gets called
    mxDesktop = Reference<com::sun::star::frame::XDesktop>( getMultiServiceFactory()->createInstance(
                rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.frame.Desktop" ))), UNO_QUERY );
    CPPUNIT_ASSERT(mxDesktop.is());
}

void DBAccessTest::tearDown()
{
    test::BootstrapFixture::tearDown();
}

CPPUNIT_TEST_SUITE_REGISTRATION(DBAccessTest);

CPPUNIT_PLUGIN_IMPLEMENT();

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


<commit_before>/*************************************************************************
 *
 *  $RCSfile: Object.cxx,v $
 *
 *  $Revision: 1.18 $
 *
 *  last change: $Author: hr $ $Date: 2004-11-09 12:12:58 $
 *
 *  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_JAVA_LANG_OBJJECT_HXX_
#include "java/lang/Class.hxx"
#endif
#include "connectivity/CommonTools.hxx"

#ifndef _COM_SUN_STAR_UNO_EXCEPTION_HPP_
#include <com/sun/star/uno/Exception.hpp>
#endif
#ifndef _CONNECTIVITY_JAVA_TOOLS_HXX_
#include "java/tools.hxx"
#endif
#ifndef _CONNECTIVITY_JAVA_SQL_SQLEXCEPTION_HXX_
#include "java/sql/SQLException.hxx"
#endif
#ifndef _VOS_PROCESS_HXX_
#include <vos/process.hxx>
#endif
#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif
#include <osl/thread.h>

#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif

using namespace connectivity;
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;

// -----------------------------------------------------------------------------
::rtl::Reference< jvmaccess::VirtualMachine > getJavaVM2(const ::rtl::Reference< jvmaccess::VirtualMachine >& _rVM = ::rtl::Reference< jvmaccess::VirtualMachine >(),
                                                        sal_Bool _bSet = sal_False)
{
    static ::rtl::Reference< jvmaccess::VirtualMachine > s_VM;
    if ( _rVM.is() || _bSet )
        s_VM = _rVM;
    return s_VM;
}
// -----------------------------------------------------------------------------
::rtl::Reference< jvmaccess::VirtualMachine > java_lang_Object::getVM(const Reference<XMultiServiceFactory >& _rxFactory)
{
    ::rtl::Reference< jvmaccess::VirtualMachine > xVM = getJavaVM2();
    if ( !xVM.is() && _rxFactory.is() )
        xVM = getJavaVM2(::connectivity::getJavaVM(_rxFactory));

    return xVM;
}
// -----------------------------------------------------------------------------
typedef ::std::map<oslThreadIdentifier,TGuard> TGuardMap;
TGuardMap& lcl_getGuardMap()
{
    static TGuardMap s_sMap;
    return s_sMap;
}
// -----------------------------------------------------------------------------
TGuard getVMGuard()
{
    TGuardMap& s_sMap = lcl_getGuardMap();

    oslThreadIdentifier id = osl_getThreadIdentifier(NULL);
    TGuardMap::iterator aFind = s_sMap.find(id);
    if ( aFind == s_sMap.end() )
        aFind = s_sMap.insert(TGuardMap::value_type(id,TGuard(new jvmaccess::VirtualMachine::AttachGuard(java_lang_Object::getVM())))).first;
    return aFind->second;
}
// -----------------------------------------------------------------------------
SDBThreadAttach::SDBThreadAttach()
 : pEnv(NULL)
{
    m_aGuard = getVMGuard();
    if ( m_aGuard.get() )
        pEnv = m_aGuard->getEnvironment();
}
// -----------------------------------------------------------------------------
SDBThreadAttach::~SDBThreadAttach()
{
}
// -----------------------------------------------------------------------------
sal_Int32& getJavaVMRefCount()
{
    static sal_Int32 s_nRefCount = 0;
    return s_nRefCount;
}
// -----------------------------------------------------------------------------
void SDBThreadAttach::addRef()
{
    getJavaVMRefCount()++;
}
// -----------------------------------------------------------------------------
void SDBThreadAttach::releaseRef()
{
    getJavaVMRefCount()--;
    if ( getJavaVMRefCount() == 0 )
    {
        TGuardMap& s_sMap = lcl_getGuardMap();
        s_sMap.clear();
        getJavaVM2(::rtl::Reference< jvmaccess::VirtualMachine >(),sal_True);
    }
}
// -----------------------------------------------------------------------------
// statische Variablen der Klasse:
jclass java_lang_Object::theClass = 0;

jclass java_lang_Object::getMyClass()
{
    if( !theClass )
    {
        SDBThreadAttach t;

        if( !t.pEnv ) return (jclass)NULL;
        jclass tempClass = t.pEnv->FindClass( "java/lang/Object" );
        theClass = (jclass)t.pEnv->NewGlobalRef( tempClass );
        t.pEnv->DeleteLocalRef( tempClass );
    }
    return theClass;
}
// der eigentliche Konstruktor
java_lang_Object::java_lang_Object(const Reference<XMultiServiceFactory >& _rxFactory)
            : object( 0 ),m_xFactory(_rxFactory)
{
}

// der protected-Konstruktor fuer abgeleitete Klassen
java_lang_Object::java_lang_Object( JNIEnv * pXEnv, jobject myObj )
    : object( NULL )
{
    if( pXEnv && myObj )
        object = pXEnv->NewGlobalRef( myObj );
}

java_lang_Object::~java_lang_Object()
{
    if( object )
    {
        SDBThreadAttach t;
        if( t.pEnv )
            t.pEnv->DeleteGlobalRef( object );
    }
}
void java_lang_Object::clearObject(JNIEnv& rEnv)
{
    if( object )
    {
        rEnv.DeleteGlobalRef( object );
        object = NULL;
    }
}

void java_lang_Object::clearObject()
{
    if( object )
    {
        SDBThreadAttach t;
        if( t.pEnv )
            t.pEnv->DeleteGlobalRef( object );
        object = NULL;
    }
}
// der protected-Konstruktor fuer abgeleitete Klassen
void java_lang_Object::saveRef( JNIEnv * pXEnv, jobject myObj )
{
    OSL_ENSURE( myObj, "object in c++ -> Java Wrapper" );
    if( pXEnv && myObj )
        object = pXEnv->NewGlobalRef( myObj );
}

java_lang_Class * java_lang_Object::getClass()
{
    jobject out;
    SDBThreadAttach t;
    if( t.pEnv )
    {
        // temporaere Variable initialisieren
        static char * cSignature = "()Ljava/lang/Class;";
        static char * cMethodName = "getClass";
        // Java-Call absetzen
        static jmethodID mID = NULL;
        if ( !mID  )
            mID  = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
        if( mID )
        {
            out = t.pEnv->CallObjectMethodA( object, mID, NULL );
            ThrowSQLException(t.pEnv,NULL);
            return new java_lang_Class( t.pEnv, out );
        } //mID
    } //pEnv
    return NULL;
}

::rtl::OUString java_lang_Object::toString()
{

    SDBThreadAttach t;
    ::rtl::OUString aStr;
    if( t.pEnv )
    {
        // temporaere Variable initialisieren
        static char * cSignature = "()Ljava/lang/String;";
        static char * cMethodName = "toString";
        // Java-Call absetzen
        static jmethodID mID = NULL;
        if ( !mID  )
            mID  = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
        if( mID )
        {
            jstring out = (jstring)t.pEnv->CallObjectMethod( object, mID);
            ThrowSQLException(t.pEnv,NULL);
            aStr = JavaString2String(t.pEnv,out);
        } //mID
    } //pEnv
    return  aStr;
}
// --------------------------------------------------------------------------------
void java_lang_Object::ThrowSQLException(JNIEnv * pEnv,const Reference< XInterface> & _rContext) throw(SQLException, RuntimeException)
{
    jthrowable jThrow = NULL;
    if(pEnv && (jThrow = pEnv->ExceptionOccurred()))
    {
        pEnv->ExceptionClear();// we have to clear the exception here because we want to handle it itself
        if(pEnv->IsInstanceOf(jThrow,java_sql_SQLException_BASE::getMyClass()))
        {
            java_sql_SQLException_BASE* pException = new java_sql_SQLException_BASE(pEnv,jThrow);
            SQLException e( pException->getMessage(),
                                _rContext,
                                pException->getSQLState(),
                                pException->getErrorCode(),
                                Any()
                            );
            delete pException;
            throw  e;
        }
        else if(pEnv->IsInstanceOf(jThrow,java_lang_Throwable::getMyClass()))
        {
            java_lang_Throwable *pThrow = new java_lang_Throwable(pEnv,jThrow);
            ::rtl::OUString aMsg = pThrow->getMessage();
            if(!aMsg.getLength())
                aMsg = pThrow->getLocalizedMessage();
            if(!aMsg.getLength())
                aMsg = pThrow->toString();
            delete pThrow;
            throw SQLException(aMsg,_rContext,::rtl::OUString(),-1,Any());
        }
        else
            pEnv->DeleteLocalRef( jThrow );
    }
}

<commit_msg>INTEGRATION: CWS dba22 (1.18.16); FILE MERGED 2005/01/14 12:35:22 oj 1.18.16.3: #i39671# attachguard for every call 2005/01/10 06:29:19 oj 1.18.16.2: compile error under linux 2005/01/04 11:45:21 oj 1.18.16.1: #i39671# erase guard when no longer needed<commit_after>/*************************************************************************
 *
 *  $RCSfile: Object.cxx,v $
 *
 *  $Revision: 1.19 $
 *
 *  last change: $Author: kz $ $Date: 2005-01-21 16:42:11 $
 *
 *  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_JAVA_LANG_OBJJECT_HXX_
#include "java/lang/Class.hxx"
#endif
#include "connectivity/CommonTools.hxx"

#ifndef _COM_SUN_STAR_UNO_EXCEPTION_HPP_
#include <com/sun/star/uno/Exception.hpp>
#endif
#ifndef _CONNECTIVITY_JAVA_TOOLS_HXX_
#include "java/tools.hxx"
#endif
#ifndef _CONNECTIVITY_JAVA_SQL_SQLEXCEPTION_HXX_
#include "java/sql/SQLException.hxx"
#endif
#ifndef _VOS_PROCESS_HXX_
#include <vos/process.hxx>
#endif
#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif
#include <osl/thread.h>

#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif

using namespace connectivity;
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;

// -----------------------------------------------------------------------------
::rtl::Reference< jvmaccess::VirtualMachine > getJavaVM2(const ::rtl::Reference< jvmaccess::VirtualMachine >& _rVM = ::rtl::Reference< jvmaccess::VirtualMachine >(),
                                                        sal_Bool _bSet = sal_False)
{
    static ::rtl::Reference< jvmaccess::VirtualMachine > s_VM;
    if ( _rVM.is() || _bSet )
        s_VM = _rVM;
    return s_VM;
}
// -----------------------------------------------------------------------------
::rtl::Reference< jvmaccess::VirtualMachine > java_lang_Object::getVM(const Reference<XMultiServiceFactory >& _rxFactory)
{
    ::rtl::Reference< jvmaccess::VirtualMachine > xVM = getJavaVM2();
    if ( !xVM.is() && _rxFactory.is() )
        xVM = getJavaVM2(::connectivity::getJavaVM(_rxFactory));

    return xVM;
}
// -----------------------------------------------------------------------------
SDBThreadAttach::SDBThreadAttach()
 : m_aGuard(java_lang_Object::getVM())
 , pEnv(NULL)
{
    pEnv = m_aGuard.getEnvironment();
    OSL_ENSURE(pEnv,"Environment is nULL!");
}
// -----------------------------------------------------------------------------
SDBThreadAttach::~SDBThreadAttach()
{
}
// -----------------------------------------------------------------------------
oslInterlockedCount& getJavaVMRefCount()
{
    static oslInterlockedCount s_nRefCount = 0;
    return s_nRefCount;
}
// -----------------------------------------------------------------------------
void SDBThreadAttach::addRef()
{
    osl_incrementInterlockedCount(&getJavaVMRefCount());
}
// -----------------------------------------------------------------------------
void SDBThreadAttach::releaseRef()
{
    osl_decrementInterlockedCount(&getJavaVMRefCount());
    if ( getJavaVMRefCount() == 0 )
    {
        getJavaVM2(::rtl::Reference< jvmaccess::VirtualMachine >(),sal_True);
    }
}
// -----------------------------------------------------------------------------
// statische Variablen der Klasse:
jclass java_lang_Object::theClass = 0;

jclass java_lang_Object::getMyClass()
{
    if( !theClass )
    {
        SDBThreadAttach t;

        if( !t.pEnv ) return (jclass)NULL;
        jclass tempClass = t.pEnv->FindClass( "java/lang/Object" );
        theClass = (jclass)t.pEnv->NewGlobalRef( tempClass );
        t.pEnv->DeleteLocalRef( tempClass );
    }
    return theClass;
}
// der eigentliche Konstruktor
java_lang_Object::java_lang_Object(const Reference<XMultiServiceFactory >& _rxFactory)
            : object( 0 ),m_xFactory(_rxFactory)
{
    SDBThreadAttach::addRef();
}

// der protected-Konstruktor fuer abgeleitete Klassen
java_lang_Object::java_lang_Object( JNIEnv * pXEnv, jobject myObj )
    : object( NULL )
{
    SDBThreadAttach::addRef();
    if( pXEnv && myObj )
        object = pXEnv->NewGlobalRef( myObj );
}

java_lang_Object::~java_lang_Object()
{
    if( object )
    {
        SDBThreadAttach t;
        if( t.pEnv )
            t.pEnv->DeleteGlobalRef( object );
        object = NULL;
    }
    SDBThreadAttach::releaseRef();
}
void java_lang_Object::clearObject(JNIEnv& rEnv)
{
    if( object )
    {
        rEnv.DeleteGlobalRef( object );
        object = NULL;
    }
}

void java_lang_Object::clearObject()
{
    if( object )
    {
        SDBThreadAttach t;
        if( t.pEnv )
            t.pEnv->DeleteGlobalRef( object );
        object = NULL;
    }
}
// der protected-Konstruktor fuer abgeleitete Klassen
void java_lang_Object::saveRef( JNIEnv * pXEnv, jobject myObj )
{
    OSL_ENSURE( myObj, "object in c++ -> Java Wrapper" );
    if( pXEnv && myObj )
        object = pXEnv->NewGlobalRef( myObj );
}

java_lang_Class * java_lang_Object::getClass()
{
    jobject out;
    SDBThreadAttach t;
    if( t.pEnv )
    {
        // temporaere Variable initialisieren
        static char * cSignature = "()Ljava/lang/Class;";
        static char * cMethodName = "getClass";
        // Java-Call absetzen
        static jmethodID mID = NULL;
        if ( !mID  )
            mID  = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
        if( mID )
        {
            out = t.pEnv->CallObjectMethodA( object, mID, NULL );
            ThrowSQLException(t.pEnv,NULL);
            return new java_lang_Class( t.pEnv, out );
        } //mID
    } //pEnv
    return NULL;
}

::rtl::OUString java_lang_Object::toString()
{

    SDBThreadAttach t;
    ::rtl::OUString aStr;
    if( t.pEnv )
    {
        // temporaere Variable initialisieren
        static char * cSignature = "()Ljava/lang/String;";
        static char * cMethodName = "toString";
        // Java-Call absetzen
        static jmethodID mID = NULL;
        if ( !mID  )
            mID  = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
        if( mID )
        {
            jstring out = (jstring)t.pEnv->CallObjectMethod( object, mID);
            ThrowSQLException(t.pEnv,NULL);
            aStr = JavaString2String(t.pEnv,out);
        } //mID
    } //pEnv
    return  aStr;
}
// --------------------------------------------------------------------------------
void java_lang_Object::ThrowSQLException(JNIEnv * pEnv,const Reference< XInterface> & _rContext) throw(SQLException, RuntimeException)
{
    jthrowable jThrow = NULL;
    if(pEnv && (jThrow = pEnv->ExceptionOccurred()))
    {
        pEnv->ExceptionClear();// we have to clear the exception here because we want to handle it itself
        if(pEnv->IsInstanceOf(jThrow,java_sql_SQLException_BASE::getMyClass()))
        {
            java_sql_SQLException_BASE* pException = new java_sql_SQLException_BASE(pEnv,jThrow);
            SQLException e( pException->getMessage(),
                                _rContext,
                                pException->getSQLState(),
                                pException->getErrorCode(),
                                Any()
                            );
            delete pException;
            throw  e;
        }
        else if(pEnv->IsInstanceOf(jThrow,java_lang_Throwable::getMyClass()))
        {
            java_lang_Throwable *pThrow = new java_lang_Throwable(pEnv,jThrow);
            ::rtl::OUString aMsg = pThrow->getMessage();
            if(!aMsg.getLength())
                aMsg = pThrow->getLocalizedMessage();
            if(!aMsg.getLength())
                aMsg = pThrow->toString();
            delete pThrow;
            throw SQLException(aMsg,_rContext,::rtl::OUString(),-1,Any());
        }
        else
            pEnv->DeleteLocalRef( jThrow );
    }
}

<|endoftext|>