<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: updateprotocol.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: hr $ $Date: 2007-07-31 15:58:00 $
 *
 *  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_extensions.hxx"

#ifndef _COM_SUN_STAR_XML_XPATH_XXPATHAPI_HPP_
#include <com/sun/star/xml/xpath/XXPathAPI.hpp>
#endif

#include "updateprotocol.hxx"

#ifndef _COM_SUN_STAR_DEPLOYMENT_UPDATEINFORMATINENTRY_HPP_
#include <com/sun/star/deployment/UpdateInformationEntry.hpp>
#endif

#include <rtl/ref.hxx>
#include <rtl/uri.hxx>
#include <rtl/strbuf.hxx>
#include <rtl/ustrbuf.hxx>
#include <rtl/bootstrap.hxx>
#include <osl/process.h>

#include <cppuhelper/implbase1.hxx>

namespace css = com::sun::star ;
namespace container = css::container ;
namespace deployment = css::deployment ;
namespace lang = css::lang ;
namespace uno = css::uno ;
namespace task = css::task ;
namespace xml = css::xml ;

#define UNISTRING(s) rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(s))

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

static bool
getBootstrapData(
    uno::Sequence< ::rtl::OUString > & rRepositoryList,
    ::rtl::OUString & rBuildID,
    ::rtl::OUString & rInstallSetID)
{
    rtl::OUString aPath, aPath2;
    if( osl_getExecutableFile(&aPath.pData) != osl_Process_E_None )
        return false;

    sal_uInt32 lastIndex = aPath.lastIndexOf('/');
    if ( lastIndex > 0 )
    {
        aPath = aPath.copy( 0, lastIndex+1 );
        aPath += UNISTRING( SAL_CONFIGFILE( "version" ) );
    }

    rtl::Bootstrap aVersionFile(aPath);
    aVersionFile.getFrom(UNISTRING("ProductBuildid"), rBuildID, rtl::OUString());
    aVersionFile.getFrom(UNISTRING("UpdateID"), rInstallSetID, rtl::OUString());

    rtl::OUString aValue;
    aVersionFile.getFrom(UNISTRING("UpdateURL"), aValue, rtl::OUString());
    if( aValue.getLength() > 0 )
    {
        rRepositoryList.realloc(1);
        rRepositoryList[0] = aValue;
    }

    return true;
}

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

// Returns 'true' if successfully connected to the update server
bool
checkForUpdates(
    UpdateInfo& o_rUpdateInfo,
    uno::Reference< uno::XComponentContext > const & rxContext,
    uno::Reference< task::XInteractionHandler > const & rxInteractionHandler,
    const uno::Reference< deployment::XUpdateInformationProvider >& rUpdateInfoProvider)
{
    OSL_TRACE("checking for updates ..\n");

    ::rtl::OUString myArch;
    ::rtl::OUString myOS;

    rtl::Bootstrap::get(UNISTRING("_OS"), myOS);
    rtl::Bootstrap::get(UNISTRING("_ARCH"), myArch);

    uno::Sequence< ::rtl::OUString > aRepositoryList;
    ::rtl::OUString aBuildID;
    ::rtl::OUString aInstallSetID;

    if( ! ( getBootstrapData(aRepositoryList, aBuildID, aInstallSetID) && (aRepositoryList.getLength() > 0) ) )
        return false;

    if( !rxContext.is() )
        throw uno::RuntimeException(
            UNISTRING( "checkForUpdates: empty component context" ), uno::Reference< uno::XInterface >() );

    OSL_ASSERT( rxContext->getServiceManager().is() );

    // XPath implementation
    uno::Reference< xml::xpath::XXPathAPI > xXPath(
        rxContext->getServiceManager()->createInstanceWithContext( UNISTRING( "com.sun.star.xml.xpath.XPathAPI" ), rxContext ),
        uno::UNO_QUERY_THROW);

    xXPath->registerNS( UNISTRING("inst"), UNISTRING("http://installation.openoffice.org/description") );

    if( rxInteractionHandler.is() )
        rUpdateInfoProvider->setInteractionHandler(rxInteractionHandler);

    try
    {
        uno::Reference< container::XEnumeration > aUpdateInfoEnumeration =
            rUpdateInfoProvider->getUpdateInformationEnumeration( aRepositoryList, aInstallSetID );

        if ( !aUpdateInfoEnumeration.is() )
            return false; // something went wrong ..

        rtl::OUStringBuffer aBuffer;
        aBuffer.appendAscii("/child::inst:description[inst:os=\'");
        aBuffer.append( myOS );
        aBuffer.appendAscii("\' and inst:arch=\'");
        aBuffer.append( myArch );
        aBuffer.appendAscii("\' and inst:buildid>");
        aBuffer.append( aBuildID );
        aBuffer.appendAscii("]");

        rtl::OUString aXPathExpression = aBuffer.makeStringAndClear();

        while( aUpdateInfoEnumeration->hasMoreElements() )
        {
            deployment::UpdateInformationEntry aEntry;

            if( aUpdateInfoEnumeration->nextElement() >>= aEntry )
            {
                uno::Reference< xml::dom::XNode > xNode( aEntry.UpdateDocument.get() );
                uno::Reference< xml::dom::XNodeList > xNodeList =
                    xXPath->selectNodeList(xNode, aXPathExpression + UNISTRING("/inst:update/attribute::src"));

/*
                o_rUpdateInfo.Sources.push_back( DownloadSource(true,
                    UNISTRING("http://openoffice.bouncer.osuosl.org/?product=OpenOffice.org&os=solarissparcwjre&lang=en-US&version=2.2.1") ) );
*/

                sal_Int32 i, imax = xNodeList->getLength();
                for( i = 0; i < imax; ++i )
                {
                    uno::Reference< xml::dom::XNode > xNode2( xNodeList->item(i) );

                    if( xNode2.is() )
                    {
                        uno::Reference< xml::dom::XElement > xParent(xNode2->getParentNode(), uno::UNO_QUERY_THROW);
                        rtl::OUString aType = xParent->getAttribute(UNISTRING("type"));
                        bool bIsDirect = ( sal_False == aType.equalsIgnoreAsciiCaseAscii("text/html") );

                        o_rUpdateInfo.Sources.push_back( DownloadSource(bIsDirect, xNode2->getNodeValue()) );
                    }
                }

                uno::Reference< xml::dom::XNode > xNode2 =
                    xXPath->selectSingleNode(xNode, aXPathExpression + UNISTRING("/inst:version/text()"));

                if( xNode2.is() )
                    o_rUpdateInfo.Version = xNode2->getNodeValue();

                xNode2 = xXPath->selectSingleNode(xNode, aXPathExpression + UNISTRING("/inst:buildid/text()"));

                if( xNode2.is() )
                    o_rUpdateInfo.BuildId = xNode2->getNodeValue();

                o_rUpdateInfo.Description = aEntry.Description;

                // Release Notes
                xNodeList = xXPath->selectNodeList(xNode, aXPathExpression + UNISTRING("/inst:relnote"));
                imax = xNodeList->getLength();
                for( i = 0; i < imax; ++i )
                {
                    uno::Reference< xml::dom::XElement > xRelNote(xNodeList->item(i), uno::UNO_QUERY);
                    if( xRelNote.is() )
                    {
                        sal_Int32 pos = xRelNote->getAttribute(UNISTRING("pos")).toInt32();

                        ReleaseNote aRelNote((sal_uInt8) pos, xRelNote->getAttribute(UNISTRING("src")));

                        if( xRelNote->hasAttribute(UNISTRING("src2")) )
                        {
                            pos = xRelNote->getAttribute(UNISTRING("pos2")).toInt32();
                            aRelNote.Pos2 = (sal_Int8) pos;
                            aRelNote.URL2 = xRelNote->getAttribute(UNISTRING("src2"));
                        }

                        o_rUpdateInfo.ReleaseNotes.push_back(aRelNote);
                    }
                }
/*
                o_rUpdateInfo.ReleaseNotes.push_back(
                    ReleaseNote(1, UNISTRING("http://qa.openoffice.org/tests/online_update_test.html"))
                );
*/

                if( o_rUpdateInfo.Sources.size() > 0 )
                    return true;
            }
        }
    }
    catch( ... )
    {
        return false;
    }

    return true;
}
<commit_msg>INTEGRATION: CWS updchk10 (1.7.2); FILE MERGED 2007/10/29 13:26:40 dv 1.7.2.3: #i82851# Extension manager notifies update check about found updates 2007/10/23 10:54:05 dv 1.7.2.2: #i82851# Support automatic checking for extension updates 2007/10/08 10:40:49 dv 1.7.2.1: added support for autoupdatecheck for extensions<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: updateprotocol.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: ihi $ $Date: 2007-11-19 16:50:00 $
 *
 *  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_extensions.hxx"

#ifndef _COM_SUN_STAR_XML_XPATH_XXPATHAPI_HPP_
#include <com/sun/star/xml/xpath/XXPathAPI.hpp>
#endif

#include "updateprotocol.hxx"
#include "updatecheckconfig.hxx"

#ifndef _COM_SUN_STAR_DEPLOYMENT_UPDATEINFORMATINENTRY_HPP_
#include <com/sun/star/deployment/UpdateInformationEntry.hpp>
#endif
#ifndef  _COM_SUN_STAR_DEPLOYMENT_XPACKAGEINFORMATIONPROVIDER_HPP_
#include <com/sun/star/deployment/XPackageInformationProvider.hpp>
#endif

#include <rtl/ref.hxx>
#include <rtl/uri.hxx>
#include <rtl/strbuf.hxx>
#include <rtl/ustrbuf.hxx>
#include <rtl/bootstrap.hxx>
#include <osl/process.h>

#include <cppuhelper/implbase1.hxx>

namespace css = com::sun::star ;
namespace container = css::container ;
namespace deployment = css::deployment ;
namespace lang = css::lang ;
namespace uno = css::uno ;
namespace task = css::task ;
namespace xml = css::xml ;

#define UNISTRING(s) rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(s))

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

