<commit_before>/*************************************************************************
 *
 *  $RCSfile: ConfigurationAccess.cxx,v $
 *
 *  $Revision: 1.1 $
 *
 *  last change: $Author: iha $ $Date: 2003-12-10 18:11:33 $
 *
 *  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: 2003 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include "ConfigurationAccess.hxx"
#include "macros.hxx"

// header for class SvtSysLocale
#ifndef INCLUDED_SVTOOLS_SYSLOCALE_HXX
#include <svtools/syslocale.hxx>
#endif
// header for class ConfigItem
#ifndef _UTL_CONFIGITEM_HXX_
#include <unotools/configitem.hxx>
#endif

//.............................................................................
namespace chart
{
//.............................................................................
using namespace ::com::sun::star;

namespace
{
bool lcl_IsMetric()
{
    SvtSysLocale aSysLocale;
    const LocaleDataWrapper* pLocWrapper = aSysLocale.GetLocaleDataPtr();
    MeasurementSystem eSys = pLocWrapper->getMeasurementSystemEnum();

    return ( eSys == MEASURE_METRIC );
}
}//end anonymous namespace

class CalcConfigItem : public ::utl::ConfigItem
{
public:
    CalcConfigItem();
    virtual ~CalcConfigItem();

    FieldUnit getFieldUnit();
};

CalcConfigItem::CalcConfigItem()
    : ConfigItem( ::rtl::OUString( C2U( "Office.Calc/Layout" )))
{
}
CalcConfigItem::~CalcConfigItem()
{
}

FieldUnit CalcConfigItem::getFieldUnit()
{
    FieldUnit eResult( FUNIT_CM );

    uno::Sequence< ::rtl::OUString > aNames( 1 );
    if( lcl_IsMetric() )
        aNames[ 0 ] = ::rtl::OUString( C2U( "Other/MeasureUnit/Metric" ));
    else
        aNames[ 0 ] = ::rtl::OUString( C2U( "Other/MeasureUnit/NonMetric" ));

    uno::Sequence< uno::Any > aResult( GetProperties( aNames ));
    sal_Int32 nValue;
    if( aResult[ 0 ] >>= nValue )
        eResult = static_cast< FieldUnit >( nValue );

    return eResult;
}

ConfigurationAccess::ConfigurationAccess()
    : m_pCalcConfigItem(0)
{
    m_pCalcConfigItem = new CalcConfigItem();
}
ConfigurationAccess::~ConfigurationAccess()
{
    delete m_pCalcConfigItem;
}
FieldUnit ConfigurationAccess::getFieldUnit()
{
    FieldUnit aUnit( m_pCalcConfigItem->getFieldUnit() );
    return aUnit;
}

//.............................................................................
} //namespace chart
//.............................................................................
<commit_msg>INTEGRATION: CWS ooo19126 (1.1.110); FILE MERGED 2005/09/05 18:42:44 rt 1.1.110.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ConfigurationAccess.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 00:34:21 $
 *
 *  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 "ConfigurationAccess.hxx"
#include "macros.hxx"

// header for class SvtSysLocale
#ifndef INCLUDED_SVTOOLS_SYSLOCALE_HXX
#include <svtools/syslocale.hxx>
#endif
// header for class ConfigItem
#ifndef _UTL_CONFIGITEM_HXX_
#include <unotools/configitem.hxx>
#endif

//.............................................................................
namespace chart
{
//.............................................................................
using namespace ::com::sun::star;

namespace
{
bool lcl_IsMetric()
{
    SvtSysLocale aSysLocale;
    const LocaleDataWrapper* pLocWrapper = aSysLocale.GetLocaleDataPtr();
    MeasurementSystem eSys = pLocWrapper->getMeasurementSystemEnum();

    return ( eSys == MEASURE_METRIC );
}
}//end anonymous namespace

class CalcConfigItem : public ::utl::ConfigItem
{
public:
    CalcConfigItem();
    virtual ~CalcConfigItem();

    FieldUnit getFieldUnit();
};

CalcConfigItem::CalcConfigItem()
    : ConfigItem( ::rtl::OUString( C2U( "Office.Calc/Layout" )))
{
}
CalcConfigItem::~CalcConfigItem()
{
}

FieldUnit CalcConfigItem::getFieldUnit()
{
    FieldUnit eResult( FUNIT_CM );

    uno::Sequence< ::rtl::OUString > aNames( 1 );
    if( lcl_IsMetric() )
        aNames[ 0 ] = ::rtl::OUString( C2U( "Other/MeasureUnit/Metric" ));
    else
        aNames[ 0 ] = ::rtl::OUString( C2U( "Other/MeasureUnit/NonMetric" ));

    uno::Sequence< uno::Any > aResult( GetProperties( aNames ));
    sal_Int32 nValue;
    if( aResult[ 0 ] >>= nValue )
        eResult = static_cast< FieldUnit >( nValue );

    return eResult;
}

ConfigurationAccess::ConfigurationAccess()
    : m_pCalcConfigItem(0)
{
    m_pCalcConfigItem = new CalcConfigItem();
}
ConfigurationAccess::~ConfigurationAccess()
{
    delete m_pCalcConfigItem;
}
FieldUnit ConfigurationAccess::getFieldUnit()
{
    FieldUnit aUnit( m_pCalcConfigItem->getFieldUnit() );
    return aUnit;
}

//.............................................................................
} //namespace chart
//.............................................................................
<|endoftext|>


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

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_chart2.hxx"
#include "BarChartTypeTemplate.hxx"
#include "macros.hxx"
#include "DiagramHelper.hxx"
#include "servicenames_charttypes.hxx"
#include "ContainerHelper.hxx"
#include "DataSeriesHelper.hxx"

#ifndef CHART_PROPERTYHELPER_HXX
#include "PropertyHelper.hxx"
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_
#include <com/sun/star/beans/PropertyAttribute.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_LINESTYLE_HPP_
#include <com/sun/star/drawing/LineStyle.hpp>
#endif
#ifndef _COM_SUN_STAR_CHART2_DATAPOINTGEOMETRY3D_HPP_
#include <com/sun/star/chart2/DataPointGeometry3D.hpp>
#endif

#include <algorithm>

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

using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Sequence;
using ::com::sun::star::beans::Property;
using ::osl::MutexGuard;
using ::rtl::OUString;

namespace
{

static const OUString lcl_aServiceName(
    RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.chart2.BarChartTypeTemplate" ));

enum
{
    PROP_BAR_TEMPLATE_DIMENSION,
    PROP_BAR_TEMPLATE_GEOMETRY3D
};

void lcl_AddPropertiesToVector(
    ::std::vector< Property > & rOutProperties )
{
    rOutProperties.push_back(
        Property( C2U( "Dimension" ),
                  PROP_BAR_TEMPLATE_DIMENSION,
                  ::getCppuType( reinterpret_cast< const sal_Int32 * >(0)),
                  beans::PropertyAttribute::BOUND
                  | beans::PropertyAttribute::MAYBEDEFAULT ));
    rOutProperties.push_back(
        Property( C2U( "Geometry3D" ),
                  PROP_BAR_TEMPLATE_GEOMETRY3D,
                  ::getCppuType( reinterpret_cast< const sal_Int32 * >(0)),
                  beans::PropertyAttribute::BOUND
                  | beans::PropertyAttribute::MAYBEDEFAULT ));
}

void lcl_AddDefaultsToMap(
    ::chart::tPropertyValueMap & rOutMap )
{
    ::chart::PropertyHelper::setPropertyValueDefault< sal_Int32 >( rOutMap, PROP_BAR_TEMPLATE_DIMENSION, 2 );
    ::chart::PropertyHelper::setPropertyValueDefault( rOutMap, PROP_BAR_TEMPLATE_GEOMETRY3D, ::chart2::DataPointGeometry3D::CUBOID );
}

const Sequence< Property > & lcl_GetPropertySequence()
{
    static Sequence< Property > aPropSeq;

    // /--
    MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
    if( 0 == aPropSeq.getLength() )
    {
        // get properties
        ::std::vector< ::com::sun::star::beans::Property > aProperties;
        lcl_AddPropertiesToVector( aProperties );

        // and sort them for access via bsearch
        ::std::sort( aProperties.begin(), aProperties.end(),
                     ::chart::PropertyNameLess() );

        // transfer result to static Sequence
        aPropSeq = ::chart::ContainerHelper::ContainerToSequence( aProperties );
    }

    return aPropSeq;
}

::cppu::IPropertyArrayHelper & lcl_getInfoHelper()
{
    static ::cppu::OPropertyArrayHelper aArrayHelper(
        lcl_GetPropertySequence(),
        /* bSorted = */ sal_True );

    return aArrayHelper;
}

} // anonymous namespace

namespace chart
{

BarChartTypeTemplate::BarChartTypeTemplate(
    Reference<
        uno::XComponentContext > const & xContext,
    const OUString & rServiceName,
    StackMode eStackMode,
    BarDirection eDirection,
    sal_Int32 nDim         /* = 2 */ ) :
        ChartTypeTemplate( xContext, rServiceName ),
        ::property::OPropertySet( m_aMutex ),
        m_eStackMode( eStackMode ),
        m_eBarDirection( eDirection ),
        m_nDim( nDim )
{}

BarChartTypeTemplate::~BarChartTypeTemplate()
{}

sal_Int32 BarChartTypeTemplate::getDimension() const
{
    return m_nDim;
}

StackMode BarChartTypeTemplate::getStackMode( sal_Int32 /* nChartTypeIndex */ ) const
{
    return m_eStackMode;
}

bool BarChartTypeTemplate::isSwapXAndY() const
{
    return (m_eBarDirection == HORIZONTAL);
}

// ____ XChartTypeTemplate ____
sal_Bool SAL_CALL BarChartTypeTemplate::matchesTemplate(
    const Reference< chart2::XDiagram >& xDiagram,
    sal_Bool bAdaptProperties )
    throw (uno::RuntimeException)
{
    sal_Bool bResult = ChartTypeTemplate::matchesTemplate( xDiagram, bAdaptProperties );

    //check BarDirection
    if( bResult )
    {
        bool bFound = false;
        bool bAmbiguous = false;
        bool bVertical = DiagramHelper::getVertical( xDiagram, bFound, bAmbiguous );
        if( m_eBarDirection == HORIZONTAL )
            bResult = sal_Bool( bVertical );
        else if( m_eBarDirection == VERTICAL )
            bResult = sal_Bool( !bVertical );
    }

    // adapt solid-type of template according to values in series
    if( bAdaptProperties &&
        bResult &&
        getDimension() == 3 )
    {
        ::std::vector< Reference< chart2::XDataSeries > > aSeriesVec(
            DiagramHelper::getDataSeriesFromDiagram( xDiagram ));

        sal_Int32 aCommonGeom( 0 );
        bool bGeomFound = false, bAdaptGeom = false;
        for( ::std::vector< Reference< chart2::XDataSeries > >::const_iterator aIt =
                 aSeriesVec.begin(); aIt != aSeriesVec.end(); ++aIt )
        {
            try
            {
                sal_Int32 aGeom = 0;
                Reference< beans::XPropertySet > xProp( *aIt, uno::UNO_QUERY_THROW );
                if( xProp->getPropertyValue( C2U( "Geometry3D" )) >>= aGeom )
                {
                    if( ! bGeomFound )
                    {
                        // first series
                        aCommonGeom = aGeom;
                        bGeomFound = true;
                        bAdaptGeom = true;
                    }
                    else
                    {
                        // further series: compare for uniqueness
                        if( aCommonGeom != aGeom )
                        {
                            bAdaptGeom = false;
                            break;
                        }
                    }
                }
            }
            catch( uno::Exception & ex )
            {
                ASSERT_EXCEPTION( ex );
            }
        }

        if( bAdaptGeom )
        {
            setFastPropertyValue_NoBroadcast(
                PROP_BAR_TEMPLATE_GEOMETRY3D, uno::makeAny( aCommonGeom ));
        }
    }

    return bResult;
}
Reference< chart2::XChartType > BarChartTypeTemplate::getChartTypeForIndex( sal_Int32 /*nChartTypeIndex*/ )
{
    Reference< chart2::XChartType > xResult;

    try
    {
        Reference< lang::XMultiServiceFactory > xFact(
            GetComponentContext()->getServiceManager(), uno::UNO_QUERY_THROW );
        xResult.set( xFact->createInstance(
                         CHART2_SERVICE_NAME_CHARTTYPE_COLUMN ), uno::UNO_QUERY_THROW );
    }
    catch( uno::Exception & ex )
    {
        ASSERT_EXCEPTION( ex );
    }

    return xResult;
}

Reference< chart2::XChartType > SAL_CALL BarChartTypeTemplate::getChartTypeForNewSeries(
        const uno::Sequence< Reference< chart2::XChartType > >& aFormerlyUsedChartTypes )
    throw (uno::RuntimeException)
{
    Reference< chart2::XChartType > xResult( getChartTypeForIndex( 0 ) );
    ChartTypeTemplate::copyPropertiesFromOldToNewCoordianteSystem( aFormerlyUsedChartTypes, xResult );
    return xResult;
}

// ____ OPropertySet ____
uno::Any BarChartTypeTemplate::GetDefaultValue( sal_Int32 nHandle ) const
    throw(beans::UnknownPropertyException)
{
    static tPropertyValueMap aStaticDefaults;

    // /--
    ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
    if( 0 == aStaticDefaults.size() )
    {
        // initialize defaults
        lcl_AddDefaultsToMap( aStaticDefaults );
    }

    tPropertyValueMap::const_iterator aFound(
        aStaticDefaults.find( nHandle ));

    if( aFound == aStaticDefaults.end())
        return uno::Any();

    return (*aFound).second;
    // \--
}

::cppu::IPropertyArrayHelper & SAL_CALL BarChartTypeTemplate::getInfoHelper()
{
    return lcl_getInfoHelper();
}

// ____ XPropertySet ____
Reference< beans::XPropertySetInfo > SAL_CALL
    BarChartTypeTemplate::getPropertySetInfo()
    throw (uno::RuntimeException)
{
    static Reference< beans::XPropertySetInfo > xInfo;

    // /--
    MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
    if( !xInfo.is())
    {
        xInfo = ::cppu::OPropertySetHelper::createPropertySetInfo(
            getInfoHelper());
    }

    return xInfo;
    // \--
}

void SAL_CALL BarChartTypeTemplate::applyStyle(
    const Reference< chart2::XDataSeries >& xSeries,
    ::sal_Int32 nChartTypeIndex,
    ::sal_Int32 nSeriesIndex,
    ::sal_Int32 nSeriesCount )
    throw (uno::RuntimeException)
{
    ChartTypeTemplate::applyStyle( xSeries, nChartTypeIndex, nSeriesIndex, nSeriesCount );
    if( getDimension() == 3 )
    {
        try
        {
            //apply Geometry3D
            uno::Any aAGeometry3D;
            this->getFastPropertyValue( aAGeometry3D, PROP_BAR_TEMPLATE_GEOMETRY3D );
            DataSeriesHelper::setPropertyAlsoToAllAttributedDataPoints( xSeries, C2U( "Geometry3D" ), aAGeometry3D );
        }
        catch( uno::Exception & ex )
        {
            ASSERT_EXCEPTION( ex );
        }
    }
}

void SAL_CALL BarChartTypeTemplate::resetStyles(
    const Reference< chart2::XDiagram >& xDiagram )
    throw (uno::RuntimeException)
{
    ChartTypeTemplate::resetStyles( xDiagram );
    if( getDimension() == 3 )
    {
        ::std::vector< Reference< chart2::XDataSeries > > aSeriesVec(
            DiagramHelper::getDataSeriesFromDiagram( xDiagram ));
        uno::Any aLineStyleAny( uno::makeAny( drawing::LineStyle_NONE ));
        for( ::std::vector< Reference< chart2::XDataSeries > >::iterator aIt( aSeriesVec.begin());
             aIt != aSeriesVec.end(); ++aIt )
        {
            Reference< beans::XPropertyState > xState( *aIt, uno::UNO_QUERY );
            if( xState.is())
            {
                xState->setPropertyToDefault( C2U("Geometry3D"));
                Reference< beans::XPropertySet > xProp( xState, uno::UNO_QUERY );
                if( xProp.is() &&
                    xProp->getPropertyValue( C2U("BorderStyle")) == aLineStyleAny )
                {
                    xState->setPropertyToDefault( C2U("BorderStyle"));
                }
            }
        }
    }

    DiagramHelper::setVertical( xDiagram, false );
}

void BarChartTypeTemplate::createCoordinateSystems(
    const Reference< chart2::XCoordinateSystemContainer > & xCooSysCnt )
{
    ChartTypeTemplate::createCoordinateSystems( xCooSysCnt );

    Reference< chart2::XDiagram > xDiagram( xCooSysCnt, uno::UNO_QUERY );
    DiagramHelper::setVertical( xDiagram, m_eBarDirection == HORIZONTAL );
}

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

Sequence< OUString > BarChartTypeTemplate::getSupportedServiceNames_Static()
{
    Sequence< OUString > aServices( 2 );
    aServices[ 0 ] = lcl_aServiceName;
    aServices[ 1 ] = C2U( "com.sun.star.chart2.ChartTypeTemplate" );
    return aServices;
}

// implement XServiceInfo methods basing upon getSupportedServiceNames_Static
APPHELPER_XSERVICEINFO_IMPL( BarChartTypeTemplate, lcl_aServiceName );

IMPLEMENT_FORWARD_XINTERFACE2( BarChartTypeTemplate, ChartTypeTemplate, OPropertySet )
IMPLEMENT_FORWARD_XTYPEPROVIDER2( BarChartTypeTemplate, ChartTypeTemplate, OPropertySet )

} //  namespace chart
<commit_msg>INTEGRATION: CWS chart15 (1.11.10); FILE MERGED 2007/12/12 09:51:30 bm 1.11.10.2: RESYNC: (1.11-1.12); FILE MERGED 2007/12/05 13:22:55 bm 1.11.10.1: #i79698# use new helper DiagramHelper::getGeometry3D<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: BarChartTypeTemplate.cxx,v $
 *
 *  $Revision: 1.13 $
 *
 *  last change: $Author: ihi $ $Date: 2008-01-14 14:02:50 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_chart2.hxx"
#include "BarChartTypeTemplate.hxx"
#include "macros.hxx"
#include "DiagramHelper.hxx"
#include "servicenames_charttypes.hxx"
#include "ContainerHelper.hxx"
#include "DataSeriesHelper.hxx"

#ifndef CHART_PROPERTYHELPER_HXX
#include "PropertyHelper.hxx"
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_
#include <com/sun/star/beans/PropertyAttribute.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_LINESTYLE_HPP_
#include <com/sun/star/drawing/LineStyle.hpp>
#endif
#ifndef _COM_SUN_STAR_CHART2_DATAPOINTGEOMETRY3D_HPP_
#include <com/sun/star/chart2/DataPointGeometry3D.hpp>
#endif

#include <algorithm>

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

using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Sequence;
using ::com::sun::star::beans::Property;
using ::osl::MutexGuard;
using ::rtl::OUString;