static bool
getBootstrapData(
    uno::Sequence< ::rtl::OUString > & rRepositoryList,
    ::rtl::OUString & rBuildID,
    ::rtl::OUString & rInstallSetID)
{
    rtl::OUString aPath, aPath2;
    if( osl_getExecutableFile(&aPath.pData) != osl_Process_E_None )
        return false;

    sal_uInt32 lastIndex = aPath.lastIndexOf('/');
    if ( lastIndex > 0 )
    {
        aPath = aPath.copy( 0, lastIndex+1 );
        aPath += UNISTRING( SAL_CONFIGFILE( "version" ) );
    }

    rtl::Bootstrap aVersionFile(aPath);
    aVersionFile.getFrom(UNISTRING("ProductBuildid"), rBuildID, rtl::OUString());
    aVersionFile.getFrom(UNISTRING("UpdateID"), rInstallSetID, rtl::OUString());

    rtl::OUString aValue;
    aVersionFile.getFrom(UNISTRING("UpdateURL"), aValue, rtl::OUString());
    if( aValue.getLength() > 0 )
    {
        rRepositoryList.realloc(1);
        rRepositoryList[0] = aValue;
    }

    return true;
}

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

// Returns 'true' if successfully connected to the update server
bool
checkForUpdates(
    UpdateInfo& o_rUpdateInfo,
    uno::Reference< uno::XComponentContext > const & rxContext,
    uno::Reference< task::XInteractionHandler > const & rxInteractionHandler,
    const uno::Reference< deployment::XUpdateInformationProvider >& rUpdateInfoProvider)
{
    OSL_TRACE("checking for updates ..\n");

    ::rtl::OUString myArch;
    ::rtl::OUString myOS;

    rtl::Bootstrap::get(UNISTRING("_OS"), myOS);
    rtl::Bootstrap::get(UNISTRING("_ARCH"), myArch);

    uno::Sequence< ::rtl::OUString > aRepositoryList;
    ::rtl::OUString aBuildID;
    ::rtl::OUString aInstallSetID;

    if( ! ( getBootstrapData(aRepositoryList, aBuildID, aInstallSetID) && (aRepositoryList.getLength() > 0) ) )
        return false;

    if( !rxContext.is() )
        throw uno::RuntimeException(
            UNISTRING( "checkForUpdates: empty component context" ), uno::Reference< uno::XInterface >() );

    OSL_ASSERT( rxContext->getServiceManager().is() );

    // XPath implementation
    uno::Reference< xml::xpath::XXPathAPI > xXPath(
        rxContext->getServiceManager()->createInstanceWithContext( UNISTRING( "com.sun.star.xml.xpath.XPathAPI" ), rxContext ),
        uno::UNO_QUERY_THROW);

    xXPath->registerNS( UNISTRING("inst"), UNISTRING("http://installation.openoffice.org/description") );

    if( rxInteractionHandler.is() )
        rUpdateInfoProvider->setInteractionHandler(rxInteractionHandler);

    try
    {
        uno::Reference< container::XEnumeration > aUpdateInfoEnumeration =
            rUpdateInfoProvider->getUpdateInformationEnumeration( aRepositoryList, aInstallSetID );

        if ( !aUpdateInfoEnumeration.is() )
            return false; // something went wrong ..

        rtl::OUStringBuffer aBuffer;
        aBuffer.appendAscii("/child::inst:description[inst:os=\'");
        aBuffer.append( myOS );
        aBuffer.appendAscii("\' and inst:arch=\'");
        aBuffer.append( myArch );
        aBuffer.appendAscii("\' and inst:buildid>");
        aBuffer.append( aBuildID );
        aBuffer.appendAscii("]");

        rtl::OUString aXPathExpression = aBuffer.makeStringAndClear();

        while( aUpdateInfoEnumeration->hasMoreElements() )
        {
            deployment::UpdateInformationEntry aEntry;

            if( aUpdateInfoEnumeration->nextElement() >>= aEntry )
            {
                uno::Reference< xml::dom::XNode > xNode( aEntry.UpdateDocument.get() );
                uno::Reference< xml::dom::XNodeList > xNodeList =
                    xXPath->selectNodeList(xNode, aXPathExpression + UNISTRING("/inst:update/attribute::src"));

/*
                o_rUpdateInfo.Sources.push_back( DownloadSource(true,
                    UNISTRING("http://openoffice.bouncer.osuosl.org/?product=OpenOffice.org&os=solarissparcwjre&lang=en-US&version=2.2.1") ) );
*/

                sal_Int32 i, imax = xNodeList->getLength();
                for( i = 0; i < imax; ++i )
                {
                    uno::Reference< xml::dom::XNode > xNode2( xNodeList->item(i) );

                    if( xNode2.is() )
                    {
                        uno::Reference< xml::dom::XElement > xParent(xNode2->getParentNode(), uno::UNO_QUERY_THROW);
                        rtl::OUString aType = xParent->getAttribute(UNISTRING("type"));
                        bool bIsDirect = ( sal_False == aType.equalsIgnoreAsciiCaseAscii("text/html") );

                        o_rUpdateInfo.Sources.push_back( DownloadSource(bIsDirect, xNode2->getNodeValue()) );
                    }
                }

                uno::Reference< xml::dom::XNode > xNode2 =
                    xXPath->selectSingleNode(xNode, aXPathExpression + UNISTRING("/inst:version/text()"));

                if( xNode2.is() )
                    o_rUpdateInfo.Version = xNode2->getNodeValue();

                xNode2 = xXPath->selectSingleNode(xNode, aXPathExpression + UNISTRING("/inst:buildid/text()"));

                if( xNode2.is() )
                    o_rUpdateInfo.BuildId = xNode2->getNodeValue();

                o_rUpdateInfo.Description = aEntry.Description;

                // Release Notes
                xNodeList = xXPath->selectNodeList(xNode, aXPathExpression + UNISTRING("/inst:relnote"));
                imax = xNodeList->getLength();
                for( i = 0; i < imax; ++i )
                {
                    uno::Reference< xml::dom::XElement > xRelNote(xNodeList->item(i), uno::UNO_QUERY);
                    if( xRelNote.is() )
                    {
                        sal_Int32 pos = xRelNote->getAttribute(UNISTRING("pos")).toInt32();

                        ReleaseNote aRelNote((sal_uInt8) pos, xRelNote->getAttribute(UNISTRING("src")));

                        if( xRelNote->hasAttribute(UNISTRING("src2")) )
                        {
                            pos = xRelNote->getAttribute(UNISTRING("pos2")).toInt32();
                            aRelNote.Pos2 = (sal_Int8) pos;
                            aRelNote.URL2 = xRelNote->getAttribute(UNISTRING("src2"));
                        }

                        o_rUpdateInfo.ReleaseNotes.push_back(aRelNote);
                    }
                }
/*
                o_rUpdateInfo.ReleaseNotes.push_back(
                    ReleaseNote(1, UNISTRING("http://qa.openoffice.org/tests/online_update_test.html"))
                );
*/

                if( o_rUpdateInfo.Sources.size() > 0 )
                    return true;
            }
        }
    }
    catch( ... )
    {
        return false;
    }

    return true;
}

//------------------------------------------------------------------------------
bool storeExtensionUpdateInfos( const uno::Reference< uno::XComponentContext > & rxContext,
                                const uno::Sequence< uno::Sequence< rtl::OUString > > &rUpdateInfos )
{
    if ( rUpdateInfos.hasElements() )
    {
        rtl::Reference< UpdateCheckConfig > aConfig = UpdateCheckConfig::get( rxContext );

        for ( sal_Int32 i = rUpdateInfos.getLength() - 1; i >= 0; i-- )
        {
            aConfig->storeExtensionVersion( rUpdateInfos[i][0], rUpdateInfos[i][1] );
        }
    }
    return rUpdateInfos.hasElements();
}

//------------------------------------------------------------------------------
// Returns 'true' if there are updates for any extension

bool checkForExtensionUpdates( const uno::Reference< uno::XComponentContext > & rxContext )
{
    uno::Sequence< uno::Sequence< rtl::OUString > > aUpdateList;

    uno::Reference< deployment::XPackageInformationProvider > xInfoProvider;
    try
    {
        uno::Any aValue( rxContext->getValueByName(
                UNISTRING( "/singletons/com.sun.star.deployment.PackageInformationProvider" ) ) );
        OSL_VERIFY( aValue >>= xInfoProvider );
    }
    catch( const uno::Exception& )
    {
        OSL_ENSURE( false, "checkForExtensionUpdates: could not create the PackageInformationProvider!" );
    }

    if ( !xInfoProvider.is() ) return false;

    aUpdateList = xInfoProvider->isUpdateAvailable( ::rtl::OUString() );
    storeExtensionUpdateInfos( rxContext, aUpdateList );

    return aUpdateList.hasElements();
}

//------------------------------------------------------------------------------
// Returns 'true' if there are any pending updates for any extension (offline check)