namespace
{

static const OUString lcl_aServiceName(
    RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.chart2.BarChartTypeTemplate" ));

enum
{
    PROP_BAR_TEMPLATE_DIMENSION,
    PROP_BAR_TEMPLATE_GEOMETRY3D
};

void lcl_AddPropertiesToVector(
    ::std::vector< Property > & rOutProperties )
{
    rOutProperties.push_back(
        Property( C2U( "Dimension" ),
                  PROP_BAR_TEMPLATE_DIMENSION,
                  ::getCppuType( reinterpret_cast< const sal_Int32 * >(0)),
                  beans::PropertyAttribute::BOUND
                  | beans::PropertyAttribute::MAYBEDEFAULT ));
    rOutProperties.push_back(
        Property( C2U( "Geometry3D" ),
                  PROP_BAR_TEMPLATE_GEOMETRY3D,
                  ::getCppuType( reinterpret_cast< const sal_Int32 * >(0)),
                  beans::PropertyAttribute::BOUND
                  | beans::PropertyAttribute::MAYBEDEFAULT ));
}

void lcl_AddDefaultsToMap(
    ::chart::tPropertyValueMap & rOutMap )
{
    ::chart::PropertyHelper::setPropertyValueDefault< sal_Int32 >( rOutMap, PROP_BAR_TEMPLATE_DIMENSION, 2 );
    ::chart::PropertyHelper::setPropertyValueDefault( rOutMap, PROP_BAR_TEMPLATE_GEOMETRY3D, ::chart2::DataPointGeometry3D::CUBOID );
}

const Sequence< Property > & lcl_GetPropertySequence()
{
    static Sequence< Property > aPropSeq;

    // /--
    MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
    if( 0 == aPropSeq.getLength() )
    {
        // get properties
        ::std::vector< ::com::sun::star::beans::Property > aProperties;
        lcl_AddPropertiesToVector( aProperties );

        // and sort them for access via bsearch
        ::std::sort( aProperties.begin(), aProperties.end(),
                     ::chart::PropertyNameLess() );

        // transfer result to static Sequence
        aPropSeq = ::chart::ContainerHelper::ContainerToSequence( aProperties );
    }

    return aPropSeq;
}

::cppu::IPropertyArrayHelper & lcl_getInfoHelper()
{
    static ::cppu::OPropertyArrayHelper aArrayHelper(
        lcl_GetPropertySequence(),
        /* bSorted = */ sal_True );

    return aArrayHelper;
}

} // anonymous namespace

namespace chart
{

BarChartTypeTemplate::BarChartTypeTemplate(
    Reference<
        uno::XComponentContext > const & xContext,
    const OUString & rServiceName,
    StackMode eStackMode,
    BarDirection eDirection,
    sal_Int32 nDim         /* = 2 */ ) :
        ChartTypeTemplate( xContext, rServiceName ),
        ::property::OPropertySet( m_aMutex ),
        m_eStackMode( eStackMode ),
        m_eBarDirection( eDirection ),
        m_nDim( nDim )
{}

BarChartTypeTemplate::~BarChartTypeTemplate()
{}

sal_Int32 BarChartTypeTemplate::getDimension() const
{
    return m_nDim;
}

StackMode BarChartTypeTemplate::getStackMode( sal_Int32 /* nChartTypeIndex */ ) const
{
    return m_eStackMode;
}

bool BarChartTypeTemplate::isSwapXAndY() const
{
    return (m_eBarDirection == HORIZONTAL);
}

// ____ XChartTypeTemplate ____
sal_Bool SAL_CALL BarChartTypeTemplate::matchesTemplate(
    const Reference< chart2::XDiagram >& xDiagram,
    sal_Bool bAdaptProperties )
    throw (uno::RuntimeException)
{
    sal_Bool bResult = ChartTypeTemplate::matchesTemplate( xDiagram, bAdaptProperties );

    //check BarDirection
    if( bResult )
    {
        bool bFound = false;
        bool bAmbiguous = false;
        bool bVertical = DiagramHelper::getVertical( xDiagram, bFound, bAmbiguous );
        if( m_eBarDirection == HORIZONTAL )
            bResult = sal_Bool( bVertical );
        else if( m_eBarDirection == VERTICAL )
            bResult = sal_Bool( !bVertical );
    }

    // adapt solid-type of template according to values in series
    if( bAdaptProperties &&
        bResult &&
        getDimension() == 3 )
    {
        ::std::vector< Reference< chart2::XDataSeries > > aSeriesVec(
            DiagramHelper::getDataSeriesFromDiagram( xDiagram ));

        bool bGeomFound = false, bGeomAmbiguous = false;
        sal_Int32 aCommonGeom = DiagramHelper::getGeometry3D( xDiagram, bGeomFound, bGeomAmbiguous );

        if( !bGeomAmbiguous )
        {
            setFastPropertyValue_NoBroadcast(
                PROP_BAR_TEMPLATE_GEOMETRY3D, uno::makeAny( aCommonGeom ));
        }
    }

    return bResult;
}
Reference< chart2::XChartType > BarChartTypeTemplate::getChartTypeForIndex( sal_Int32 /*nChartTypeIndex*/ )
{
    Reference< chart2::XChartType > xResult;

    try
    {
        Reference< lang::XMultiServiceFactory > xFact(
            GetComponentContext()->getServiceManager(), uno::UNO_QUERY_THROW );
        xResult.set( xFact->createInstance(
                         CHART2_SERVICE_NAME_CHARTTYPE_COLUMN ), uno::UNO_QUERY_THROW );
    }
    catch( uno::Exception & ex )
    {
        ASSERT_EXCEPTION( ex );
    }

    return xResult;
}

Reference< chart2::XChartType > SAL_CALL BarChartTypeTemplate::getChartTypeForNewSeries(
        const uno::Sequence< Reference< chart2::XChartType > >& aFormerlyUsedChartTypes )
    throw (uno::RuntimeException)
{
    Reference< chart2::XChartType > xResult( getChartTypeForIndex( 0 ) );
    ChartTypeTemplate::copyPropertiesFromOldToNewCoordianteSystem( aFormerlyUsedChartTypes, xResult );
    return xResult;
}

// ____ OPropertySet ____
uno::Any BarChartTypeTemplate::GetDefaultValue( sal_Int32 nHandle ) const
    throw(beans::UnknownPropertyException)
{
    static tPropertyValueMap aStaticDefaults;

    // /--
    ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
    if( 0 == aStaticDefaults.size() )
    {
        // initialize defaults
        lcl_AddDefaultsToMap( aStaticDefaults );
    }

    tPropertyValueMap::const_iterator aFound(
        aStaticDefaults.find( nHandle ));

    if( aFound == aStaticDefaults.end())
        return uno::Any();

    return (*aFound).second;
    // \--
}

::cppu::IPropertyArrayHelper & SAL_CALL BarChartTypeTemplate::getInfoHelper()
{
    return lcl_getInfoHelper();
}

// ____ XPropertySet ____
Reference< beans::XPropertySetInfo > SAL_CALL
    BarChartTypeTemplate::getPropertySetInfo()
    throw (uno::RuntimeException)
{
    static Reference< beans::XPropertySetInfo > xInfo;

    // /--
    MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
    if( !xInfo.is())
    {
        xInfo = ::cppu::OPropertySetHelper::createPropertySetInfo(
            getInfoHelper());
    }

    return xInfo;
    // \--
}

void SAL_CALL BarChartTypeTemplate::applyStyle(
    const Reference< chart2::XDataSeries >& xSeries,
    ::sal_Int32 nChartTypeIndex,
    ::sal_Int32 nSeriesIndex,
    ::sal_Int32 nSeriesCount )
    throw (uno::RuntimeException)
{
    ChartTypeTemplate::applyStyle( xSeries, nChartTypeIndex, nSeriesIndex, nSeriesCount );
    if( getDimension() == 3 )
    {
        try
        {
            //apply Geometry3D
            uno::Any aAGeometry3D;
            this->getFastPropertyValue( aAGeometry3D, PROP_BAR_TEMPLATE_GEOMETRY3D );
            DataSeriesHelper::setPropertyAlsoToAllAttributedDataPoints( xSeries, C2U( "Geometry3D" ), aAGeometry3D );
        }
        catch( uno::Exception & ex )
        {
            ASSERT_EXCEPTION( ex );
        }
    }
}

void SAL_CALL BarChartTypeTemplate::resetStyles(
    const Reference< chart2::XDiagram >& xDiagram )
    throw (uno::RuntimeException)
{
    ChartTypeTemplate::resetStyles( xDiagram );
    if( getDimension() == 3 )
    {
        ::std::vector< Reference< chart2::XDataSeries > > aSeriesVec(
            DiagramHelper::getDataSeriesFromDiagram( xDiagram ));
        uno::Any aLineStyleAny( uno::makeAny( drawing::LineStyle_NONE ));
        for( ::std::vector< Reference< chart2::XDataSeries > >::iterator aIt( aSeriesVec.begin());
             aIt != aSeriesVec.end(); ++aIt )
        {
            Reference< beans::XPropertyState > xState( *aIt, uno::UNO_QUERY );
            if( xState.is())
            {
                xState->setPropertyToDefault( C2U("Geometry3D"));
                Reference< beans::XPropertySet > xProp( xState, uno::UNO_QUERY );
                if( xProp.is() &&
                    xProp->getPropertyValue( C2U("BorderStyle")) == aLineStyleAny )
                {
                    xState->setPropertyToDefault( C2U("BorderStyle"));
                }
            }
        }
    }

    DiagramHelper::setVertical( xDiagram, false );
}

void BarChartTypeTemplate::createCoordinateSystems(
    const Reference< chart2::XCoordinateSystemContainer > & xCooSysCnt )
{
    ChartTypeTemplate::createCoordinateSystems( xCooSysCnt );

    Reference< chart2::XDiagram > xDiagram( xCooSysCnt, uno::UNO_QUERY );
    DiagramHelper::setVertical( xDiagram, m_eBarDirection == HORIZONTAL );
}

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

Sequence< OUString > BarChartTypeTemplate::getSupportedServiceNames_Static()
{
    Sequence< OUString > aServices( 2 );
    aServices[ 0 ] = lcl_aServiceName;
    aServices[ 1 ] = C2U( "com.sun.star.chart2.ChartTypeTemplate" );
    return aServices;
}

// implement XServiceInfo methods basing upon getSupportedServiceNames_Static
APPHELPER_XSERVICEINFO_IMPL( BarChartTypeTemplate, lcl_aServiceName );

IMPLEMENT_FORWARD_XINTERFACE2( BarChartTypeTemplate, ChartTypeTemplate, OPropertySet )
IMPLEMENT_FORWARD_XTYPEPROVIDER2( BarChartTypeTemplate, ChartTypeTemplate, OPropertySet )

} //  namespace chart
<|endoftext|>


<commit_before>//
// Copyright (c) 2003-2011 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
/*
 * Copyright (c) 2010-2011 frankee zhou (frankee.zhou at gmail dot com)
 *
 * Distributed under under the Apache License, version 2.0 (the "License").
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at:
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */

#include <cetty/channel/socket/asio/AsioServicePool.h>

#include <boost/bind.hpp>

#include <cetty/util/Exception.h>
#include <cetty/logging/LoggerHelper.h>

#include <cetty/channel/socket/asio/AsioService.h>

namespace cetty {
namespace channel {
namespace socket {
namespace asio {

using namespace cetty::logging;
using namespace boost::asio;

class AsioServiceHolder : public EventLoopPool::EventLoopHolder {
public:
    enum {
        INITIALIZED =  0,
        RUNNING     =  1,
        STOPPED     = -1
    };

    typedef boost::shared_ptr<boost::thread> ThreadPtr;
    typedef boost::shared_ptr<boost::asio::io_service::work> WorkPtr;

public:
    AsioServiceHolder() : state(INITIALIZED), priority(0) {}
    virtual ~AsioServiceHolder() {}

    virtual const EventLoopPtr& getEventLoop() const {
        return eventLoop;
    }

    int state;
    int priority;

    WorkPtr work; /// The work that keeps the io_services running.
    ThreadPtr thread;
    AsioServicePtr service;
    EventLoopPtr eventLoop;

    void stop() {
        if (state != STOPPED) {
            state = STOPPED;
            service->stop();
        }
    }
};

AsioServicePool::AsioServicePool(int threadCnt)
    : EventLoopPool(threadCnt),
      nextServiceIndex(0) {

    // Give all the io_services work to do so that their run() functions will not
    // exit until they are explicitly stopped.
    for (int i = 0; i < eventLoopCnt; ++i) {
        AsioServiceHolder* holder = new AsioServiceHolder();
        AsioServicePtr service = new AsioService(shared_from_this());
        holder->service = service;
        holder->eventLoop = boost::static_pointer_cast<EventLoop>(service);
        holder->work = WorkPtr(new io_service::work(service->service()));

        eventLoops.push_back(holder);
    }

    // automatic start
    if (!mainThread) {
        // Create a pool of threads to run all of the io_services.
        for (std::size_t i = 0; i < eventLoops.size(); ++i) {
            AsioServiceHolder* holder = (AsioServiceHolder*)eventLoops[i];
            holder->thread
                = ThreadPtr(new boost::thread(
                                boost::bind(&AsioServicePool::runIOservice,
                                            this,
                                            holder)));

            boost::thread::id id = holder->thread->get_id();
            holder->service->setThreadId(id);
            allEventLoops.insert(std::make_pair(id, holder->eventLoop));
        }

        started = true;
    }
    else {
        AsioServiceHolder* holder = (AsioServiceHolder*)eventLoops.front();

        boost::thread::id id = boost::this_thread::get_id();
        holder->service->setThreadId(id);
        allEventLoops.insert(std::make_pair(id, holder->eventLoop));
    }
}

bool AsioServicePool::start() {
    if (!started && mainThread) {
        LOG_INFO << "AsioServciePool running in main thread mode.";

        if (runIOservice((AsioServiceHolder*)eventLoops.front()) < 0) {
            LOG_ERROR << "AsioServicePool run the main thread service error.";
            return false;
        }
    }

    started = true;
    return true;
}

void cetty::channel::socket::asio::AsioServicePool::waitForStop() {
    if (mainThread) {
        return;
    }

    // Wait for all threads in the pool to exit.
    for (int i = 0; i < eventLoopCnt; ++i) {
        AsioServiceHolder* holder = (AsioServiceHolder*)eventLoops[i];
        holder->thread->join();
    }
}

void AsioServicePool::stop() {
    // Explicitly stop all io_services.
    for (int i = 0; i < eventLoopCnt; ++i) {
        AsioServiceHolder* holder = (AsioServiceHolder*)eventLoops[i];
        holder->stop();
    }

    started = false;
}

const AsioServicePtr& AsioServicePool::getNextService() {
    return getNextServiceHolder()->service;
}

int AsioServicePool::runIOservice(AsioServiceHolder* holder) {
    BOOST_ASSERT(holder && holder->service && "ioservice can not be NULL.");

    AsioServicePtr& service = holder->service;

    boost::system::error_code err;
    std::size_t opCount = service->service().run(err);

    // if error happened, try to recover.
    if (err) {
        LOG_ERROR  << "when runIOservice, the io service has error = " << err.value();
        stop();
        return -1;
    }

    LOG_INFO << "runIOservice OK, and " << opCount << "handlers that were executed.";
    return opCount;
}

const EventLoopPtr& AsioServicePool::getNextLoop() {
    return getNextServiceHolder()->eventLoop;
}

AsioServiceHolder* AsioServicePool::getNextServiceHolder() {
    // Only one service.
    if (eventLoopCnt == 1) {
        return (AsioServiceHolder*)eventLoops.front();
    }

    // Use a round-robin scheme to choose the next io_service to use.
    AsioServiceHolder* holder = (AsioServiceHolder*)eventLoops[nextServiceIndex];
    ++nextServiceIndex;

    if (nextServiceIndex == eventLoopCnt) {
        nextServiceIndex = 0;
    }

    return holder;
}

}
}
}
}
<commit_msg>在线程启动时候，重新设置thread id<commit_after>//
// Copyright (c) 2003-2011 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
/*
 * Copyright (c) 2010-2011 frankee zhou (frankee.zhou at gmail dot com)
 *
 * Distributed under under the Apache License, version 2.0 (the "License").
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at:
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */

#include <cetty/channel/socket/asio/AsioServicePool.h>

#include <boost/bind.hpp>

#include <cetty/util/Exception.h>
#include <cetty/logging/LoggerHelper.h>

#include <cetty/channel/socket/asio/AsioService.h>

namespace cetty {
namespace channel {
namespace socket {
namespace asio {

using namespace cetty::logging;
using namespace boost::asio;

class AsioServiceHolder : public EventLoopPool::EventLoopHolder {
public:
    enum {
        INITIALIZED =  0,
        RUNNING     =  1,
        STOPPED     = -1
    };

    typedef boost::shared_ptr<boost::thread> ThreadPtr;
    typedef boost::shared_ptr<boost::asio::io_service::work> WorkPtr;

public:
    AsioServiceHolder() : state(INITIALIZED), priority(0) {}
    virtual ~AsioServiceHolder() {}

    virtual const EventLoopPtr& getEventLoop() const {
        return eventLoop;
    }

    int state;
    int priority;

    WorkPtr work; /// The work that keeps the io_services running.
    ThreadPtr thread;
    AsioServicePtr service;
    EventLoopPtr eventLoop;

    void stop() {
        if (state != STOPPED) {
            state = STOPPED;
            service->stop();
        }
    }
};

AsioServicePool::AsioServicePool(int threadCnt)
    : EventLoopPool(threadCnt),
      nextServiceIndex(0) {

    // Give all the io_services work to do so that their run() functions will not
    // exit until they are explicitly stopped.
    for (int i = 0; i < eventLoopCnt; ++i) {
        AsioServiceHolder* holder = new AsioServiceHolder();
        AsioServicePtr service = new AsioService(shared_from_this());
        holder->service = service;
        holder->eventLoop = boost::static_pointer_cast<EventLoop>(service);
        holder->work = WorkPtr(new io_service::work(service->service()));

        eventLoops.push_back(holder);
    }

    // automatic start
    if (!mainThread) {
        // Create a pool of threads to run all of the io_services.
        for (std::size_t i = 0; i < eventLoops.size(); ++i) {
            AsioServiceHolder* holder = (AsioServiceHolder*)eventLoops[i];
            holder->thread
                = ThreadPtr(new boost::thread(
                                boost::bind(&AsioServicePool::runIOservice,
                                            this,
                                            holder)));

            boost::thread::id id = holder->thread->get_id();
            holder->service->setThreadId(id);
            allEventLoops.insert(std::make_pair(id, holder->eventLoop));
        }

        started = true;
    }
    else {
        AsioServiceHolder* holder = (AsioServiceHolder*)eventLoops.front();

        boost::thread::id id = boost::this_thread::get_id();
        holder->service->setThreadId(id);
        allEventLoops.insert(std::make_pair(id, holder->eventLoop));
    }
}

bool AsioServicePool::start() {
    if (!started && mainThread) {
        LOG_INFO << "AsioServciePool running in main thread mode.";

        if (runIOservice((AsioServiceHolder*)eventLoops.front()) < 0) {
            LOG_ERROR << "AsioServicePool run the main thread service error.";
            return false;
        }
    }

    started = true;
    return true;
}

void cetty::channel::socket::asio::AsioServicePool::waitForStop() {
    if (mainThread) {
        return;
    }

    // Wait for all threads in the pool to exit.
    for (int i = 0; i < eventLoopCnt; ++i) {
        AsioServiceHolder* holder = (AsioServiceHolder*)eventLoops[i];
        holder->thread->join();
    }
}

void AsioServicePool::stop() {
    // Explicitly stop all io_services.
    for (int i = 0; i < eventLoopCnt; ++i) {
        AsioServiceHolder* holder = (AsioServiceHolder*)eventLoops[i];
        holder->stop();
    }

    started = false;
}

const AsioServicePtr& AsioServicePool::getNextService() {
    return getNextServiceHolder()->service;
}

int AsioServicePool::runIOservice(AsioServiceHolder* holder) {
    BOOST_ASSERT(holder && holder->service && "ioservice can not be NULL.");

    AsioServicePtr& service = holder->service;

    service->setThreadId(boost::this_thread::get_id());

    boost::system::error_code err;
    std::size_t opCount = service->service().run(err);

    // if error happened, try to recover.
    if (err) {
        LOG_ERROR  << "when runIOservice, the io service has error = " << err.value();
        stop();
        return -1;
    }

    LOG_INFO << "runIOservice OK, and " << opCount << "handlers that were executed.";
    return opCount;
}

const EventLoopPtr& AsioServicePool::getNextLoop() {
    return getNextServiceHolder()->eventLoop;
}

AsioServiceHolder* AsioServicePool::getNextServiceHolder() {
    // Only one service.
    if (eventLoopCnt == 1) {
        return (AsioServiceHolder*)eventLoops.front();
    }

    // Use a round-robin scheme to choose the next io_service to use.
    AsioServiceHolder* holder = (AsioServiceHolder*)eventLoops[nextServiceIndex];
    ++nextServiceIndex;

    if (nextServiceIndex == eventLoopCnt) {
        nextServiceIndex = 0;
    }

    return holder;
}

}
}
}
}
<|endoftext|>


<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/file_path.h"
#include "base/string_util.h"
#include "chrome/browser/password_manager/password_manager.h"
#include "chrome/browser/password_manager/password_store.h"
#include "chrome/browser/pref_service.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/testing_profile.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/gmock/include/gmock/gmock.h"

using webkit_glue::PasswordForm;
using testing::_;
using testing::DoAll;
using ::testing::Exactly;
using ::testing::WithArg;
using ::testing::Return;

class MockPasswordManagerDelegate : public PasswordManager::Delegate {
 public:
  MOCK_METHOD1(FillPasswordForm, void(
     const webkit_glue::PasswordFormDomManager::FillData&));
  MOCK_METHOD1(AddSavePasswordInfoBar, void(PasswordFormManager*));
  MOCK_METHOD0(GetProfileForPasswordManager, Profile*());
  MOCK_METHOD0(DidLastPageLoadEncounterSSLErrors, bool());
};

class TestingProfileWithPasswordStore : public TestingProfile {
 public:
  explicit TestingProfileWithPasswordStore(PasswordStore* store)
      : store_(store) {}
  virtual PasswordStore* GetPasswordStore(ServiceAccessType access) {
    return store_;
  }
 private:
  PasswordStore* store_;
};

class MockPasswordStore : public PasswordStore {
 public:
  MOCK_METHOD1(RemoveLogin, void(const PasswordForm&));
  MOCK_METHOD0(ReportMetricsImpl void());
  MOCK_METHOD2(GetLogins, int(const PasswordForm&, PasswordStoreConsumer*));
  MOCK_METHOD1(AddLogin, void(const PasswordForm&));
  MOCK_METHOD1(UpdateLogin, void(const PasswordForm&));
  MOCK_METHOD1(AddLoginImpl, void(const PasswordForm&));
  MOCK_METHOD1(UpdateLoginImpl, void(const PasswordForm&));
  MOCK_METHOD1(RemoveLoginImpl, void(const PasswordForm&));
  MOCK_METHOD2(RemoveLoginsCreatedBetweenImpl, void(const base::Time&,
               const base::Time&));
  MOCK_METHOD2(GetLoginsImpl, void(GetLoginsRequest*, const PasswordForm&));
  MOCK_METHOD1(GetAutofillableLoginsImpl, void(GetLoginsRequest*));
  MOCK_METHOD1(GetBlacklistLoginsImpl, void(GetLoginsRequest*));
  MOCK_METHOD1(FillAutofillableLogins,
      bool(std::vector<webkit_glue::PasswordForm*>*));
  MOCK_METHOD1(FillBlacklistLogins,
      bool(std::vector<webkit_glue::PasswordForm*>*));
};

ACTION_P2(InvokeConsumer, handle, forms) {
  arg0->OnPasswordStoreRequestDone(handle, forms);
}

ACTION_P(SaveToScopedPtr, scoped) {
  scoped->reset(arg0);
}

class PasswordManagerTest : public testing::Test {
 public:
  PasswordManagerTest() {}
 protected:

  virtual void SetUp() {
    store_ = new MockPasswordStore();
    profile_.reset(new TestingProfileWithPasswordStore(store_));
    EXPECT_CALL(delegate_, GetProfileForPasswordManager())
        .WillRepeatedly(Return(profile_.get()));
    manager_.reset(new PasswordManager(&delegate_));
    EXPECT_CALL(delegate_, DidLastPageLoadEncounterSSLErrors())
        .WillRepeatedly(Return(false));
  }

  virtual void TearDown() {
    manager_.reset();
    store_ = NULL;
  }

  PasswordForm MakeSimpleForm() {
    PasswordForm form;
    form.origin = GURL("http://www.google.com/a/LoginAuth");
    form.action = GURL("http://www.google.com/a/Login");
    form.username_element = ASCIIToUTF16("Email");
    form.password_element = ASCIIToUTF16("Passwd");
    form.username_value = ASCIIToUTF16("google");
    form.password_value = ASCIIToUTF16("password");
    form.submit_element = ASCIIToUTF16("signIn");
    form.signon_realm = "http://www.google.com";
    return form;
  }

  PasswordManager* manager() { return manager_.get(); }