bool checkForPendingUpdates( const uno::Reference< uno::XComponentContext > & rxContext )
{
    uno::Sequence< uno::Sequence< rtl::OUString > > aExtensionList;
    uno::Reference< deployment::XPackageInformationProvider > xInfoProvider;
    try
    {
        uno::Any aValue( rxContext->getValueByName(
                UNISTRING( "/singletons/com.sun.star.deployment.PackageInformationProvider" ) ) );
        OSL_VERIFY( aValue >>= xInfoProvider );
    }
    catch( const uno::Exception& )
    {
        OSL_ENSURE( false, "checkForExtensionUpdates: could not create the PackageInformationProvider!" );
    }

    if ( !xInfoProvider.is() ) return false;

    bool bPendingUpdateFound = false;

    aExtensionList = xInfoProvider->getExtensionList();
    if ( aExtensionList.hasElements() )
    {
        rtl::Reference< UpdateCheckConfig > aConfig = UpdateCheckConfig::get( rxContext );

        for ( sal_Int32 i = aExtensionList.getLength() - 1; i >= 0; i-- )
        {
            bPendingUpdateFound = aConfig->checkExtensionVersion( aExtensionList[i][0], aExtensionList[i][1] );
            if ( bPendingUpdateFound )
                break;
        }
    }

    return bPendingUpdateFound;
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2018, Arm Limited and affiliates.
 * SPDX-License-Identifier: Apache-2.0
 *
 * 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.
 */

#if !defined(MBED_CONF_NSAPI_PRESENT)
#error [NOT_SUPPORTED] A json configuration file is needed. Skipping this build.
#endif

#ifndef MBED_CONF_APP_CELLULAR_SIM_PIN
#error [NOT_SUPPORTED] SIM pin code is needed. Skipping this build.
#endif

#if defined(TARGET_ADV_WISE_1570) || defined(TARGET_MTB_ADV_WISE_1570)
#error [NOT_SUPPORTED] target MTB_ADV_WISE_1570 does not have SMS functionality
#endif

#include "greentea-client/test_env.h"
#include "unity.h"
#include "utest.h"

#include "mbed.h"

#include "AT_CellularSMS.h"
#include "CellularContext.h"
#include "CellularDevice.h"
#include "../../cellular_tests_common.h"

#define NETWORK_TIMEOUT (600*1000)
#define SIM_BUSY 314

static CellularContext *ctx;
static CellularDevice *device;
static CellularSMS *sms;
static char service_center_address[SMS_MAX_PHONE_NUMBER_SIZE];
static int service_address_type;

static void create_context()
{
    device = CellularDevice::get_default_instance();
    TEST_ASSERT(device != NULL);
    device->set_timeout(9000);
    ctx = CellularContext::get_default_instance();
    TEST_ASSERT(ctx != NULL);
    ctx->set_sim_pin(MBED_CONF_APP_CELLULAR_SIM_PIN);
#ifdef MBED_CONF_APP_APN
    ctx->set_credentials(MBED_CONF_APP_APN);
#endif
}

static void store_service_center_address()
{
    // First we need to go SIM_PIN state to make sure that we can get service address and device ready to accept AT commands
    create_context();
    TEST_ASSERT(ctx->set_sim_ready() == NSAPI_ERROR_OK);

    wait(5); // some modems needs more time access sim

    ATHandler *at_init = device->get_at_handler();
    at_init->lock();
    at_init->set_at_timeout(30 * 1000);
    at_init->cmd_start("AT+CSCA?");
    at_init->cmd_stop();

    TEST_ASSERT(at_init->get_last_error() == NSAPI_ERROR_OK);

    at_init->resp_start("+CSCA:");
    at_init->read_string(service_center_address, sizeof(service_center_address));
    service_address_type = at_init->read_int();
    at_init->resp_stop();
    TEST_ASSERT(at_init->get_last_error() == NSAPI_ERROR_OK);

    at_init->unlock();
    device->release_at_handler(at_init);
}

static void init()
{
    // First store current service address
    store_service_center_address();
    create_context();

    TEST_ASSERT(ctx->register_to_network() == NSAPI_ERROR_OK);
    sms = device->open_sms();
    TEST_ASSERT(sms != NULL);
    wait(3); // some modems needs more time access sim
}

static void test_sms_initialize_text_mode()
{
    nsapi_error_t err = sms->initialize(CellularSMS::CellularSMSMmodeText);
    TEST_ASSERT(err == NSAPI_ERROR_OK || (err == NSAPI_ERROR_DEVICE_ERROR &&
                                          ((AT_CellularSMS *)sms)->get_device_error().errCode == SIM_BUSY));

}

static void test_sms_initialize_pdu_mode()
{
    nsapi_error_t err = sms->initialize(CellularSMS::CellularSMSMmodePDU);
    TEST_ASSERT(err == NSAPI_ERROR_OK || err == NSAPI_ERROR_UNSUPPORTED || (err == NSAPI_ERROR_DEVICE_ERROR &&
                ((AT_CellularSMS *)sms)->get_device_error().errCode == SIM_BUSY));
}

static void test_set_cscs()
{
    nsapi_error_t err = sms->set_cscs("IRA");
    TEST_ASSERT(err == NSAPI_ERROR_OK || err == NSAPI_ERROR_UNSUPPORTED || (err == NSAPI_ERROR_DEVICE_ERROR &&
                ((AT_CellularSMS *)sms)->get_device_error().errCode == SIM_BUSY));
    err = sms->set_cscs("UCS2");
    TEST_ASSERT(err == NSAPI_ERROR_OK || err == NSAPI_ERROR_UNSUPPORTED || (err == NSAPI_ERROR_DEVICE_ERROR &&
                ((AT_CellularSMS *)sms)->get_device_error().errCode == SIM_BUSY));
    err = sms->set_cscs("GSM");
    TEST_ASSERT(err == NSAPI_ERROR_OK || err == NSAPI_ERROR_UNSUPPORTED || (err == NSAPI_ERROR_DEVICE_ERROR &&
                ((AT_CellularSMS *)sms)->get_device_error().errCode == SIM_BUSY));
}

static void test_set_csca()
{
    nsapi_error_t err = sms->set_csca("55555", 129);
    TEST_ASSERT(err == NSAPI_ERROR_OK || (err == NSAPI_ERROR_DEVICE_ERROR &&
                                          ((AT_CellularSMS *)sms)->get_device_error().errCode == SIM_BUSY));
    err = sms->set_csca("+35855555", 145);
    TEST_ASSERT(err == NSAPI_ERROR_OK || (err == NSAPI_ERROR_DEVICE_ERROR &&
                                          ((AT_CellularSMS *)sms)->get_device_error().errCode == SIM_BUSY));
    err = sms->set_csca(service_center_address, service_address_type);
    TEST_ASSERT(err == NSAPI_ERROR_OK || (err == NSAPI_ERROR_DEVICE_ERROR &&
                                          ((AT_CellularSMS *)sms)->get_device_error().errCode == SIM_BUSY));
}

static void test_set_cpms_me()
{
    nsapi_error_t err = sms->set_cpms("ME", "ME", "ME");
    TEST_ASSERT(err == NSAPI_ERROR_OK || err == NSAPI_ERROR_UNSUPPORTED || (err == NSAPI_ERROR_DEVICE_ERROR &&
                ((AT_CellularSMS *)sms)->get_device_error().errCode == SIM_BUSY));
}

#ifdef MBED_CONF_APP_CELLULAR_PHONE_NUMBER
static const char TEST_MESSAGE[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
static int callbacks_received = 0;

static void sms_callback()
{
    callbacks_received++;
}

static void test_set_sms_callback()
{
    sms->set_sms_callback(sms_callback);
}

static void test_set_cpms_sm()
{
    TEST_ASSERT(sms->set_cpms("SM", "SM", "SM") == NSAPI_ERROR_OK);
}

static void test_sms_send()
{
    const int msg_len = strlen(TEST_MESSAGE);
    TEST_ASSERT(sms->send_sms(MBED_CONF_APP_CELLULAR_PHONE_NUMBER, TEST_MESSAGE, msg_len) == msg_len);
}

static void test_get_sms()
{
    uint16_t buf_len = sizeof(TEST_MESSAGE);
    char buf[buf_len];

    char phone_num[SMS_MAX_PHONE_NUMBER_SIZE];

    char time_stamp[SMS_MAX_TIME_STAMP_SIZE];

    int buf_size = 0;

    wait(7);

    TEST_ASSERT(sms->get_sms(buf, buf_len, phone_num, SMS_MAX_PHONE_NUMBER_SIZE, time_stamp, SMS_MAX_TIME_STAMP_SIZE, &buf_size) == buf_len - 1);
    TEST_ASSERT(strcmp(phone_num, MBED_CONF_APP_CELLULAR_PHONE_NUMBER) == 0);
    TEST_ASSERT(strcmp(buf, TEST_MESSAGE) == 0);
    TEST_ASSERT(buf_size == 0);
    TEST_ASSERT(callbacks_received > 0);
    callbacks_received = 0;

}

static void test_delete_all_messages()
{
    //send a message so that there is something to delete
    test_sms_send();
    wait(7);
    TEST_ASSERT(sms->delete_all_messages() == NSAPI_ERROR_OK);
    callbacks_received = 0;
}

static void test_set_extra_sim_wait_time_1000()
{
    sms->set_extra_sim_wait_time(1000);
}

#endif

using namespace utest::v1;

static utest::v1::status_t greentea_failure_handler(const Case *const source, const failure_t reason)
{
    greentea_case_failure_abort_handler(source, reason);
    return STATUS_ABORT;
}

static Case cases[] = {
    Case("CellularSMS init", init, greentea_failure_handler),
    Case("CellularSMS test ME for storage", test_set_cpms_me, greentea_failure_handler),
    Case("CellularSMS test initialize to PDU mode", test_sms_initialize_pdu_mode, greentea_failure_handler),
    Case("CellularSMS test character sets", test_set_cscs, greentea_failure_handler),
    Case("CellularSMS test service center address", test_set_csca, greentea_failure_handler)
#ifdef MBED_CONF_APP_CELLULAR_PHONE_NUMBER
    ,
    Case("CellularSMS test delete all messages", test_delete_all_messages, greentea_failure_handler),
    Case("CellularSMS test sms callback", test_set_sms_callback, greentea_failure_handler),
    Case("CellularSMS test sms send", test_sms_send, greentea_failure_handler),
    Case("CellularSMS test get sms", test_get_sms, greentea_failure_handler),
    Case("CellularSMS test set sim wait time 1s", test_set_extra_sim_wait_time_1000, greentea_failure_handler),
    Case("CellularSMS test SM for storage", test_set_cpms_sm, greentea_failure_handler),
    Case("CellularSMS test initialize to text mode", test_sms_initialize_text_mode, greentea_failure_handler),
    Case("CellularSMS test delete all messages", test_delete_all_messages, greentea_failure_handler),
    Case("CellularSMS test sms send", test_sms_send, greentea_failure_handler),
    Case("CellularSMS test get sms", test_get_sms, greentea_failure_handler),
    Case("CellularSMS test delete all messages", test_delete_all_messages, greentea_failure_handler)
#endif
};

static utest::v1::status_t test_setup(const size_t number_of_cases)
{
    GREENTEA_SETUP(600, "default_auto");
    return verbose_test_setup_handler(number_of_cases);
}

static Specification specification(test_setup, cases);

int main()
{
#if MBED_CONF_MBED_TRACE_ENABLE
    trace_open();
#endif
    int ret = Harness::run(specification);
#if MBED_CONF_MBED_TRACE_ENABLE
    trace_close();
#endif
    return ret;
}
<commit_msg>Applied suggested astyle fixes<commit_after>/*
 * Copyright (c) 2018, Arm Limited and affiliates.
 * SPDX-License-Identifier: Apache-2.0
 *
 * 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.
 */

#if !defined(MBED_CONF_NSAPI_PRESENT)
#error [NOT_SUPPORTED] A json configuration file is needed. Skipping this build.
#endif

#ifndef MBED_CONF_APP_CELLULAR_SIM_PIN
#error [NOT_SUPPORTED] SIM pin code is needed. Skipping this build.
#endif

#if defined(TARGET_ADV_WISE_1570) || defined(TARGET_MTB_ADV_WISE_1570)
#error [NOT_SUPPORTED] target MTB_ADV_WISE_1570 does not have SMS functionality
#endif

#include "greentea-client/test_env.h"
#include "unity.h"
#include "utest.h"

#include "mbed.h"

#include "AT_CellularSMS.h"
#include "CellularContext.h"
#include "CellularDevice.h"
#include "../../cellular_tests_common.h"

#define NETWORK_TIMEOUT (600*1000)
#define SIM_BUSY 314

static CellularContext *ctx;
static CellularDevice *device;
static CellularSMS *sms;
static char service_center_address[SMS_MAX_PHONE_NUMBER_SIZE];
static int service_address_type;

static void create_context()
{
    device = CellularDevice::get_default_instance();
    TEST_ASSERT(device != NULL);
    device->set_timeout(9000);
    ctx = CellularContext::get_default_instance();
    TEST_ASSERT(ctx != NULL);
    ctx->set_sim_pin(MBED_CONF_APP_CELLULAR_SIM_PIN);
#ifdef MBED_CONF_APP_APN
    ctx->set_credentials(MBED_CONF_APP_APN);
#endif
}

static void store_service_center_address()
{
    // First we need to go SIM_PIN state to make sure that we can get service address and device ready to accept AT commands
    create_context();
    TEST_ASSERT(ctx->set_sim_ready() == NSAPI_ERROR_OK);

    wait(5); // some modems needs more time access sim

    ATHandler *at_init = device->get_at_handler();
    at_init->lock();
    at_init->set_at_timeout(30 * 1000);
    at_init->cmd_start("AT+CSCA?");
    at_init->cmd_stop();

    TEST_ASSERT(at_init->get_last_error() == NSAPI_ERROR_OK);

    at_init->resp_start("+CSCA:");
    at_init->read_string(service_center_address, sizeof(service_center_address));
    service_address_type = at_init->read_int();
    at_init->resp_stop();
    TEST_ASSERT(at_init->get_last_error() == NSAPI_ERROR_OK);

    at_init->unlock();
    device->release_at_handler(at_init);
}

static void init()
{
    // First store current service address
    store_service_center_address();
    create_context();

    TEST_ASSERT(ctx->register_to_network() == NSAPI_ERROR_OK);
    sms = device->open_sms();
    TEST_ASSERT(sms != NULL);
    wait(3); // some modems needs more time access sim
}

static void test_sms_initialize_text_mode()
{
    nsapi_error_t err = sms->initialize(CellularSMS::CellularSMSMmodeText);
    TEST_ASSERT(err == NSAPI_ERROR_OK || (err == NSAPI_ERROR_DEVICE_ERROR &&
                                          ((AT_CellularSMS *)sms)->get_device_error().errCode == SIM_BUSY));

}

static void test_sms_initialize_pdu_mode()
{
    nsapi_error_t err = sms->initialize(CellularSMS::CellularSMSMmodePDU);
    TEST_ASSERT(err == NSAPI_ERROR_OK || err == NSAPI_ERROR_UNSUPPORTED || (err == NSAPI_ERROR_DEVICE_ERROR &&
                                                                            ((AT_CellularSMS *)sms)->get_device_error().errCode == SIM_BUSY));
}

static void test_set_cscs()
{
    nsapi_error_t err = sms->set_cscs("IRA");
    TEST_ASSERT(err == NSAPI_ERROR_OK || err == NSAPI_ERROR_UNSUPPORTED || (err == NSAPI_ERROR_DEVICE_ERROR &&
                                                                            ((AT_CellularSMS *)sms)->get_device_error().errCode == SIM_BUSY));
    err = sms->set_cscs("UCS2");
    TEST_ASSERT(err == NSAPI_ERROR_OK || err == NSAPI_ERROR_UNSUPPORTED || (err == NSAPI_ERROR_DEVICE_ERROR &&
                                                                            ((AT_CellularSMS *)sms)->get_device_error().errCode == SIM_BUSY));
    err = sms->set_cscs("GSM");
    TEST_ASSERT(err == NSAPI_ERROR_OK || err == NSAPI_ERROR_UNSUPPORTED || (err == NSAPI_ERROR_DEVICE_ERROR &&
                                                                            ((AT_CellularSMS *)sms)->get_device_error().errCode == SIM_BUSY));
}

static void test_set_csca()
{
    nsapi_error_t err = sms->set_csca("55555", 129);
    TEST_ASSERT(err == NSAPI_ERROR_OK || (err == NSAPI_ERROR_DEVICE_ERROR &&
                                          ((AT_CellularSMS *)sms)->get_device_error().errCode == SIM_BUSY));
    err = sms->set_csca("+35855555", 145);
    TEST_ASSERT(err == NSAPI_ERROR_OK || (err == NSAPI_ERROR_DEVICE_ERROR &&
                                          ((AT_CellularSMS *)sms)->get_device_error().errCode == SIM_BUSY));
    err = sms->set_csca(service_center_address, service_address_type);
    TEST_ASSERT(err == NSAPI_ERROR_OK || (err == NSAPI_ERROR_DEVICE_ERROR &&
                                          ((AT_CellularSMS *)sms)->get_device_error().errCode == SIM_BUSY));
}

static void test_set_cpms_me()
{
    nsapi_error_t err = sms->set_cpms("ME", "ME", "ME");
    TEST_ASSERT(err == NSAPI_ERROR_OK || err == NSAPI_ERROR_UNSUPPORTED || (err == NSAPI_ERROR_DEVICE_ERROR &&
                                                                            ((AT_CellularSMS *)sms)->get_device_error().errCode == SIM_BUSY));
}

#ifdef MBED_CONF_APP_CELLULAR_PHONE_NUMBER
static const char TEST_MESSAGE[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
static int callbacks_received = 0;

static void sms_callback()
{
    callbacks_received++;
}

static void test_set_sms_callback()
{
    sms->set_sms_callback(sms_callback);
}

static void test_set_cpms_sm()
{
    TEST_ASSERT(sms->set_cpms("SM", "SM", "SM") == NSAPI_ERROR_OK);
}

static void test_sms_send()
{
    const int msg_len = strlen(TEST_MESSAGE);
    TEST_ASSERT(sms->send_sms(MBED_CONF_APP_CELLULAR_PHONE_NUMBER, TEST_MESSAGE, msg_len) == msg_len);
}

static void test_get_sms()
{
    uint16_t buf_len = sizeof(TEST_MESSAGE);
    char buf[buf_len];

    char phone_num[SMS_MAX_PHONE_NUMBER_SIZE];

    char time_stamp[SMS_MAX_TIME_STAMP_SIZE];

    int buf_size = 0;

    wait(7);

    TEST_ASSERT(sms->get_sms(buf, buf_len, phone_num, SMS_MAX_PHONE_NUMBER_SIZE, time_stamp, SMS_MAX_TIME_STAMP_SIZE, &buf_size) == buf_len - 1);
    TEST_ASSERT(strcmp(phone_num, MBED_CONF_APP_CELLULAR_PHONE_NUMBER) == 0);
    TEST_ASSERT(strcmp(buf, TEST_MESSAGE) == 0);
    TEST_ASSERT(buf_size == 0);
    TEST_ASSERT(callbacks_received > 0);
    callbacks_received = 0;

}

static void test_delete_all_messages()
{
    //send a message so that there is something to delete
    test_sms_send();
    wait(7);
    TEST_ASSERT(sms->delete_all_messages() == NSAPI_ERROR_OK);
    callbacks_received = 0;
}

static void test_set_extra_sim_wait_time_1000()
{
    sms->set_extra_sim_wait_time(1000);
}

#endif

using namespace utest::v1;

static utest::v1::status_t greentea_failure_handler(const Case *const source, const failure_t reason)
{
    greentea_case_failure_abort_handler(source, reason);
    return STATUS_ABORT;
}

static Case cases[] = {
    Case("CellularSMS init", init, greentea_failure_handler),
    Case("CellularSMS test ME for storage", test_set_cpms_me, greentea_failure_handler),
    Case("CellularSMS test initialize to PDU mode", test_sms_initialize_pdu_mode, greentea_failure_handler),
    Case("CellularSMS test character sets", test_set_cscs, greentea_failure_handler),
    Case("CellularSMS test service center address", test_set_csca, greentea_failure_handler)
#ifdef MBED_CONF_APP_CELLULAR_PHONE_NUMBER
    ,
    Case("CellularSMS test delete all messages", test_delete_all_messages, greentea_failure_handler),
    Case("CellularSMS test sms callback", test_set_sms_callback, greentea_failure_handler),
    Case("CellularSMS test sms send", test_sms_send, greentea_failure_handler),
    Case("CellularSMS test get sms", test_get_sms, greentea_failure_handler),
    Case("CellularSMS test set sim wait time 1s", test_set_extra_sim_wait_time_1000, greentea_failure_handler),
    Case("CellularSMS test SM for storage", test_set_cpms_sm, greentea_failure_handler),
    Case("CellularSMS test initialize to text mode", test_sms_initialize_text_mode, greentea_failure_handler),
    Case("CellularSMS test delete all messages", test_delete_all_messages, greentea_failure_handler),
    Case("CellularSMS test sms send", test_sms_send, greentea_failure_handler),
    Case("CellularSMS test get sms", test_get_sms, greentea_failure_handler),
    Case("CellularSMS test delete all messages", test_delete_all_messages, greentea_failure_handler)
#endif
};

static utest::v1::status_t test_setup(const size_t number_of_cases)
{
    GREENTEA_SETUP(600, "default_auto");
    return verbose_test_setup_handler(number_of_cases);
}

static Specification specification(test_setup, cases);

int main()
{
#if MBED_CONF_MBED_TRACE_ENABLE
    trace_open();
#endif
    int ret = Harness::run(specification);
#if MBED_CONF_MBED_TRACE_ENABLE
    trace_close();
#endif
    return ret;
}
<|endoftext|>


<commit_before>#include <iostream>

int main()
{
    std::cout << "Hello World" << std::endl;
}<commit_msg>TosLang: Started putting together the compiler driver with what has been done so far<commit_after>#include "AST/ast.h"
#include "Parse/parser.h"
#include "Sema/symbolcollector.h"
#include "Sema/symboltable.h"
#include "Sema/typechecker.h"

// TODO: include codegen

#include <iostream>

static void Compile(const std::string& programFile)
{
    TosLang::FrontEnd::Parser parser;
    auto programAST = parser.ParseProgram(programFile);
    if (programAST == nullptr)
        return;

    auto symbolTable = std::make_shared<TosLang::FrontEnd::SymbolTable>();
    TosLang::FrontEnd::SymbolCollector sCollector{ symbolTable };
    sCollector.Run(programAST);

    TosLang::FrontEnd::TypeChecker tChecker{ symbolTable };
    tChecker.Run(programAST);
    if (tChecker.GetErrorCount() != 0)
        return;
}

int main()
{
}<|endoftext|>


<commit_before>//http://www.cranems.com/

#include <iostream>

using namespace std;

int main()
{

   cout << "Maquina de vendas" << endl ;

}
<commit_msg>teste2<commit_after>//http://www.cranems.com/
//teste2

#include <iostream>

using namespace std;

int main()
{

   cout << "Maquina de vendas" << endl ;

}
<|endoftext|>


<commit_before>#include <chrono>
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>

using namespace RooFit;

// call from command line like, for instance:
// root -l 'unbinned_scaling2.cpp()'

// timing_flag is used to activate only selected timing statements [1-7]

void unbinned_scaling2(int num_cpu=1, bool force_num_int=false, int optConst=2,
                       int N_gaussians=1, int N_observables=1, int N_parameters=2,
                       int N_events=100000,
                       int parallel_interleave=0,
                       int seed=1,
                       int print_level=0,
                       int timing_flag=1
                       ) {
  //gSystem->Exec("top -n1 -b");
  // num_cpu: -1 is special option -> overhead communicatie protocol vergelijken (vgl met 1 cpu)
  // parallel_interleave: 0 = blokken gelijke grootte, 1 = interleave
  //
  //             binned:         generateBinned ipv generate -> als je aantal events ongeveer even groot is als aantal bins krijg je load balancing problemen, dat zou interleave beetje moeten ondervangen
  // verwachtingen
  // - historisch: tot ~8 cpu gaat het goed
  // - weinig data en veel parameters: comm overhead belangrijk (fit snel, veel tijd in oversturen params)
  // - weinig parameters, veel data: scalability hoort beter te zijn (minder comm overhead) -> bottom line van wat de software kan
  // - observables even op 1 houden, alles optellen klopt conceptueel-statistisch niet

  RooMsgService::instance().addStream(DEBUG, Topic(Generation));

  // int N_parameters(8);  // must be even, means and sigmas have diff ranges
  ofstream outfile;

  if (timing_flag > 0) {
    outfile.open("timing_meta.json", ios::app);

    outfile << "{\"N_gaussians\": \"" << N_gaussians
            << "\", \"N_observables\": \"" << N_observables
            << "\", \"N_parameters\": \"" << N_parameters
            << "\", \"N_events\": \"" << N_events
            << "\", \"num_cpu\": \"" << num_cpu
            << "\", \"parallel_interleave\": \"" << parallel_interleave
            << "\", \"seed\": \"" << seed
            << "\", \"pid\": \"" << getpid()
            << "\"}," << std::endl;

    outfile.close();
  }

  RooTrace::timing_flag = timing_flag;

  // plotting configuration
  int obs_plot_x(3);
  int obs_plot_y(2);
  int obs_plot_x_px(1200);
  int obs_plot_y_px(800);

  // other stuff
  int printlevel(print_level);
  int optimizeConst(optConst);
  // int N_timing_loops(3); // not used

  gRandom->SetSeed(seed);

  // some sanity checks
  if (obs_plot_x * obs_plot_y < N_observables) {
    std::cout << "WARNING: obs_plot_x * obs_plot_y < N_observables,"
                 " won't be able to plot all observables!"
              << std::endl << std::endl;
  }
  if (N_parameters % 2 != 0) {
    std::cout << "set N_parameters to an even number!" << std::endl;
    exit(2);
  }

  // here we go!

  RooWorkspace w("w", 1) ;

  RooArgSet obs_set;

  // create gaussian parameters
  float mean[N_parameters/2], sigma[N_parameters/2];
  for (int ix = 0; ix < N_parameters/2; ++ix) {
    mean[ix] = gRandom->Gaus(0, 2);
    sigma[ix] = 0.1 + abs(gRandom->Gaus(0, 2));
  }

  // create gaussians and also the observables and parameters they depend on
  RooAbsReal* gaussian_ix;
  for (int ix = 0; ix < N_gaussians; ++ix) {
    std::cout << ix << std::endl;
    std::ostringstream os;
    // int ix_p = (ix/2) % N_parameters;
    int ix_p = ix % (N_parameters / 2);
    os << "Gaussian::g" << ix
       << "(x" << ix % N_observables << "[-10,10],"
       << "m" << ix_p << "[" << mean[ix_p] << ",-10,10],"
       << "s" << ix_p << "[" << sigma[ix_p] << ",0.1,10])";
    std::string s = os.str();
    gaussian_ix = dynamic_cast<RooAbsReal *>(w.factory(s.c_str()));

    if (force_num_int) {
      // force it
      if (gaussian_ix) {
        gaussian_ix->forceNumInt(kTRUE);
      } else {
        std::cout << "GAUSSIAN_IX " << ix << " GOT NULL PTR!!" << std::endl;
        exit(1);
      }
    }
  }

  // create uniform background signals on each observable
  for (int ix = 0; ix < N_observables; ++ix) {
    {
      std::ostringstream os;
      os << "Uniform::u" << ix << "(x" << ix << ")";
      std::string s = os.str();
      w.factory(s.c_str());
    }

    // gather the observables in a list for data generation below
    {
      std::ostringstream os;
      os << "x" << ix;
      std::string s = os.str();
      obs_set.add(*w.arg(s.c_str()));
    }
  }

  RooArgSet pdf_set = w.allPdfs();

  // create event counts for all pdfs
  RooArgSet count_set;

  // ... for the gaussians
  for (int ix = 0; ix < N_gaussians; ++ix) {
    std::stringstream os, os2;
    os << "Nsig" << ix;
    std::string s = os.str();
    os2 << "#signal events comp " << ix;
    std::string s2 = os2.str();
    RooRealVar a(s.c_str(), s2.c_str(), 100, 0., 10*N_events);
    w.import(a);
  }
  // gather them in count_set
  for (int ix = 0; ix < N_gaussians; ++ix) {
    std::stringstream os;
    os << "Nsig" << ix;
    std::string s = os.str();
    count_set.add(*w.arg(s.c_str()));
  }
  // ... and for the uniform background components
  for (int ix = 0; ix < N_observables; ++ix) {
    std::stringstream os, os2;
    os << "Nbkg" << ix;
    std::string s = os.str();
    os2 << "#background events comp " << ix;
    std::string s2 = os2.str();
    RooRealVar a(s.c_str(), s2.c_str(), 100, 0., 10*N_events);
    w.import(a);
  }
  // gather them in count_set
  for (int ix = 0; ix < N_observables; ++ix) {
    std::stringstream os;
    os << "Nbkg" << ix;
    std::string s = os.str();
    count_set.add(*w.arg(s.c_str()));
  }

  RooAddPdf sum("sum", "gaussians+uniforms", pdf_set, count_set);

  // --- Generate a toyMC sample from composite PDF ---
  RooDataSet *data = sum.generate(obs_set, N_events);
/*
  // OR reload previously written out sample:
  // wegschrijven:
  data.write("roofit_demo_random_data_values.dat");
  // om het weer in te lezen:
  RooDataSet *data = RooDataSet::read("../roofit_demo_random_data_values.dat", RooArgList(mes));
*/

  // --- Perform extended ML fit of composite PDF to toy data ---
  // sum.fitTo(*data,"Extended") ;
  // instead of full fitTo, only do the fit, leave out error matrix, using
  // run style of run_higgs.C
  std::chrono::time_point<std::chrono::high_resolution_clock> begin, end;

  if (timing_flag == 1) {
    outfile.open("timing_full_minimize.json", ios::app);
  }

  // for (int it = 0; it < N_timing_loops; ++it)
  {
    RooAbsReal* nll = sum.createNLL(*data, NumCPU(num_cpu, parallel_interleave));//, "Extended");
    RooMinimizer m(*nll);
    // m.setVerbose(1);
    m.setStrategy(0);
    m.setProfile(1);
    m.setPrintLevel(printlevel);
    m.optimizeConst(optimizeConst);

    if (timing_flag == 1) {
      begin = std::chrono::high_resolution_clock::now();
    }
    // m.hesse();

    m.minimize("Minuit2", "migrad");

    if (timing_flag == 1) {
      end = std::chrono::high_resolution_clock::now();

      float timing_s = std::chrono::duration_cast<std::chrono::nanoseconds>
                       (end-begin).count() / static_cast<float>(1e9);
      std::cout << timing_s << "s" << std::endl;

      outfile << "{\"full_minimize_wall_s\": \"" << timing_s
              << "\", \"pid\": \"" << getpid()
              << "\"}," << std::endl;
    }
  }
  if (timing_flag == 1) {
    outfile.close();
  }

  // print the "true" values for comparison
  std::cout << "--- values of PDF parameters used for data generation:"
            << std::endl;
  for (int ix = 0; ix < N_parameters/2; ++ix) {
    std::cout << "    gauss " << ix << ": m = " << mean[ix] << ", s = "
              << sigma[ix] << std::endl;
  }

  // --- Plot toy data and composite PDF overlaid ---
  TCanvas* c = new TCanvas("unbinned_scaling", "unbinned_scaling",
                           obs_plot_x_px, obs_plot_y_px);
  c->Divide(obs_plot_x, obs_plot_y);
  for (int ix = 0; ix < N_observables && ix < obs_plot_x * obs_plot_y; ++ix) {
    std::ostringstream os;
    os << "x" << ix;
    std::string s = os.str();
    RooPlot* frame = w.var(s.c_str())->frame();
    data->plotOn(frame);
    sum.plotOn(frame);
    c->cd(ix+1);
    frame->Draw();
  }
}
<commit_msg>Added parameter for setting num ints timing via RooTrace<commit_after>#include <chrono>
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>

using namespace RooFit;

// call from command line like, for instance:
// root -l 'unbinned_scaling2.cpp()'

// timing_flag is used to activate only selected timing statements [1-7]

void unbinned_scaling2(int num_cpu=1, bool force_num_int=false,
                       bool time_num_ints=false, int optConst=2,
                       int N_gaussians=1, int N_observables=1, int N_parameters=2,
                       int N_events=100000,
                       int parallel_interleave=0,
                       int seed=1,
                       int print_level=0,
                       int timing_flag=1
                       ) {
  //gSystem->Exec("top -n1 -b");
  // num_cpu: -1 is special option -> overhead communicatie protocol vergelijken (vgl met 1 cpu)
  // parallel_interleave: 0 = blokken gelijke grootte, 1 = interleave
  //
  //             binned:         generateBinned ipv generate -> als je aantal events ongeveer even groot is als aantal bins krijg je load balancing problemen, dat zou interleave beetje moeten ondervangen
  // verwachtingen
  // - historisch: tot ~8 cpu gaat het goed
  // - weinig data en veel parameters: comm overhead belangrijk (fit snel, veel tijd in oversturen params)
  // - weinig parameters, veel data: scalability hoort beter te zijn (minder comm overhead) -> bottom line van wat de software kan
  // - observables even op 1 houden, alles optellen klopt conceptueel-statistisch niet

  RooMsgService::instance().addStream(DEBUG, Topic(Generation));

  // int N_parameters(8);  // must be even, means and sigmas have diff ranges
  ofstream outfile;

  if (timing_flag > 0) {
    outfile.open("timing_meta.json", ios::app);

    outfile << "{\"N_gaussians\": \"" << N_gaussians
            << "\", \"N_observables\": \"" << N_observables
            << "\", \"N_parameters\": \"" << N_parameters
            << "\", \"N_events\": \"" << N_events
            << "\", \"num_cpu\": \"" << num_cpu
            << "\", \"parallel_interleave\": \"" << parallel_interleave
            << "\", \"seed\": \"" << seed
            << "\", \"pid\": \"" << getpid()
            << "\"}," << std::endl;

    outfile.close();
  }

  RooTrace::timing_flag = timing_flag;
  if (time_num_ints) {
    RooTrace::set_time_numInts(kTRUE);
  }

  // plotting configuration
  int obs_plot_x(3);
  int obs_plot_y(2);
  int obs_plot_x_px(1200);
  int obs_plot_y_px(800);

  // other stuff
  int printlevel(print_level);
  int optimizeConst(optConst);
  // int N_timing_loops(3); // not used

  gRandom->SetSeed(seed);

  // some sanity checks
  if (obs_plot_x * obs_plot_y < N_observables) {
    std::cout << "WARNING: obs_plot_x * obs_plot_y < N_observables,"
                 " won't be able to plot all observables!"
              << std::endl << std::endl;
  }
  if (N_parameters % 2 != 0) {
    std::cout << "set N_parameters to an even number!" << std::endl;
    exit(2);
  }

  // here we go!

  RooWorkspace w("w", 1) ;

  RooArgSet obs_set;

  // create gaussian parameters
  float mean[N_parameters/2], sigma[N_parameters/2];
  for (int ix = 0; ix < N_parameters/2; ++ix) {
    mean[ix] = gRandom->Gaus(0, 2);
    sigma[ix] = 0.1 + abs(gRandom->Gaus(0, 2));
  }

  // create gaussians and also the observables and parameters they depend on
  RooAbsReal* gaussian_ix;
  for (int ix = 0; ix < N_gaussians; ++ix) {
    std::cout << ix << std::endl;
    std::ostringstream os;
    // int ix_p = (ix/2) % N_parameters;
    int ix_p = ix % (N_parameters / 2);
    os << "Gaussian::g" << ix
       << "(x" << ix % N_observables << "[-10,10],"
       << "m" << ix_p << "[" << mean[ix_p] << ",-10,10],"
       << "s" << ix_p << "[" << sigma[ix_p] << ",0.1,10])";
    std::string s = os.str();
    gaussian_ix = dynamic_cast<RooAbsReal *>(w.factory(s.c_str()));

    if (force_num_int) {
      // force it
      if (gaussian_ix) {
        gaussian_ix->forceNumInt(kTRUE);
      } else {
        std::cout << "GAUSSIAN_IX " << ix << " GOT NULL PTR!!" << std::endl;
        exit(1);
      }
    }
  }

  // create uniform background signals on each observable
  for (int ix = 0; ix < N_observables; ++ix) {
    {
      std::ostringstream os;
      os << "Uniform::u" << ix << "(x" << ix << ")";
      std::string s = os.str();
      w.factory(s.c_str());
    }

    // gather the observables in a list for data generation below
    {
      std::ostringstream os;
      os << "x" << ix;
      std::string s = os.str();
      obs_set.add(*w.arg(s.c_str()));
    }
  }

  RooArgSet pdf_set = w.allPdfs();

  // create event counts for all pdfs
  RooArgSet count_set;

  // ... for the gaussians
  for (int ix = 0; ix < N_gaussians; ++ix) {
    std::stringstream os, os2;
    os << "Nsig" << ix;
    std::string s = os.str();
    os2 << "#signal events comp " << ix;
    std::string s2 = os2.str();
    RooRealVar a(s.c_str(), s2.c_str(), 100, 0., 10*N_events);
    w.import(a);
  }
  // gather them in count_set
  for (int ix = 0; ix < N_gaussians; ++ix) {
    std::stringstream os;
    os << "Nsig" << ix;
    std::string s = os.str();
    count_set.add(*w.arg(s.c_str()));
  }
  // ... and for the uniform background components
  for (int ix = 0; ix < N_observables; ++ix) {
    std::stringstream os, os2;
    os << "Nbkg" << ix;
    std::string s = os.str();
    os2 << "#background events comp " << ix;
    std::string s2 = os2.str();
    RooRealVar a(s.c_str(), s2.c_str(), 100, 0., 10*N_events);
    w.import(a);
  }
  // gather them in count_set
  for (int ix = 0; ix < N_observables; ++ix) {
    std::stringstream os;
    os << "Nbkg" << ix;
    std::string s = os.str();
    count_set.add(*w.arg(s.c_str()));
  }

  RooAddPdf sum("sum", "gaussians+uniforms", pdf_set, count_set);

  // --- Generate a toyMC sample from composite PDF ---
  RooDataSet *data = sum.generate(obs_set, N_events);
/*
  // OR reload previously written out sample:
  // wegschrijven:
  data.write("roofit_demo_random_data_values.dat");
  // om het weer in te lezen:
  RooDataSet *data = RooDataSet::read("../roofit_demo_random_data_values.dat", RooArgList(mes));
*/

  // --- Perform extended ML fit of composite PDF to toy data ---
  // sum.fitTo(*data,"Extended") ;
  // instead of full fitTo, only do the fit, leave out error matrix, using
  // run style of run_higgs.C
  std::chrono::time_point<std::chrono::high_resolution_clock> begin, end;

  if (timing_flag == 1) {
    outfile.open("timing_full_minimize.json", ios::app);
  }

  // for (int it = 0; it < N_timing_loops; ++it)
  {
    RooAbsReal* nll = sum.createNLL(*data, NumCPU(num_cpu, parallel_interleave));//, "Extended");
    RooMinimizer m(*nll);
    // m.setVerbose(1);
    m.setStrategy(0);
    m.setProfile(1);
    m.setPrintLevel(printlevel);
    m.optimizeConst(optimizeConst);

    if (timing_flag == 1) {
      begin = std::chrono::high_resolution_clock::now();
    }
    // m.hesse();

    m.minimize("Minuit2", "migrad");

    if (timing_flag == 1) {
      end = std::chrono::high_resolution_clock::now();

      float timing_s = std::chrono::duration_cast<std::chrono::nanoseconds>
                       (end-begin).count() / static_cast<float>(1e9);
      std::cout << timing_s << "s" << std::endl;

      outfile << "{\"full_minimize_wall_s\": \"" << timing_s
              << "\", \"pid\": \"" << getpid()
              << "\"}," << std::endl;
    }
  }
  if (timing_flag == 1) {
    outfile.close();
  }

  // print the "true" values for comparison
  std::cout << "--- values of PDF parameters used for data generation:"
            << std::endl;
  for (int ix = 0; ix < N_parameters/2; ++ix) {
    std::cout << "    gauss " << ix << ": m = " << mean[ix] << ", s = "
              << sigma[ix] << std::endl;
  }

  // --- Plot toy data and composite PDF overlaid ---
  TCanvas* c = new TCanvas("unbinned_scaling", "unbinned_scaling",
                           obs_plot_x_px, obs_plot_y_px);
  c->Divide(obs_plot_x, obs_plot_y);
  for (int ix = 0; ix < N_observables && ix < obs_plot_x * obs_plot_y; ++ix) {
    std::ostringstream os;
    os << "x" << ix;
    std::string s = os.str();
    RooPlot* frame = w.var(s.c_str())->frame();
    data->plotOn(frame);
    sum.plotOn(frame);
    c->cd(ix+1);
    frame->Draw();
  }
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: xmlfiltertabpagexslt.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: rt $ $Date: 2007-04-26 08:13:23 $
 *
 *  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_filter.hxx"

#ifndef _COM_SUN_STAR_FRAME_XCONFIGMANAGER_HPP_
#include <com/sun/star/frame/XConfigManager.hpp>
#endif

#include "com/sun/star/ui/dialogs/TemplateDescription.hpp"

#ifndef _FILEDLGHELPER_HXX
#include <sfx2/filedlghelper.hxx>
#endif

#ifndef _UNOTOOLS_LOCALFILEHELPER_HXX
#include <unotools/localfilehelper.hxx>
#endif

#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif

#ifndef SVTOOLS_URIHELPER_HXX
#include <svtools/urihelper.hxx>
#endif

#include "xmlfiltertabpagexslt.hxx"
#include "xmlfiltertabpagexslt.hrc"
#include "xmlfiltersettingsdialog.hxx"
#include "xmlfilterhelpids.hrc"

using namespace ::rtl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::frame;
using namespace ::com::sun::star::lang;

XMLFilterTabPageXSLT::XMLFilterTabPageXSLT( Window* pParent, ResMgr& rResMgr, const Reference< XMultiServiceFactory >& rxMSF ) :
    TabPage( pParent, ResId( RID_XML_FILTER_TABPAGE_XSLT, rResMgr ) ),

    maFTDocType( this, ResId( FT_XML_DOCTYPE, rResMgr ) ),
    maEDDocType( this, ResId( ED_XML_DOCTYPE, rResMgr ) ),

    maFTDTDSchema( this, ResId( FT_XML_DTD_SCHEMA, rResMgr ) ),
    maEDDTDSchema( this, ResId( ED_XML_DTD_SCHEMA, rResMgr ), INET_PROT_FILE ),
    maPBDTDSchemaBrowse( this, ResId( ED_XML_DTD_SCHEMA_BROWSE, rResMgr ) ),

    maFTExportXSLT( this, ResId( FT_XML_EXPORT_XSLT, rResMgr ) ),
    maEDExportXSLT( this, ResId( ED_XML_EXPORT_XSLT, rResMgr ), INET_PROT_FILE ),
    maPBExprotXSLT( this, ResId( PB_XML_EXPORT_XSLT_BROWSE, rResMgr ) ),

    maFTImportXSLT( this, ResId( FT_XML_IMPORT_XSLT, rResMgr ) ),
    maEDImportXSLT( this, ResId( ED_XML_IMPORT_XSLT, rResMgr ), INET_PROT_FILE ),
    maPBImportXSLT( this, ResId( PB_XML_IMPORT_XSLT_BROWSE, rResMgr ) ),

    maFTImportTemplate( this, ResId( FT_XML_IMPORT_TEMPLATE, rResMgr ) ),
    maEDImportTemplate( this, ResId( ED_XML_IMPORT_TEMPLATE, rResMgr ), INET_PROT_FILE ),
    maPBImportTemplate( this, ResId( PB_XML_IMPORT_TEMPLATE_BROWSE, rResMgr ) ),

    sHTTPSchema( RTL_CONSTASCII_USTRINGPARAM( "http://" ) ),
    sSHTTPSchema( RTL_CONSTASCII_USTRINGPARAM( "shttp://" ) ),
    sFILESchema( RTL_CONSTASCII_USTRINGPARAM( "file://" ) ),
    sFTPSchema( RTL_CONSTASCII_USTRINGPARAM( "ftp://" ) ),
    sInstPath( RTL_CONSTASCII_USTRINGPARAM( "$(prog)/" ) )
{
    FreeResource();

    try
    {
        Reference< XConfigManager > xCfgMgr( rxMSF->createInstance(OUString::createFromAscii("com.sun.star.config.SpecialConfigManager")), UNO_QUERY );
        if( xCfgMgr.is() )
            sInstPath = xCfgMgr->substituteVariables( sInstPath );
    }
    catch(Exception&)
    {
        DBG_ERROR( "XMLFilterTabPageXSLT::XMLFilterTabPageXSLT exception catched!" );
    }

    maPBDTDSchemaBrowse.SetClickHdl( LINK ( this, XMLFilterTabPageXSLT, ClickBrowseHdl_Impl ) );
    maPBExprotXSLT.SetClickHdl( LINK ( this, XMLFilterTabPageXSLT, ClickBrowseHdl_Impl ) );
    maPBImportXSLT.SetClickHdl( LINK ( this, XMLFilterTabPageXSLT, ClickBrowseHdl_Impl ) );
    maPBImportTemplate.SetClickHdl( LINK ( this, XMLFilterTabPageXSLT, ClickBrowseHdl_Impl ) );

    maEDDTDSchema.SetHelpId( HID_XML_FILTER_DTD );
    maEDExportXSLT.SetHelpId( HID_XML_FILTER_EXPORT_XSLT );
    maEDImportXSLT.SetHelpId( HID_XML_FILTER_IMPORT_XSLT );
    maEDImportTemplate.SetHelpId( HID_XML_FILTER_IMPORT_TEMPLATE );
}

XMLFilterTabPageXSLT::~XMLFilterTabPageXSLT()
{
}

bool XMLFilterTabPageXSLT::FillInfo( filter_info_impl* pInfo )
{
    if( pInfo )
    {
        pInfo->maDocType = maEDDocType.GetText();
        pInfo->maDTD = GetURL( maEDDTDSchema );
        pInfo->maExportXSLT = GetURL( maEDExportXSLT );
        pInfo->maImportXSLT = GetURL( maEDImportXSLT );
        pInfo->maImportTemplate = GetURL( maEDImportTemplate );
    }

    return true;
}

void XMLFilterTabPageXSLT::SetInfo(const filter_info_impl* pInfo)
{
    if( pInfo )
    {
        maEDDocType.SetText( pInfo->maDocType );

        SetURL( maEDDTDSchema, pInfo->maDTD );
        SetURL( maEDExportXSLT, pInfo->maExportXSLT );
        SetURL( maEDImportXSLT, pInfo->maImportXSLT );
        SetURL( maEDImportTemplate, pInfo->maImportTemplate );
    }
}

void XMLFilterTabPageXSLT::SetURL( SvtURLBox& rURLBox, const OUString& rURL )
{
    OUString aPath;

    if( rURL.matchIgnoreAsciiCase( OUString( RTL_CONSTASCII_USTRINGPARAM( "file://" ) ) ) )
    {
        osl::FileBase::getSystemPathFromFileURL( rURL, aPath );

        rURLBox.SetBaseURL( rURL );
        rURLBox.SetText( aPath );
    }
    else if( rURL.matchIgnoreAsciiCase( OUString( RTL_CONSTASCII_USTRINGPARAM( "http://" ) ) ) ||
             rURL.matchIgnoreAsciiCase( OUString( RTL_CONSTASCII_USTRINGPARAM( "shttp://" ) ) ) ||
             rURL.matchIgnoreAsciiCase( OUString( RTL_CONSTASCII_USTRINGPARAM( "ftp://" ) ) ) )
    {
        rURLBox.SetBaseURL( rURL );
        rURLBox.SetText( rURL );
    }
    else if( rURL.getLength() )
    {
        rtl::OUString aURL( rURL );
        aURL = URIHelper::SmartRel2Abs( sInstPath, aURL, Link(), false );
        osl::FileBase::getSystemPathFromFileURL( aURL, aPath );

        rURLBox.SetBaseURL( aURL );
        rURLBox.SetText( aPath );
    }
    else
    {
        rURLBox.SetBaseURL( sInstPath );
        String aEmpty;
        rURLBox.SetText( aEmpty );
    }
}

OUString XMLFilterTabPageXSLT::GetURL( SvtURLBox& rURLBox )
{
    OUString aURL;
    OUString aStrPath ( rURLBox.GetText() );
    if( aStrPath.matchIgnoreAsciiCase( OUString( RTL_CONSTASCII_USTRINGPARAM( "http://" ) ) ) ||
        aStrPath.matchIgnoreAsciiCase( OUString( RTL_CONSTASCII_USTRINGPARAM( "shttp://" ) ) ) ||
        aStrPath.matchIgnoreAsciiCase( OUString( RTL_CONSTASCII_USTRINGPARAM( "ftp://" ) ) ) )
    {
        return aStrPath;
    }
    else
    {
        const String aBaseURL ( rURLBox.GetBaseURL() );
        osl::FileBase::getFileURLFromSystemPath( aStrPath, aURL );
    }

    return aURL;
}

IMPL_LINK ( XMLFilterTabPageXSLT, ClickBrowseHdl_Impl, PushButton *, pButton )
{
    SvtURLBox* pURLBox;

    if( pButton == &maPBDTDSchemaBrowse )
    {
        pURLBox = &maEDDTDSchema;
    }
    else if( pButton == &maPBExprotXSLT )
    {
        pURLBox = &maEDExportXSLT;
    }
    else if( pButton == &maPBImportXSLT )
    {
        pURLBox = &maEDImportXSLT;
    }
    else
    {
        pURLBox = &maEDImportTemplate;
    }

    // Open Fileopen-Dialog
       ::sfx2::FileDialogHelper aDlg(
        com::sun::star::ui::dialogs::TemplateDescription::FILEOPEN_SIMPLE, 0 );

    aDlg.SetDisplayDirectory( GetURL( *pURLBox ) );

    if ( aDlg.Execute() == ERRCODE_NONE )
    {
        OUString aURL( aDlg.GetPath() );

        SetURL( *pURLBox, aURL );
    }

    return( 0L );
}

<commit_msg>INTEGRATION: CWS changefileheader (1.7.154); FILE MERGED 2008/04/01 15:16:02 thb 1.7.154.3: #i85898# Stripping all external header guards 2008/04/01 10:56:20 thb 1.7.154.2: #i85898# Stripping all external header guards 2008/03/28 15:32:01 rt 1.7.154.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: xmlfiltertabpagexslt.cxx,v $
 * $Revision: 1.8 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_filter.hxx"
#include <com/sun/star/frame/XConfigManager.hpp>

#include "com/sun/star/ui/dialogs/TemplateDescription.hpp"
#include <sfx2/filedlghelper.hxx>
#include <unotools/localfilehelper.hxx>
#include <osl/file.hxx>
#include <svtools/urihelper.hxx>

#include "xmlfiltertabpagexslt.hxx"
#include "xmlfiltertabpagexslt.hrc"
#include "xmlfiltersettingsdialog.hxx"
#include "xmlfilterhelpids.hrc"

using namespace ::rtl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::frame;
using namespace ::com::sun::star::lang;

XMLFilterTabPageXSLT::XMLFilterTabPageXSLT( Window* pParent, ResMgr& rResMgr, const Reference< XMultiServiceFactory >& rxMSF ) :
    TabPage( pParent, ResId( RID_XML_FILTER_TABPAGE_XSLT, rResMgr ) ),

    maFTDocType( this, ResId( FT_XML_DOCTYPE, rResMgr ) ),
    maEDDocType( this, ResId( ED_XML_DOCTYPE, rResMgr ) ),

    maFTDTDSchema( this, ResId( FT_XML_DTD_SCHEMA, rResMgr ) ),
    maEDDTDSchema( this, ResId( ED_XML_DTD_SCHEMA, rResMgr ), INET_PROT_FILE ),
    maPBDTDSchemaBrowse( this, ResId( ED_XML_DTD_SCHEMA_BROWSE, rResMgr ) ),

    maFTExportXSLT( this, ResId( FT_XML_EXPORT_XSLT, rResMgr ) ),
    maEDExportXSLT( this, ResId( ED_XML_EXPORT_XSLT, rResMgr ), INET_PROT_FILE ),
    maPBExprotXSLT( this, ResId( PB_XML_EXPORT_XSLT_BROWSE, rResMgr ) ),

    maFTImportXSLT( this, ResId( FT_XML_IMPORT_XSLT, rResMgr ) ),
    maEDImportXSLT( this, ResId( ED_XML_IMPORT_XSLT, rResMgr ), INET_PROT_FILE ),
    maPBImportXSLT( this, ResId( PB_XML_IMPORT_XSLT_BROWSE, rResMgr ) ),

    maFTImportTemplate( this, ResId( FT_XML_IMPORT_TEMPLATE, rResMgr ) ),
    maEDImportTemplate( this, ResId( ED_XML_IMPORT_TEMPLATE, rResMgr ), INET_PROT_FILE ),
    maPBImportTemplate( this, ResId( PB_XML_IMPORT_TEMPLATE_BROWSE, rResMgr ) ),

    sHTTPSchema( RTL_CONSTASCII_USTRINGPARAM( "http://" ) ),
    sSHTTPSchema( RTL_CONSTASCII_USTRINGPARAM( "shttp://" ) ),
    sFILESchema( RTL_CONSTASCII_USTRINGPARAM( "file://" ) ),
    sFTPSchema( RTL_CONSTASCII_USTRINGPARAM( "ftp://" ) ),
    sInstPath( RTL_CONSTASCII_USTRINGPARAM( "$(prog)/" ) )
{
    FreeResource();

    try
    {
        Reference< XConfigManager > xCfgMgr( rxMSF->createInstance(OUString::createFromAscii("com.sun.star.config.SpecialConfigManager")), UNO_QUERY );
        if( xCfgMgr.is() )
            sInstPath = xCfgMgr->substituteVariables( sInstPath );
    }
    catch(Exception&)
    {
        DBG_ERROR( "XMLFilterTabPageXSLT::XMLFilterTabPageXSLT exception catched!" );
    }

    maPBDTDSchemaBrowse.SetClickHdl( LINK ( this, XMLFilterTabPageXSLT, ClickBrowseHdl_Impl ) );
    maPBExprotXSLT.SetClickHdl( LINK ( this, XMLFilterTabPageXSLT, ClickBrowseHdl_Impl ) );
    maPBImportXSLT.SetClickHdl( LINK ( this, XMLFilterTabPageXSLT, ClickBrowseHdl_Impl ) );
    maPBImportTemplate.SetClickHdl( LINK ( this, XMLFilterTabPageXSLT, ClickBrowseHdl_Impl ) );

    maEDDTDSchema.SetHelpId( HID_XML_FILTER_DTD );
    maEDExportXSLT.SetHelpId( HID_XML_FILTER_EXPORT_XSLT );
    maEDImportXSLT.SetHelpId( HID_XML_FILTER_IMPORT_XSLT );
    maEDImportTemplate.SetHelpId( HID_XML_FILTER_IMPORT_TEMPLATE );
}

XMLFilterTabPageXSLT::~XMLFilterTabPageXSLT()
{
}

bool XMLFilterTabPageXSLT::FillInfo( filter_info_impl* pInfo )
{
    if( pInfo )
    {
        pInfo->maDocType = maEDDocType.GetText();
        pInfo->maDTD = GetURL( maEDDTDSchema );
        pInfo->maExportXSLT = GetURL( maEDExportXSLT );
        pInfo->maImportXSLT = GetURL( maEDImportXSLT );
        pInfo->maImportTemplate = GetURL( maEDImportTemplate );
    }

    return true;
}

void XMLFilterTabPageXSLT::SetInfo(const filter_info_impl* pInfo)
{
    if( pInfo )
    {
        maEDDocType.SetText( pInfo->maDocType );

        SetURL( maEDDTDSchema, pInfo->maDTD );
        SetURL( maEDExportXSLT, pInfo->maExportXSLT );
        SetURL( maEDImportXSLT, pInfo->maImportXSLT );
        SetURL( maEDImportTemplate, pInfo->maImportTemplate );
    }
}

void XMLFilterTabPageXSLT::SetURL( SvtURLBox& rURLBox, const OUString& rURL )
{
    OUString aPath;

    if( rURL.matchIgnoreAsciiCase( OUString( RTL_CONSTASCII_USTRINGPARAM( "file://" ) ) ) )
    {
        osl::FileBase::getSystemPathFromFileURL( rURL, aPath );

        rURLBox.SetBaseURL( rURL );
        rURLBox.SetText( aPath );
    }
    else if( rURL.matchIgnoreAsciiCase( OUString( RTL_CONSTASCII_USTRINGPARAM( "http://" ) ) ) ||
             rURL.matchIgnoreAsciiCase( OUString( RTL_CONSTASCII_USTRINGPARAM( "shttp://" ) ) ) ||
             rURL.matchIgnoreAsciiCase( OUString( RTL_CONSTASCII_USTRINGPARAM( "ftp://" ) ) ) )
    {
        rURLBox.SetBaseURL( rURL );
        rURLBox.SetText( rURL );
    }
    else if( rURL.getLength() )
    {
        rtl::OUString aURL( rURL );
        aURL = URIHelper::SmartRel2Abs( sInstPath, aURL, Link(), false );
        osl::FileBase::getSystemPathFromFileURL( aURL, aPath );

        rURLBox.SetBaseURL( aURL );
        rURLBox.SetText( aPath );
    }
    else
    {
        rURLBox.SetBaseURL( sInstPath );
        String aEmpty;
        rURLBox.SetText( aEmpty );
    }
}

OUString XMLFilterTabPageXSLT::GetURL( SvtURLBox& rURLBox )
{
    OUString aURL;
    OUString aStrPath ( rURLBox.GetText() );
    if( aStrPath.matchIgnoreAsciiCase( OUString( RTL_CONSTASCII_USTRINGPARAM( "http://" ) ) ) ||
        aStrPath.matchIgnoreAsciiCase( OUString( RTL_CONSTASCII_USTRINGPARAM( "shttp://" ) ) ) ||
        aStrPath.matchIgnoreAsciiCase( OUString( RTL_CONSTASCII_USTRINGPARAM( "ftp://" ) ) ) )
    {
        return aStrPath;
    }
    else
    {
        const String aBaseURL ( rURLBox.GetBaseURL() );
        osl::FileBase::getFileURLFromSystemPath( aStrPath, aURL );
    }

    return aURL;
}

IMPL_LINK ( XMLFilterTabPageXSLT, ClickBrowseHdl_Impl, PushButton *, pButton )
{
    SvtURLBox* pURLBox;

    if( pButton == &maPBDTDSchemaBrowse )
    {
        pURLBox = &maEDDTDSchema;
    }
    else if( pButton == &maPBExprotXSLT )
    {
        pURLBox = &maEDExportXSLT;
    }
    else if( pButton == &maPBImportXSLT )
    {
        pURLBox = &maEDImportXSLT;
    }
    else
    {
        pURLBox = &maEDImportTemplate;
    }

    // Open Fileopen-Dialog
       ::sfx2::FileDialogHelper aDlg(
        com::sun::star::ui::dialogs::TemplateDescription::FILEOPEN_SIMPLE, 0 );

    aDlg.SetDisplayDirectory( GetURL( *pURLBox ) );

    if ( aDlg.Execute() == ERRCODE_NONE )
    {
        OUString aURL( aDlg.GetPath() );

        SetURL( *pURLBox, aURL );
    }

    return( 0L );
}

<|endoftext|>