  scoped_ptr<Profile> profile_;
  scoped_refptr<MockPasswordStore> store_;
  MockPasswordManagerDelegate delegate_;  // Owned by manager_.
  scoped_ptr<PasswordManager> manager_;
};

MATCHER_P(FormMatches, form, "") {
  return form.signon_realm == arg.signon_realm &&
         form.origin == arg.origin &&
         form.action == arg.action &&
         form.username_element == arg.username_element &&
         form.password_element == arg.password_element &&
         form.submit_element == arg.submit_element;
}

TEST_F(PasswordManagerTest, FormSubmitEmptyStore) {
  // Test that observing a newly submitted form shows the save password bar.
  std::vector<PasswordForm*> result;  // Empty password store.
  EXPECT_CALL(delegate_, FillPasswordForm(_)).Times(Exactly(0));
  EXPECT_CALL(*store_, GetLogins(_,_))
      .WillOnce(DoAll(WithArg<1>(InvokeConsumer(0, result)), Return(0)));
  std::vector<PasswordForm> observed;
  PasswordForm form(MakeSimpleForm());
  observed.push_back(form);
  manager()->PasswordFormsFound(observed);  // The initial load.
  manager()->PasswordFormsVisible(observed);  // The initial layout.

  // And the form submit contract is to call ProvisionallySavePassword.
  manager()->ProvisionallySavePassword(form);

  scoped_ptr<PasswordFormManager> form_to_save;
  EXPECT_CALL(delegate_, AddSavePasswordInfoBar(_))
      .WillOnce(WithArg<0>(SaveToScopedPtr(&form_to_save)));

  // Now the password manager waits for the navigation to complete.
  manager()->DidStopLoading();

  ASSERT_FALSE(NULL == form_to_save.get());
  EXPECT_CALL(*store_, AddLogin(FormMatches(form)));

  // Simulate saving the form, as if the info bar was accepted.
  form_to_save->Save();
}

TEST_F(PasswordManagerTest, FormSubmitNoGoodMatch) {
  // Same as above, except with an existing form for the same signon realm,
  // but different origin.  Detailed cases like this are covered by
  // PasswordFormManagerTest.
  std::vector<PasswordForm*> result;
  PasswordForm* existing_different = new PasswordForm(MakeSimpleForm());
  existing_different->username_value = ASCIIToUTF16("google2");
  result.push_back(existing_different);
  EXPECT_CALL(delegate_, FillPasswordForm(_));
  EXPECT_CALL(*store_, GetLogins(_,_))
      .WillOnce(DoAll(WithArg<1>(InvokeConsumer(0, result)), Return(0)));

  std::vector<PasswordForm> observed;
  PasswordForm form(MakeSimpleForm());
  observed.push_back(form);
  manager()->PasswordFormsFound(observed);  // The initial load.
  manager()->PasswordFormsVisible(observed);  // The initial layout.
  manager()->ProvisionallySavePassword(form);

  // We still expect an add, since we didn't have a good match.
  scoped_ptr<PasswordFormManager> form_to_save;
  EXPECT_CALL(delegate_, AddSavePasswordInfoBar(_))
      .WillOnce(WithArg<0>(SaveToScopedPtr(&form_to_save)));

  manager()->DidStopLoading();

  EXPECT_CALL(*store_, AddLogin(FormMatches(form)));
  // Simulate saving the form.
  form_to_save->Save();
}

TEST_F(PasswordManagerTest, FormSeenThenLeftPage) {
  std::vector<PasswordForm*> result;  // Empty password store.
  EXPECT_CALL(delegate_, FillPasswordForm(_)).Times(Exactly(0));
  EXPECT_CALL(*store_, GetLogins(_,_))
    .WillOnce(DoAll(WithArg<1>(InvokeConsumer(0, result)), Return(0)));
  std::vector<PasswordForm> observed;
  PasswordForm form(MakeSimpleForm());
  observed.push_back(form);
  manager()->PasswordFormsFound(observed);  // The initial load.
  manager()->PasswordFormsVisible(observed);  // The initial layout.

  manager()->DidNavigate();

  // No expected calls.
  manager()->DidStopLoading();
}

TEST_F(PasswordManagerTest, FormSubmitFailedLogin) {
  std::vector<PasswordForm*> result;  // Empty password store.
  EXPECT_CALL(delegate_, FillPasswordForm(_)).Times(Exactly(0));
  EXPECT_CALL(*store_, GetLogins(_,_))
    .WillRepeatedly(DoAll(WithArg<1>(InvokeConsumer(0, result)), Return(0)));
  std::vector<PasswordForm> observed;
  PasswordForm form(MakeSimpleForm());
  observed.push_back(form);
  manager()->PasswordFormsFound(observed);  // The initial load.
  manager()->PasswordFormsVisible(observed);  // The initial layout.

  manager()->ProvisionallySavePassword(form);

  // The form reappears, and is visible in the layout:
  manager()->PasswordFormsFound(observed);
  manager()->PasswordFormsVisible(observed);

  // No expected calls to the PasswordStore...
  manager()->DidStopLoading();
}

TEST_F(PasswordManagerTest, FormSubmitInvisibleLogin) {
  // Tests fix of issue 28911: if the login form reappears on the subsequent
  // page, but is invisible, it shouldn't count as a failed login.
  std::vector<PasswordForm*> result;  // Empty password store.
  EXPECT_CALL(delegate_, FillPasswordForm(_)).Times(Exactly(0));
  EXPECT_CALL(*store_, GetLogins(_,_))
      .WillRepeatedly(DoAll(WithArg<1>(InvokeConsumer(0, result)), Return(0)));
  std::vector<PasswordForm> observed;
  PasswordForm form(MakeSimpleForm());
  observed.push_back(form);
  manager()->PasswordFormsFound(observed);  // The initial load.
  manager()->PasswordFormsVisible(observed);  // The initial layout.

  manager()->ProvisionallySavePassword(form);

  // The form reappears, but is not visible in the layout:
  manager()->PasswordFormsFound(observed);
  // No call to PasswordFormsVisible.

  // Expect info bar to appear:
  scoped_ptr<PasswordFormManager> form_to_save;
  EXPECT_CALL(delegate_, AddSavePasswordInfoBar(_))
      .WillOnce(WithArg<0>(SaveToScopedPtr(&form_to_save)));

  manager()->DidStopLoading();

  ASSERT_FALSE(NULL == form_to_save.get());
  EXPECT_CALL(*store_, AddLogin(FormMatches(form)));
  // Simulate saving the form.
  form_to_save->Save();
}

TEST_F(PasswordManagerTest, InitiallyInvisibleForm) {
  // Make sure an invisible login form still gets autofilled.
  std::vector<PasswordForm*> result;
  PasswordForm* existing = new PasswordForm(MakeSimpleForm());
  result.push_back(existing);
  EXPECT_CALL(delegate_, FillPasswordForm(_));
  EXPECT_CALL(*store_, GetLogins(_,_))
      .WillRepeatedly(DoAll(WithArg<1>(InvokeConsumer(0, result)), Return(0)));
  std::vector<PasswordForm> observed;
  PasswordForm form(MakeSimpleForm());
  observed.push_back(form);
  manager()->PasswordFormsFound(observed);  // The initial load.
  // PasswordFormsVisible is not called.

  manager()->DidStopLoading();
}
<commit_msg>Unreviewed build fix - fix typo in last unreviewd build fix :(<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/file_path.h"
#include "base/string_util.h"
#include "chrome/browser/password_manager/password_manager.h"
#include "chrome/browser/password_manager/password_store.h"
#include "chrome/browser/pref_service.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/testing_profile.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/gmock/include/gmock/gmock.h"

using webkit_glue::PasswordForm;
using testing::_;
using testing::DoAll;
using ::testing::Exactly;
using ::testing::WithArg;
using ::testing::Return;

class MockPasswordManagerDelegate : public PasswordManager::Delegate {
 public:
  MOCK_METHOD1(FillPasswordForm, void(
     const webkit_glue::PasswordFormDomManager::FillData&));
  MOCK_METHOD1(AddSavePasswordInfoBar, void(PasswordFormManager*));
  MOCK_METHOD0(GetProfileForPasswordManager, Profile*());
  MOCK_METHOD0(DidLastPageLoadEncounterSSLErrors, bool());
};

class TestingProfileWithPasswordStore : public TestingProfile {
 public:
  explicit TestingProfileWithPasswordStore(PasswordStore* store)
      : store_(store) {}
  virtual PasswordStore* GetPasswordStore(ServiceAccessType access) {
    return store_;
  }
 private:
  PasswordStore* store_;
};

class MockPasswordStore : public PasswordStore {
 public:
  MOCK_METHOD1(RemoveLogin, void(const PasswordForm&));
  MOCK_METHOD0(ReportMetricsImpl, void());
  MOCK_METHOD2(GetLogins, int(const PasswordForm&, PasswordStoreConsumer*));
  MOCK_METHOD1(AddLogin, void(const PasswordForm&));
  MOCK_METHOD1(UpdateLogin, void(const PasswordForm&));
  MOCK_METHOD1(AddLoginImpl, void(const PasswordForm&));
  MOCK_METHOD1(UpdateLoginImpl, void(const PasswordForm&));
  MOCK_METHOD1(RemoveLoginImpl, void(const PasswordForm&));
  MOCK_METHOD2(RemoveLoginsCreatedBetweenImpl, void(const base::Time&,
               const base::Time&));
  MOCK_METHOD2(GetLoginsImpl, void(GetLoginsRequest*, const PasswordForm&));
  MOCK_METHOD1(GetAutofillableLoginsImpl, void(GetLoginsRequest*));
  MOCK_METHOD1(GetBlacklistLoginsImpl, void(GetLoginsRequest*));
  MOCK_METHOD1(FillAutofillableLogins,
      bool(std::vector<webkit_glue::PasswordForm*>*));
  MOCK_METHOD1(FillBlacklistLogins,
      bool(std::vector<webkit_glue::PasswordForm*>*));
};

ACTION_P2(InvokeConsumer, handle, forms) {
  arg0->OnPasswordStoreRequestDone(handle, forms);
}

ACTION_P(SaveToScopedPtr, scoped) {
  scoped->reset(arg0);
}

class PasswordManagerTest : public testing::Test {
 public:
  PasswordManagerTest() {}
 protected:

  virtual void SetUp() {
    store_ = new MockPasswordStore();
    profile_.reset(new TestingProfileWithPasswordStore(store_));
    EXPECT_CALL(delegate_, GetProfileForPasswordManager())
        .WillRepeatedly(Return(profile_.get()));
    manager_.reset(new PasswordManager(&delegate_));
    EXPECT_CALL(delegate_, DidLastPageLoadEncounterSSLErrors())
        .WillRepeatedly(Return(false));
  }

  virtual void TearDown() {
    manager_.reset();
    store_ = NULL;
  }

  PasswordForm MakeSimpleForm() {
    PasswordForm form;
    form.origin = GURL("http://www.google.com/a/LoginAuth");
    form.action = GURL("http://www.google.com/a/Login");
    form.username_element = ASCIIToUTF16("Email");
    form.password_element = ASCIIToUTF16("Passwd");
    form.username_value = ASCIIToUTF16("google");
    form.password_value = ASCIIToUTF16("password");
    form.submit_element = ASCIIToUTF16("signIn");
    form.signon_realm = "http://www.google.com";
    return form;
  }

  PasswordManager* manager() { return manager_.get(); }

  scoped_ptr<Profile> profile_;
  scoped_refptr<MockPasswordStore> store_;
  MockPasswordManagerDelegate delegate_;  // Owned by manager_.
  scoped_ptr<PasswordManager> manager_;
};

MATCHER_P(FormMatches, form, "") {
  return form.signon_realm == arg.signon_realm &&
         form.origin == arg.origin &&
         form.action == arg.action &&
         form.username_element == arg.username_element &&
         form.password_element == arg.password_element &&
         form.submit_element == arg.submit_element;
}

TEST_F(PasswordManagerTest, FormSubmitEmptyStore) {
  // Test that observing a newly submitted form shows the save password bar.
  std::vector<PasswordForm*> result;  // Empty password store.
  EXPECT_CALL(delegate_, FillPasswordForm(_)).Times(Exactly(0));
  EXPECT_CALL(*store_, GetLogins(_,_))
      .WillOnce(DoAll(WithArg<1>(InvokeConsumer(0, result)), Return(0)));
  std::vector<PasswordForm> observed;
  PasswordForm form(MakeSimpleForm());
  observed.push_back(form);
  manager()->PasswordFormsFound(observed);  // The initial load.
  manager()->PasswordFormsVisible(observed);  // The initial layout.

  // And the form submit contract is to call ProvisionallySavePassword.
  manager()->ProvisionallySavePassword(form);

  scoped_ptr<PasswordFormManager> form_to_save;
  EXPECT_CALL(delegate_, AddSavePasswordInfoBar(_))
      .WillOnce(WithArg<0>(SaveToScopedPtr(&form_to_save)));

  // Now the password manager waits for the navigation to complete.
  manager()->DidStopLoading();

  ASSERT_FALSE(NULL == form_to_save.get());
  EXPECT_CALL(*store_, AddLogin(FormMatches(form)));

  // Simulate saving the form, as if the info bar was accepted.
  form_to_save->Save();
}

TEST_F(PasswordManagerTest, FormSubmitNoGoodMatch) {
  // Same as above, except with an existing form for the same signon realm,
  // but different origin.  Detailed cases like this are covered by
  // PasswordFormManagerTest.
  std::vector<PasswordForm*> result;
  PasswordForm* existing_different = new PasswordForm(MakeSimpleForm());
  existing_different->username_value = ASCIIToUTF16("google2");
  result.push_back(existing_different);
  EXPECT_CALL(delegate_, FillPasswordForm(_));
  EXPECT_CALL(*store_, GetLogins(_,_))
      .WillOnce(DoAll(WithArg<1>(InvokeConsumer(0, result)), Return(0)));

  std::vector<PasswordForm> observed;
  PasswordForm form(MakeSimpleForm());
  observed.push_back(form);
  manager()->PasswordFormsFound(observed);  // The initial load.
  manager()->PasswordFormsVisible(observed);  // The initial layout.
  manager()->ProvisionallySavePassword(form);

  // We still expect an add, since we didn't have a good match.
  scoped_ptr<PasswordFormManager> form_to_save;
  EXPECT_CALL(delegate_, AddSavePasswordInfoBar(_))
      .WillOnce(WithArg<0>(SaveToScopedPtr(&form_to_save)));

  manager()->DidStopLoading();

  EXPECT_CALL(*store_, AddLogin(FormMatches(form)));
  // Simulate saving the form.
  form_to_save->Save();
}

TEST_F(PasswordManagerTest, FormSeenThenLeftPage) {
  std::vector<PasswordForm*> result;  // Empty password store.
  EXPECT_CALL(delegate_, FillPasswordForm(_)).Times(Exactly(0));
  EXPECT_CALL(*store_, GetLogins(_,_))
    .WillOnce(DoAll(WithArg<1>(InvokeConsumer(0, result)), Return(0)));
  std::vector<PasswordForm> observed;
  PasswordForm form(MakeSimpleForm());
  observed.push_back(form);
  manager()->PasswordFormsFound(observed);  // The initial load.
  manager()->PasswordFormsVisible(observed);  // The initial layout.

  manager()->DidNavigate();

  // No expected calls.
  manager()->DidStopLoading();
}

TEST_F(PasswordManagerTest, FormSubmitFailedLogin) {
  std::vector<PasswordForm*> result;  // Empty password store.
  EXPECT_CALL(delegate_, FillPasswordForm(_)).Times(Exactly(0));
  EXPECT_CALL(*store_, GetLogins(_,_))
    .WillRepeatedly(DoAll(WithArg<1>(InvokeConsumer(0, result)), Return(0)));
  std::vector<PasswordForm> observed;
  PasswordForm form(MakeSimpleForm());
  observed.push_back(form);
  manager()->PasswordFormsFound(observed);  // The initial load.
  manager()->PasswordFormsVisible(observed);  // The initial layout.

  manager()->ProvisionallySavePassword(form);

  // The form reappears, and is visible in the layout:
  manager()->PasswordFormsFound(observed);
  manager()->PasswordFormsVisible(observed);

  // No expected calls to the PasswordStore...
  manager()->DidStopLoading();
}

TEST_F(PasswordManagerTest, FormSubmitInvisibleLogin) {
  // Tests fix of issue 28911: if the login form reappears on the subsequent
  // page, but is invisible, it shouldn't count as a failed login.
  std::vector<PasswordForm*> result;  // Empty password store.
  EXPECT_CALL(delegate_, FillPasswordForm(_)).Times(Exactly(0));
  EXPECT_CALL(*store_, GetLogins(_,_))
      .WillRepeatedly(DoAll(WithArg<1>(InvokeConsumer(0, result)), Return(0)));
  std::vector<PasswordForm> observed;
  PasswordForm form(MakeSimpleForm());
  observed.push_back(form);
  manager()->PasswordFormsFound(observed);  // The initial load.
  manager()->PasswordFormsVisible(observed);  // The initial layout.

  manager()->ProvisionallySavePassword(form);

  // The form reappears, but is not visible in the layout:
  manager()->PasswordFormsFound(observed);
  // No call to PasswordFormsVisible.

  // Expect info bar to appear:
  scoped_ptr<PasswordFormManager> form_to_save;
  EXPECT_CALL(delegate_, AddSavePasswordInfoBar(_))
      .WillOnce(WithArg<0>(SaveToScopedPtr(&form_to_save)));

  manager()->DidStopLoading();

  ASSERT_FALSE(NULL == form_to_save.get());
  EXPECT_CALL(*store_, AddLogin(FormMatches(form)));
  // Simulate saving the form.
  form_to_save->Save();
}

TEST_F(PasswordManagerTest, InitiallyInvisibleForm) {
  // Make sure an invisible login form still gets autofilled.
  std::vector<PasswordForm*> result;
  PasswordForm* existing = new PasswordForm(MakeSimpleForm());
  result.push_back(existing);
  EXPECT_CALL(delegate_, FillPasswordForm(_));
  EXPECT_CALL(*store_, GetLogins(_,_))
      .WillRepeatedly(DoAll(WithArg<1>(InvokeConsumer(0, result)), Return(0)));
  std::vector<PasswordForm> observed;
  PasswordForm form(MakeSimpleForm());
  observed.push_back(form);
  manager()->PasswordFormsFound(observed);  // The initial load.
  // PasswordFormsVisible is not called.

  manager()->DidStopLoading();
}
<|endoftext|>


<commit_before>/***************************************************************************
 *  containers/test_block_scheduler.cpp
 *
 *  Part of the STXXL. See http://stxxl.sourceforge.net
 *
 *  Copyright (C) 2010-2011 Raoul Steffen <R-Steffen@gmx.de>
 *
 *  Distributed under the Boost Software License, Version 1.0.
 *  (See accompanying file LICENSE_1_0.txt or copy at
 *  http://www.boost.org/LICENSE_1_0.txt)
 **************************************************************************/

#include <stxxl/bits/mng/block_scheduler.h>

// Thanks Daniel Russel, Stanford University
#include <Argument_helper.h>

#include <iostream>
#include <limits>

using namespace stxxl;

template <class IBT>
void set_pattern_A(IBT & ib)
{
    for (int_type i = 0; i < ib.size; ++i)
        ib[i] = i;
}

template <class IBT>
int_type test_pattern_A(IBT & ib)
{
    int_type num_err = 0;
    for (int_type i = 0; i < ib.size; ++i)
        num_err += (ib[i] != i);
    return num_err;
}

template <class IBT>
void set_pattern_B(IBT & ib)
{
    for (int_type i = 0; i < ib.size; ++i)
        ib[i] = ib.size - i;
}

template <class IBT>
int_type test_pattern_B(IBT & ib)
{
    int_type num_err = 0;
    for (int_type i = 0; i < ib.size; ++i)
        num_err += (ib[i] != ib.size - i);
    return num_err;
}

int main(int argc, char **argv)
{
    const int block_size = 1024;
    typedef int_type value_type;

    int test_case = -1;
    int_type internal_memory = 256 * 1024 * 1024;

    dsr::Argument_helper ah;
    ah.new_named_int('t', "test-case", "I", "number of the test case to run", test_case);
    ah.new_named_int('m', "memory", "N", "internal memory to use (in bytes)", internal_memory);
    ah.set_description("stxxl block_scheduler test");
    ah.set_author("Raoul Steffen, R-Steffen@gmx.de");
    ah.process(argc, argv);

    typedef block_scheduler< swappable_block<value_type, block_size> > bst;
    typedef bst::swappable_block_identifier_type sbit;
    typedef bst::internal_block_type ibt;
    typedef bst::external_block_type ebt;

    switch (test_case)
    {
    case -1:
    case 0:
        {   // ------------------- call all functions -----------------------
            STXXL_MSG("next test: call all functions");
            ebt ext_bl; // prepare an external_block with pattern A
            block_manager::get_instance()->new_block(striping(), ext_bl);
            ibt * int_bl = new ibt;
            set_pattern_A(*int_bl);
            int_bl->write(ext_bl)->wait();

            bst * b_s = new bst(internal_memory); // the block_scheduler may use internal_memory byte for caching
            bst & bs = *b_s;
            assert(! bs.is_simulating()); // make sure is not just recording a prediction sequence

            sbit sbi1 = bs.allocate_swappable_block(); // allocate a swappable_block and store its identifier
            if (bs.is_initialized(sbi1)) // it should not be initialized
                    STXXL_ERRMSG("new block is initialized");
            bs.initialize(sbi1, ext_bl); // initialize the swappable_block with the prepared external_block
            {
                ibt & ib = bs.acquire(sbi1); // acquire the swappable_block to gain access
                int_type num_err = 0;
                for (int_type i = 0; i < block_size; ++i)
                    num_err += (ib[i] != i); // read from the swappable_block. it should contain pattern A
                if (num_err)
                    STXXL_ERRMSG("previously initialized block had " << num_err << " errors.");
            }
            {
                ibt & ib = bs.get_internal_block(sbi1); // get a new reference to the already allocated block (because we forgot the old one)
                for (int_type i = 0; i < block_size; ++i)
                    ib[i] = block_size - i; // write pattern B
                bs.release(sbi1, true); // release the swappable_block. changes have to be stored. it may now be swapped out.
            }
            sbit sbi2 = bs.allocate_swappable_block(); // allocate a second swappable_block and store its identifier
            if (bs.is_initialized(sbi2)) // it should not be initialized
                STXXL_ERRMSG("new block is initialized");
            {
                ibt & ib1 = bs.acquire(sbi1); // acquire the swappable_block to gain access
                ibt & ib2 = bs.acquire(sbi2); // acquire the swappable_block to gain access because it was uninitialized, it now becomes initialized
                for (int_type i = 0; i < block_size; ++i)
                    ib2[i] = ib1[i]; // copy pattern B
                bs.release(sbi1, false); // release the swappable_block. no changes happened.
                bs.release(sbi2, true);
            }
            if (! bs.is_initialized(sbi1)) // both blocks should now be initialized
                    STXXL_ERRMSG("block is not initialized");
            if (! bs.is_initialized(sbi2)) // both blocks should now be initialized
                        STXXL_ERRMSG("block is not initialized");
            ext_bl = bs.extract_external_block(sbi2); // get the external_block
            if (bs.is_initialized(sbi2)) // should not be initialized any more
                STXXL_ERRMSG("block is initialized after extraction");
            bs.deinitialize(sbi1);
            if (bs.is_initialized(sbi1)) // should not be initialized any more
                STXXL_ERRMSG("block is initialized after deinitialize");
            bs.free_swappable_block(sbi1); // free the swappable_blocks
            bs.free_swappable_block(sbi2);
            bs.explicit_timestep();
            delete b_s;

            int_bl->read(ext_bl)->wait();
            int_type num_err = test_pattern_B(*int_bl); // check the block. it should contain pattern B.
            if (num_err)
                STXXL_ERRMSG("after extraction changed block had " << num_err << " errors.");
            delete int_bl;
        }
        {   // ---------- force swapping ---------------------
            STXXL_MSG("next test: force swapping");
            const int_type num_sb = 5;

            bst * b_s = new bst(block_size * sizeof(value_type) * 3); // only 3 internal_blocks allowed
            sbit sbi[num_sb];
            for (int_type i = 0; i < num_sb; ++i)
                sbi[i] = b_s->allocate_swappable_block();
            ibt * ib[num_sb];
            ib[0] = &b_s->acquire(sbi[0]); // fill 3 blocks
            ib[1] = &b_s->acquire(sbi[1]);
            ib[2] = &b_s->acquire(sbi[2]);
            set_pattern_A(*ib[0]);
            set_pattern_A(*ib[1]);
            set_pattern_A(*ib[2]);
            b_s->release(sbi[0], true);
            b_s->release(sbi[1], true);
            b_s->release(sbi[2], true);

            ib[3] = &b_s->acquire(sbi[3]); // fill 2 blocks, now some others have to be swapped out
            ib[4] = &b_s->acquire(sbi[4]);
            set_pattern_A(*ib[3]);
            set_pattern_A(*ib[4]);
            b_s->release(sbi[3], true);
            b_s->release(sbi[4], true);

            ib[2] = &b_s->acquire(sbi[2]); // this block can still be cached
            ib[3] = &b_s->acquire(sbi[3]); // as can this
            ib[1] = &b_s->acquire(sbi[1]); // but not this
            if (test_pattern_A(*ib[1]))
                STXXL_ERRMSG("Block 1 had errors.");
            if (test_pattern_A(*ib[2]))
                STXXL_ERRMSG("Block 2 had errors.");
            if (test_pattern_A(*ib[3]))
                STXXL_ERRMSG("Block 3 had errors.");
            b_s->release(sbi[1], false);
            b_s->release(sbi[2], false);
            b_s->release(sbi[3], false);
            for (int_type i = 0; i < num_sb; ++i)
                b_s->free_swappable_block(sbi[i]);
            delete b_s;
        }
        break;
    case 1:
        {   // ---------- do not free uninitialized block ---------------------
            STXXL_MSG("next test: do not free uninitialized block");

            bst * b_s = new bst(block_size * sizeof(value_type));
            sbit sbi;

            sbi = b_s->allocate_swappable_block();
            b_s->acquire(sbi);
            b_s->release(sbi, false);
            // do not free uninitialized block

            delete b_s;
        }
        break;
    case 2:
        {   // ---------- do not free initialized block ---------------------
            STXXL_MSG("next test: do not free initialized block");

            bst * b_s = new bst(block_size * sizeof(value_type));
            sbit sbi;

            sbi = b_s->allocate_swappable_block();
            b_s->acquire(sbi);
            b_s->release(sbi, true);
            // do not free initialized block

            delete b_s;
        }
        break;
    case 3:
        {   // ---------- do not release but free block ---------------------
            STXXL_MSG("next test: do not release but free block");

            bst * b_s = new bst(block_size * sizeof(value_type));
            sbit sbi;

            sbi = b_s->allocate_swappable_block();
            b_s->acquire(sbi);
            // do not release block
            b_s->free_swappable_block(sbi);

            delete b_s;
        }
        break;
    case 4:
        {   // ---------- do neither release nor free block ---------------------
            STXXL_MSG("next test: do neither release nor free block");

            bst * b_s = new bst(block_size * sizeof(value_type));
            sbit sbi;

            sbi = b_s->allocate_swappable_block();
            b_s->acquire(sbi);
            // do not release block
            // do not free block

            delete b_s;
        }
        break;
    case 5:
        {   // ---------- release block to often ---------------------
            STXXL_MSG("next test: release block to often");

            bst * b_s = new bst(block_size * sizeof(value_type));
            sbit sbi;

            sbi = b_s->allocate_swappable_block();
            b_s->acquire(sbi);
            b_s->release(sbi, false);
            b_s->release(sbi, false); // release once to often

            delete b_s;
        }
        break;
    }
    STXXL_MSG("end of test");
    return 0;
}

<commit_msg>Give internal memory in megabytes.<commit_after>/***************************************************************************
 *  containers/test_block_scheduler.cpp
 *
 *  Part of the STXXL. See http://stxxl.sourceforge.net
 *
 *  Copyright (C) 2010-2011 Raoul Steffen <R-Steffen@gmx.de>
 *
 *  Distributed under the Boost Software License, Version 1.0.
 *  (See accompanying file LICENSE_1_0.txt or copy at
 *  http://www.boost.org/LICENSE_1_0.txt)
 **************************************************************************/

#include <stxxl/bits/mng/block_scheduler.h>

// Thanks Daniel Russel, Stanford University
#include <Argument_helper.h>

#include <iostream>
#include <limits>

using namespace stxxl;

template <class IBT>
void set_pattern_A(IBT & ib)
{
    for (int_type i = 0; i < ib.size; ++i)
        ib[i] = i;
}

template <class IBT>
int_type test_pattern_A(IBT & ib)
{
    int_type num_err = 0;
    for (int_type i = 0; i < ib.size; ++i)
        num_err += (ib[i] != i);
    return num_err;
}

template <class IBT>
void set_pattern_B(IBT & ib)
{
    for (int_type i = 0; i < ib.size; ++i)
        ib[i] = ib.size - i;
}

template <class IBT>
int_type test_pattern_B(IBT & ib)
{
    int_type num_err = 0;
    for (int_type i = 0; i < ib.size; ++i)
        num_err += (ib[i] != ib.size - i);
    return num_err;
}

int main(int argc, char **argv)
{
    const int block_size = 1024;
    typedef int_type value_type;

    int test_case = -1;
    int internal_memory_megabytes = 256;

    dsr::Argument_helper ah;
    ah.new_named_int('t', "test-case", "I", "number of the test case to run", test_case);
    ah.new_named_int('m', "memory", "N", "internal memory to use (in megabytes)", internal_memory_megabytes);
    ah.set_description("stxxl block_scheduler test");
    ah.set_author("Raoul Steffen, R-Steffen@gmx.de");
    ah.process(argc, argv);

    int_type internal_memory = int_type(internal_memory_megabytes) * 1024 * 1024;

    typedef block_scheduler< swappable_block<value_type, block_size> > bst;
    typedef bst::swappable_block_identifier_type sbit;
    typedef bst::internal_block_type ibt;
    typedef bst::external_block_type ebt;

    switch (test_case)
    {
    case -1:
    case 0:
        {   // ------------------- call all functions -----------------------
            STXXL_MSG("next test: call all functions");
            ebt ext_bl; // prepare an external_block with pattern A
            block_manager::get_instance()->new_block(striping(), ext_bl);
            ibt * int_bl = new ibt;
            set_pattern_A(*int_bl);
            int_bl->write(ext_bl)->wait();

            bst * b_s = new bst(internal_memory); // the block_scheduler may use internal_memory byte for caching
            bst & bs = *b_s;
            assert(! bs.is_simulating()); // make sure is not just recording a prediction sequence

            sbit sbi1 = bs.allocate_swappable_block(); // allocate a swappable_block and store its identifier
            if (bs.is_initialized(sbi1)) // it should not be initialized
                    STXXL_ERRMSG("new block is initialized");
            bs.initialize(sbi1, ext_bl); // initialize the swappable_block with the prepared external_block
            {
                ibt & ib = bs.acquire(sbi1); // acquire the swappable_block to gain access
                int_type num_err = 0;
                for (int_type i = 0; i < block_size; ++i)
                    num_err += (ib[i] != i); // read from the swappable_block. it should contain pattern A
                if (num_err)
                    STXXL_ERRMSG("previously initialized block had " << num_err << " errors.");
            }
            {
                ibt & ib = bs.get_internal_block(sbi1); // get a new reference to the already allocated block (because we forgot the old one)
                for (int_type i = 0; i < block_size; ++i)
                    ib[i] = block_size - i; // write pattern B
                bs.release(sbi1, true); // release the swappable_block. changes have to be stored. it may now be swapped out.
            }
            sbit sbi2 = bs.allocate_swappable_block(); // allocate a second swappable_block and store its identifier
            if (bs.is_initialized(sbi2)) // it should not be initialized
                STXXL_ERRMSG("new block is initialized");
            {
                ibt & ib1 = bs.acquire(sbi1); // acquire the swappable_block to gain access
                ibt & ib2 = bs.acquire(sbi2); // acquire the swappable_block to gain access because it was uninitialized, it now becomes initialized
                for (int_type i = 0; i < block_size; ++i)
                    ib2[i] = ib1[i]; // copy pattern B
                bs.release(sbi1, false); // release the swappable_block. no changes happened.
                bs.release(sbi2, true);
            }
            if (! bs.is_initialized(sbi1)) // both blocks should now be initialized
                    STXXL_ERRMSG("block is not initialized");
            if (! bs.is_initialized(sbi2)) // both blocks should now be initialized
                        STXXL_ERRMSG("block is not initialized");
            ext_bl = bs.extract_external_block(sbi2); // get the external_block
            if (bs.is_initialized(sbi2)) // should not be initialized any more
                STXXL_ERRMSG("block is initialized after extraction");
            bs.deinitialize(sbi1);
            if (bs.is_initialized(sbi1)) // should not be initialized any more
                STXXL_ERRMSG("block is initialized after deinitialize");
            bs.free_swappable_block(sbi1); // free the swappable_blocks
            bs.free_swappable_block(sbi2);
            bs.explicit_timestep();
            delete b_s;

            int_bl->read(ext_bl)->wait();
            int_type num_err = test_pattern_B(*int_bl); // check the block. it should contain pattern B.
            if (num_err)
                STXXL_ERRMSG("after extraction changed block had " << num_err << " errors.");
            delete int_bl;
        }
        {   // ---------- force swapping ---------------------
            STXXL_MSG("next test: force swapping");
            const int_type num_sb = 5;

            bst * b_s = new bst(block_size * sizeof(value_type) * 3); // only 3 internal_blocks allowed
            sbit sbi[num_sb];
            for (int_type i = 0; i < num_sb; ++i)
                sbi[i] = b_s->allocate_swappable_block();
            ibt * ib[num_sb];
            ib[0] = &b_s->acquire(sbi[0]); // fill 3 blocks
            ib[1] = &b_s->acquire(sbi[1]);
            ib[2] = &b_s->acquire(sbi[2]);
            set_pattern_A(*ib[0]);
            set_pattern_A(*ib[1]);
            set_pattern_A(*ib[2]);
            b_s->release(sbi[0], true);
            b_s->release(sbi[1], true);
            b_s->release(sbi[2], true);

            ib[3] = &b_s->acquire(sbi[3]); // fill 2 blocks, now some others have to be swapped out
            ib[4] = &b_s->acquire(sbi[4]);
            set_pattern_A(*ib[3]);
            set_pattern_A(*ib[4]);
            b_s->release(sbi[3], true);
            b_s->release(sbi[4], true);

            ib[2] = &b_s->acquire(sbi[2]); // this block can still be cached
            ib[3] = &b_s->acquire(sbi[3]); // as can this
            ib[1] = &b_s->acquire(sbi[1]); // but not this
            if (test_pattern_A(*ib[1]))
                STXXL_ERRMSG("Block 1 had errors.");
            if (test_pattern_A(*ib[2]))
                STXXL_ERRMSG("Block 2 had errors.");
            if (test_pattern_A(*ib[3]))
                STXXL_ERRMSG("Block 3 had errors.");
            b_s->release(sbi[1], false);
            b_s->release(sbi[2], false);
            b_s->release(sbi[3], false);
            for (int_type i = 0; i < num_sb; ++i)
                b_s->free_swappable_block(sbi[i]);
            delete b_s;
        }
        break;
    case 1:
        {   // ---------- do not free uninitialized block ---------------------
            STXXL_MSG("next test: do not free uninitialized block");

            bst * b_s = new bst(block_size * sizeof(value_type));
            sbit sbi;

            sbi = b_s->allocate_swappable_block();
            b_s->acquire(sbi);
            b_s->release(sbi, false);
            // do not free uninitialized block

            delete b_s;
        }
        break;
    case 2:
        {   // ---------- do not free initialized block ---------------------
            STXXL_MSG("next test: do not free initialized block");

            bst * b_s = new bst(block_size * sizeof(value_type));
            sbit sbi;

            sbi = b_s->allocate_swappable_block();
            b_s->acquire(sbi);
            b_s->release(sbi, true);
            // do not free initialized block

            delete b_s;
        }
        break;
    case 3:
        {   // ---------- do not release but free block ---------------------
            STXXL_MSG("next test: do not release but free block");

            bst * b_s = new bst(block_size * sizeof(value_type));
            sbit sbi;

            sbi = b_s->allocate_swappable_block();
            b_s->acquire(sbi);
            // do not release block
            b_s->free_swappable_block(sbi);

            delete b_s;
        }
        break;
    case 4:
        {   // ---------- do neither release nor free block ---------------------
            STXXL_MSG("next test: do neither release nor free block");

            bst * b_s = new bst(block_size * sizeof(value_type));
            sbit sbi;

            sbi = b_s->allocate_swappable_block();
            b_s->acquire(sbi);
            // do not release block
            // do not free block

            delete b_s;
        }
        break;
    case 5:
        {   // ---------- release block to often ---------------------
            STXXL_MSG("next test: release block to often");

            bst * b_s = new bst(block_size * sizeof(value_type));
            sbit sbi;

            sbi = b_s->allocate_swappable_block();
            b_s->acquire(sbi);
            b_s->release(sbi, false);
            b_s->release(sbi, false); // release once to often

            delete b_s;
        }
        break;
    }
    STXXL_MSG("end of test");
    return 0;
}

<|endoftext|>


<commit_before>/*!
@file

@copyright Edouard Alligand and Joel Falcou 2015-2017
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
#ifndef BOOST_BRIGAND_SEQUENCES_MAP_HPP
#define BOOST_BRIGAND_SEQUENCES_MAP_HPP
#include <brigand/sequences/append.hpp>
#include <brigand/sequences/list.hpp>
#include <brigand/sequences/pair.hpp>
#include <brigand/types/no_such_type.hpp>
#include <brigand/types/type.hpp>
#include <type_traits>

namespace brigand
{

namespace lazy
{
    template <typename M, typename K>
    struct lookup_at
    {
        using target_t = type_<K>;
        using type = decltype(M::at(target_t{}));
    };

    template <typename M, typename K>
    struct lookup : lookup_at<M, K>::type
    {
    };
}

template <typename M, typename K>
using lookup = typename lazy::lookup<M, K>::type;

namespace detail
{
    template <class... T>
    struct map_impl;

    template <>
    struct map_impl<>
    {
        template <typename U>
        static type_<no_such_type_> at(U);

        template <class K>
        static brigand::false_type has_key(type_<K>);

        template <class K>
        static map_impl erase(type_<K>);

        template <class P>
        static map_impl<P> insert(type_<P>);
    };

    template <class... Ts>
    struct map_impl
    {
    private:
        struct Pack : pair<typename Ts::first_type, Ts>...
        {
        };

        template <class K, class P>
        static type_<typename P::second_type> at_impl(pair<K, P> *);

    public:
        template <class K>
        static decltype(at_impl<K>(static_cast<Pack *>(nullptr))) at(type_<K>);

        template <class K>
        static type_<no_such_type_> at(K);

        template <class K, class = decltype(at_impl<K>(static_cast<Pack *>(nullptr)))>
        static brigand::true_type has_key(type_<K>);

        template <class K>
        static brigand::false_type has_key(K);

        template <class K, class X>
        using erase_t = typename std::conditional<std::is_same<K, typename X::first_type>::value,
                                                  list<>, list<X>>::type;

        template <class K, typename... Xs>
        struct erase_return_t
        {
            using type = append<map_impl<>, erase_t<K, Xs>...>;
        };

        template <class K>
        static typename erase_return_t<K, Ts...>::type erase(type_<K>);

        template <class P, class = decltype(static_cast<pair<typename P::first_type, P> *>(
                               static_cast<Pack *>(nullptr)))>
        static map_impl insert(type_<P>);

        template <class P>
        static map_impl<Ts..., typename P::type> insert(P);
    };

    // if you have a "class already a base" error message, it means you have defined a map with the
    // same key present more
    // than once, which is an error
    template <class... Ts>
    struct make_map : type_<typename Ts::first_type>...
    {
        using type = map_impl<Ts...>;
    };
}
template <class... Ts>
using map = typename detail::make_map<Ts...>::type;
}
#endif
<commit_msg>Delete map.hpp<commit_after><|endoftext|>


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

#include "wfa/virtual_people/common/field_filter/field_filter.h"

#include "absl/status/status.h"
#include "gmock/gmock.h"
#include "google/protobuf/text_format.h"
#include "gtest/gtest.h"
#include "src/main/cc/wfa/virtual_people/common/field_filter/test/test.pb.h"
#include "src/test/cc/testutil/matchers.h"
#include "src/test/cc/testutil/status_macros.h"

namespace wfa_virtual_people {
namespace {

using ::wfa::StatusIs;
using ::wfa_virtual_people::test::TestProto;

TEST(FieldFilterTest, FromMessageFloatNotSupported) {
  TestProto filter_message;
  ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"PROTO(
      a {
        b {
          float_value: 1.0
        }
      }
  )PROTO", &filter_message));
  EXPECT_THAT(
      FieldFilter::New(filter_message).status(),
      StatusIs(absl::StatusCode::kInvalidArgument, ""));
}

TEST(FieldFilterTest, FromMessageDoubleNotSupported) {
  TestProto filter_message;
  ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"PROTO(
      a {
        b {
          double_value: 1.0
        }
      }
  )PROTO", &filter_message));
  EXPECT_THAT(
      FieldFilter::New(filter_message).status(),
      StatusIs(absl::StatusCode::kInvalidArgument, ""));
}

TEST(FieldFilterTest, FromMessageRepeatedNotSupported) {
  TestProto filter_message;
  ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"PROTO(
      int32_values: 1
  )PROTO", &filter_message));
  EXPECT_THAT(
      FieldFilter::New(filter_message).status(),
      StatusIs(absl::StatusCode::kInvalidArgument, ""));
}

TEST(FieldFilterTest, FromMessageSuccessful) {
  TestProto filter_message, test_proto_1, test_proto_2;
  ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"PROTO(
      a {
        b {
          int32_value: 1
          int64_value: 1
          uint32_value: 1
          uint64_value: 1
          bool_value: true
          enum_value: TEST_ENUM_1
          string_value: "string1"
        }
      }
  )PROTO", &filter_message));
  ASSERT_OK_AND_ASSIGN(
      std::unique_ptr<FieldFilter> filter, FieldFilter::New(filter_message));

  ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"PROTO(
      a {
        b {
          int32_value: 1
          int64_value: 1
          uint32_value: 1
          uint64_value: 1
          float_value: 1.0
          double_value: 1.0
          bool_value: true
          enum_value: TEST_ENUM_1
          string_value: "string1"
        }
      }
  )PROTO", &test_proto_1));
  EXPECT_TRUE(filter->IsMatch(test_proto_1));

  ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"PROTO(
      a {
        b {
          int32_value: 2
          int64_value: 1
          uint32_value: 1
          uint64_value: 1
          float_value: 1.0
          double_value: 1.0
          bool_value: true
          enum_value: TEST_ENUM_1
          string_value: "string1"
        }
      }
  )PROTO", &test_proto_2));
  EXPECT_FALSE(filter->IsMatch(test_proto_2));
}

}  // namespace
}  // namespace wfa_virtual_people
<commit_msg>Tests improvements.<commit_after>// Copyright 2021 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "wfa/virtual_people/common/field_filter/field_filter.h"

#include "absl/status/status.h"
#include "gmock/gmock.h"
#include "google/protobuf/text_format.h"
#include "gtest/gtest.h"
#include "src/main/cc/wfa/virtual_people/common/field_filter/test/test.pb.h"
#include "src/test/cc/testutil/matchers.h"
#include "src/test/cc/testutil/status_macros.h"

namespace wfa_virtual_people {
namespace {

using ::wfa::StatusIs;
using ::wfa_virtual_people::test::TestProto;

TEST(FieldFilterTest, FromMessageFloatNotSupported) {
  TestProto filter_message;
  ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"PROTO(
      a {
        b {
          float_value: 1.0
        }
      }
  )PROTO", &filter_message));
  EXPECT_THAT(
      FieldFilter::New(filter_message).status(),
      StatusIs(absl::StatusCode::kInvalidArgument, ""));
}

TEST(FieldFilterTest, FromMessageDoubleNotSupported) {
  TestProto filter_message;
  ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"PROTO(
      a {
        b {
          double_value: 1.0
        }
      }
  )PROTO", &filter_message));
  EXPECT_THAT(
      FieldFilter::New(filter_message).status(),
      StatusIs(absl::StatusCode::kInvalidArgument, ""));
}

TEST(FieldFilterTest, FromMessageRepeatedNotSupported) {
  TestProto filter_message;
  ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"PROTO(
      int32_values: 1
  )PROTO", &filter_message));
  EXPECT_THAT(
      FieldFilter::New(filter_message).status(),
      StatusIs(absl::StatusCode::kInvalidArgument, ""));
}

TEST(FieldFilterTest, FromMessageSuccessful) {
  TestProto filter_message, test_proto_1, test_proto_2;
  ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"PROTO(
      a {
        b {
          int32_value: 1
          int64_value: 1
          uint32_value: 1
          uint64_value: 1
          bool_value: true
          enum_value: TEST_ENUM_1
          string_value: "string1"
        }
      }
  )PROTO", &filter_message));
  ASSERT_OK_AND_ASSIGN(
      std::unique_ptr<FieldFilter> filter, FieldFilter::New(filter_message));

  ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"PROTO(
      a {
        b {
          int32_value: 1
          int64_value: 1
          uint32_value: 1
          uint64_value: 1
          float_value: 1.0
          double_value: 1.0
          bool_value: true
          enum_value: TEST_ENUM_1
          string_value: "string1"
        }
      }
      int32_values: 1
      int32_values: 2
  )PROTO", &test_proto_1));
  EXPECT_TRUE(filter->IsMatch(test_proto_1));

  // a.b.int32_value does not match.
  ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"PROTO(
      a {
        b {
          int32_value: 2
          int64_value: 1
          uint32_value: 1
          uint64_value: 1
          float_value: 1.0
          double_value: 1.0
          bool_value: true
          enum_value: TEST_ENUM_1
          string_value: "string1"
        }
      }
      int32_values: 1
      int32_values: 2
  )PROTO", &test_proto_2));
  EXPECT_FALSE(filter->IsMatch(test_proto_2));
}

}  // namespace
}  // namespace wfa_virtual_people
<|endoftext|>