<commit_before>/*************************************************************************
 *
 *  $RCSfile: dp_ucb.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2004-08-12 12:09:14 $
 *
 *  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: 2002 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include "dp_misc.hrc"
#include "dp_misc.h"
#include "dp_ucb.h"
#include "rtl/uri.hxx"
#include "rtl/ustrbuf.hxx"
#include "ucbhelper/content.hxx"
#include "xmlscript/xml_helper.hxx"
#include "com/sun/star/io/XInputStream.hpp"
#include "com/sun/star/ucb/CommandFailedException.hpp"
#include "com/sun/star/ucb/XContentCreator.hpp"
#include "com/sun/star/ucb/ContentInfo.hpp"
#include "com/sun/star/ucb/ContentInfoAttribute.hpp"

using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::ucb;
using ::rtl::OUString;

namespace dp_misc
{

//==============================================================================
bool create_ucb_content(
    ::ucb::Content * ret_ucbContent, OUString const & url,
    Reference<XCommandEnvironment> const & xCmdEnv,
    bool throw_exc )
{
    try {
        // dilemma: no chance to use the given iahandler here, because it would
        //          raise no such file dialogs, else no interaction for
        //          passwords, ...? xxx todo
        ::ucb::Content ucbContent( url, Reference<XCommandEnvironment>() );
        if (! ucbContent.isFolder())
            ucbContent.openStream()->closeInput();
        if (ret_ucbContent != 0)
            *ret_ucbContent = ::ucb::Content( url, xCmdEnv );
        return true;
    }
    catch (RuntimeException &) {
        throw;
    }
    catch (Exception &) {
        if (throw_exc)
            throw;
    }
    return false;
}

//==============================================================================
bool create_folder(
    ::ucb::Content * ret_ucb_content, OUString const & url_,
    Reference<XCommandEnvironment> const & xCmdEnv, bool throw_exc )
{
    ::ucb::Content ucb_content;
    if (create_ucb_content(
            &ucb_content, url_, xCmdEnv, false /* no throw */ ))
    {
        if (ucb_content.isFolder())
        {
            if (ret_ucb_content != 0)
                *ret_ucb_content = ucb_content;
            return true;
        }
    }

    OUString url( url_ );
    // xxx todo: find parent
    sal_Int32 slash = url.lastIndexOf( '/' );
    if (slash < 0) {
        // fallback:
        url = expand_url( url );
        slash = url.lastIndexOf( '/' );
    }
    ::ucb::Content parentContent;
    if (! create_folder(
            &parentContent, url.copy( 0, slash ), xCmdEnv, throw_exc ))
        return false;
    Reference<XContentCreator> xCreator( parentContent.get(), UNO_QUERY );
    if (xCreator.is())
    {
        OUString strTitle( RTL_CONSTASCII_USTRINGPARAM( "Title" ) );
        Any title( makeAny( ::rtl::Uri::decode( url.copy( slash + 1 ),
                                                rtl_UriDecodeWithCharset,
                                                RTL_TEXTENCODING_UTF8 ) ) );

        Sequence<ContentInfo> infos( xCreator->queryCreatableContentsInfo() );
        for ( sal_Int32 pos = 0; pos < infos.getLength(); ++pos )
        {
            // look KIND_FOLDER:
            ContentInfo const & info = infos[ pos ];
            if ((info.Attributes & ContentInfoAttribute::KIND_FOLDER) != 0)
            {
                // make sure the only required bootstrap property is "Title":
                Sequence<beans::Property> const & rProps = info.Properties;
                if (rProps.getLength() != 1 ||
                    !rProps[ 0 ].Name.equalsAsciiL(
                        RTL_CONSTASCII_STRINGPARAM("Title") ))
                    continue;

                try {
                    if (parentContent.insertNewContent(
                            info.Type,
                            Sequence<OUString>( &strTitle, 1 ),
                            Sequence<Any>( &title, 1 ),
                            ucb_content )) {
                        if (ret_ucb_content != 0)
                            *ret_ucb_content = ucb_content;
                        return true;
                    }
                }
                catch (RuntimeException &) {
                    throw;
                }
                catch (CommandFailedException &) {
                    // Interaction Handler already handled the error
                    // that has occured...
                }
                catch (Exception &) {
                    if (throw_exc)
                        throw;
                    return false;
                }
            }
        }
    }
    if (throw_exc)
        throw ContentCreationException(
            OUSTR("Cannot create folder: ") + url,
            Reference<XInterface>(), ContentCreationError_UNKNOWN );
    return false;
}

//==============================================================================
bool erase_path( OUString const & url,
                 Reference<XCommandEnvironment> const & xCmdEnv,
                 bool throw_exc )
{
    ::ucb::Content ucb_content;
    if (create_ucb_content( &ucb_content, url, xCmdEnv, false /* no throw */ ))
    {
        try {
            ucb_content.executeCommand(
                OUSTR("delete"), makeAny( true /* delete physically */ ) );
        }
        catch (RuntimeException &) {
            throw;
        }
        catch (Exception &) {
            if (throw_exc)
                throw;
            return false;
        }
    }
    return true;
}

//==============================================================================
::rtl::ByteSequence readFile( ::ucb::Content & ucb_content )
{
    ::rtl::ByteSequence bytes;
    Reference<io::XOutputStream> xStream(
        ::xmlscript::createOutputStream( &bytes ) );
    if (! ucb_content.openStream( xStream ))
        throw RuntimeException(
            OUSTR("::ucb::Content::openStream( XOutputStream ) failed!"), 0 );
    return bytes;
}

//==============================================================================
bool readLine( OUString * res, OUString const & startingWith,
               ::ucb::Content & ucb_content, rtl_TextEncoding textenc )
{
    // read whole file:
    ::rtl::ByteSequence bytes( readFile( ucb_content ) );
    OUString file( reinterpret_cast<sal_Char const *>(bytes.getConstArray()),
                   bytes.getLength(), textenc );
    sal_Int32 pos = 0;
    for (;;)
    {
        if (file.match( startingWith, pos ))
        {
            ::rtl::OUStringBuffer buf;
            sal_Int32 start = pos;
            pos += startingWith.getLength();
            for (;;)
            {
                pos = file.indexOf( LF, pos );
                if (pos < 0) { // EOF
                    buf.append( file.copy( start ) );
                }
                else
                {
                    if (pos > 0 && file[ pos - 1 ] == CR)
                    {
                        // consume extra CR
                        buf.append( file.copy( start, pos - start - 1 ) );
                        ++pos;
                    }
                    else
                        buf.append( file.copy( start, pos - start ) );
                    ++pos; // consume LF
                    // check next line:
                    if (pos < file.getLength() &&
                        (file[ pos ] == ' ' || file[ pos ] == '\t'))
                    {
                        buf.append( static_cast<sal_Unicode>(' ') );
                        ++pos;
                        start = pos;
                        continue;
                    }
                }
                break;
            }
            *res = buf.makeStringAndClear();
            return true;
        }
        // next line:
        sal_Int32 next_lf = file.indexOf( LF, pos );
        if (next_lf < 0) // EOF
            break;
        pos = next_lf + 1;
    }
    return false;
}

}
<commit_msg>INTEGRATION: CWS jl13 (1.4.12); FILE MERGED 2004/10/15 12:48:58 dbo 1.4.12.3: #i35536##i34555##i34149# - rc files without vnd.sun.star.expand urls - export file picker filter - reinstall cleans xlc files - minor improvements Issue number: Submitted by: Reviewed by: 2004/09/30 16:53:54 dbo 1.4.12.2: #i34555# correct double checked locking, misc cleanup 2004/09/14 15:31:44 dbo 1.4.12.1: #i34149##i33982# modified makeURL(), misc fixes<commit_after>/*************************************************************************
 *
 *  $RCSfile: dp_ucb.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: hr $ $Date: 2004-11-09 14:10:17 $
 *
 *  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: 2002 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include "dp_misc.hrc"
#include "dp_misc.h"
#include "dp_ucb.h"
#include "rtl/uri.hxx"
#include "rtl/ustrbuf.hxx"
#include "ucbhelper/content.hxx"
#include "xmlscript/xml_helper.hxx"
#include "com/sun/star/io/XInputStream.hpp"
#include "com/sun/star/ucb/CommandFailedException.hpp"
#include "com/sun/star/ucb/XContentCreator.hpp"
#include "com/sun/star/ucb/ContentInfo.hpp"
#include "com/sun/star/ucb/ContentInfoAttribute.hpp"

using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::ucb;
using ::rtl::OUString;

namespace dp_misc
{

//==============================================================================
bool create_ucb_content(
    ::ucb::Content * ret_ucbContent, OUString const & url,
    Reference<XCommandEnvironment> const & xCmdEnv,
    bool throw_exc )
{
    try {
        // dilemma: no chance to use the given iahandler here, because it would
        //          raise no such file dialogs, else no interaction for
        //          passwords, ...? xxx todo
        ::ucb::Content ucbContent( url, Reference<XCommandEnvironment>() );
        if (! ucbContent.isFolder())
            ucbContent.openStream()->closeInput();
        if (ret_ucbContent != 0)
            *ret_ucbContent = ::ucb::Content( url, xCmdEnv );
        return true;
    }
    catch (RuntimeException &) {
        throw;
    }
    catch (Exception &) {
        if (throw_exc)
            throw;
    }
    return false;
}

//==============================================================================
bool create_folder(
    ::ucb::Content * ret_ucb_content, OUString const & url_,
    Reference<XCommandEnvironment> const & xCmdEnv, bool throw_exc )
{
    ::ucb::Content ucb_content;
    if (create_ucb_content(
            &ucb_content, url_, xCmdEnv, false /* no throw */ ))
    {
        if (ucb_content.isFolder()) {
            if (ret_ucb_content != 0)
                *ret_ucb_content = ucb_content;
            return true;
        }
    }

    OUString url( url_ );
    // xxx todo: find parent
    sal_Int32 slash = url.lastIndexOf( '/' );
    if (slash < 0) {
        // fallback:
        url = expandUnoRcUrl( url );
        slash = url.lastIndexOf( '/' );
    }
    ::ucb::Content parentContent;
    if (! create_folder(
            &parentContent, url.copy( 0, slash ), xCmdEnv, throw_exc ))
        return false;
    Reference<XContentCreator> xCreator( parentContent.get(), UNO_QUERY );
    if (xCreator.is())
    {
        Any title( makeAny( ::rtl::Uri::decode( url.copy( slash + 1 ),
                                                rtl_UriDecodeWithCharset,
                                                RTL_TEXTENCODING_UTF8 ) ) );

        Sequence<ContentInfo> infos( xCreator->queryCreatableContentsInfo() );
        for ( sal_Int32 pos = 0; pos < infos.getLength(); ++pos )
        {
            // look KIND_FOLDER:
            ContentInfo const & info = infos[ pos ];
            if ((info.Attributes & ContentInfoAttribute::KIND_FOLDER) != 0)
            {
                // make sure the only required bootstrap property is "Title":
                Sequence<beans::Property> const & rProps = info.Properties;
                if (rProps.getLength() != 1 ||
                    !rProps[ 0 ].Name.equalsAsciiL(
                        RTL_CONSTASCII_STRINGPARAM("Title") ))
                    continue;

                try {
                    if (parentContent.insertNewContent(
                            info.Type,
                            Sequence<OUString>( &StrTitle::get(), 1 ),
                            Sequence<Any>( &title, 1 ),
                            ucb_content )) {
                        if (ret_ucb_content != 0)
                            *ret_ucb_content = ucb_content;
                        return true;
                    }
                }
                catch (RuntimeException &) {
                    throw;
                }
                catch (CommandFailedException &) {
                    // Interaction Handler already handled the error
                    // that has occured...
                }
                catch (Exception &) {
                    if (throw_exc)
                        throw;
                    return false;
                }
            }
        }
    }
    if (throw_exc)
        throw ContentCreationException(
            OUSTR("Cannot create folder: ") + url,
            Reference<XInterface>(), ContentCreationError_UNKNOWN );
    return false;
}

//==============================================================================
bool erase_path( OUString const & url,
                 Reference<XCommandEnvironment> const & xCmdEnv,
                 bool throw_exc )
{
    ::ucb::Content ucb_content;
    if (create_ucb_content( &ucb_content, url, xCmdEnv, false /* no throw */ ))
    {
        try {
            ucb_content.executeCommand(
                OUSTR("delete"), makeAny( true /* delete physically */ ) );
        }
        catch (RuntimeException &) {
            throw;
        }
        catch (Exception &) {
            if (throw_exc)
                throw;
            return false;
        }
    }
    return true;
}

//==============================================================================
::rtl::ByteSequence readFile( ::ucb::Content & ucb_content )
{
    ::rtl::ByteSequence bytes;
    Reference<io::XOutputStream> xStream(
        ::xmlscript::createOutputStream( &bytes ) );
    if (! ucb_content.openStream( xStream ))
        throw RuntimeException(
            OUSTR("::ucb::Content::openStream( XOutputStream ) failed!"), 0 );
    return bytes;
}

//==============================================================================
bool readLine( OUString * res, OUString const & startingWith,
               ::ucb::Content & ucb_content, rtl_TextEncoding textenc )
{
    // read whole file:
    ::rtl::ByteSequence bytes( readFile( ucb_content ) );
    OUString file( reinterpret_cast<sal_Char const *>(bytes.getConstArray()),
                   bytes.getLength(), textenc );
    sal_Int32 pos = 0;
    for (;;)
    {
        if (file.match( startingWith, pos ))
        {
            ::rtl::OUStringBuffer buf;
            sal_Int32 start = pos;
            pos += startingWith.getLength();
            for (;;)
            {
                pos = file.indexOf( LF, pos );
                if (pos < 0) { // EOF
                    buf.append( file.copy( start ) );
                }
                else
                {
                    if (pos > 0 && file[ pos - 1 ] == CR)
                    {
                        // consume extra CR
                        buf.append( file.copy( start, pos - start - 1 ) );
                        ++pos;
                    }
                    else
                        buf.append( file.copy( start, pos - start ) );
                    ++pos; // consume LF
                    // check next line:
                    if (pos < file.getLength() &&
                        (file[ pos ] == ' ' || file[ pos ] == '\t'))
                    {
                        buf.append( static_cast<sal_Unicode>(' ') );
                        ++pos;
                        start = pos;
                        continue;
                    }
                }
                break;
            }
            *res = buf.makeStringAndClear();
            return true;
        }
        // next line:
        sal_Int32 next_lf = file.indexOf( LF, pos );
        if (next_lf < 0) // EOF
            break;
        pos = next_lf + 1;
    }
    return false;
}

}
<|endoftext|>


<commit_before>/**
 *	\author    John Szwast
 *	\year      2014-2016
 *	\copyright MIT
 */

#pragma once

#include <mutex>
#include <type_traits>
#include <utility>

/**
 * \brief MemoizedMember is a C++ class that caches the result of a computation.
 *
 * \details
 *  If your class `A` has an attribute `b` with a value you want to memoize:
 *
 * 1. Write a `private`, `const` computation method, `type compute_b() const`.
 *
 * 2. Add a `MemoizedMember` member using the computation method.
 *
 * 3. Write a `public` getter for the `MemoizedMember`, `type get_b() const`.
 *
 * Here is an example memoizing an `int` type attribute.
 *
 *     class A
 *     {
 *       public:
 *         int get_b() const {return b;}
 *       private:
 *         int compute_b() const;
 *         MemoizedMember<int, A, &A::compute_b> b{*this};
 *     };
 */
template<typename Key, class Class, Key (Class::*evaluate) () const>
class MemoizedMember
{
  public:
    /**
     * \brief  "Default" constructor
     * \param[in]  instance  The Class instance in which *this is a member
     * \remarks  We require a reference to the Class of which we are a member.
     */
    MemoizedMember (Class const& instance)
    noexcept (std::is_nothrow_default_constructible<Key>::value)
      : m_instance (instance)
    {
    }

    /**
    * \brief  "Copy" constructor
    * \param[in]  instance  The Class instance in which *this is a member
    * \param[in]  r         The source of the copy
    * \remarks  We require a reference to the Class of which we are a member.
    *   We do not want to copy the reference to the class of which `r` is a member.
    */
    MemoizedMember (Class const& instance, const MemoizedMember& r)
    noexcept (std::is_nothrow_copy_constructible<Key>::value)
      : m_instance (instance)
      , m_value (r.m_value)
      , m_valid (r.m_valid)
    {
    }

    /**
    * \brief  "Move" constructor
    * \param[in]  instance  The Class instance in which *this is a member
    * \param[in]  r         The source of the copy
    * \remarks  We require a reference to the Class of which we are a member.
    *   We do not want to copy the reference to the class of which `r` is a member.
    */
    MemoizedMember (Class const& instance, MemoizedMember && r)
    noexcept (std::is_nothrow_move_constructible<Key>::value)
      : m_instance (instance)
      , m_value (std::move (r.m_value))
      , m_valid (r.m_valid)
    {
    }

    MemoizedMember(const MemoizedMember&) = delete;
    MemoizedMember(MemoizedMember&&) = delete;
    ~MemoizedMember() = default;

    /**
     * A memoized member should be affiliated with an object.  If that object is being
     * assigned we want to copy the memoization state, but m_instance shouldn't change.
     *
     * Basic exception guarantee: if copying the memoized value throws, then the memoization
     * will be cleared and recalculated on the next request.
     */
    MemoizedMember& operator= (const MemoizedMember& r)
    {
      std::lock_guard<std::mutex> guard(m_lock);

      m_valid = false;
      m_value = r.m_value;
      m_valid = r.m_valid;
      return *this;
    }

    /**
     * A memoized member should be affiliated with an object.  If that object is being
     * (move) assigned we want to move the memoization state, but m_instance shouldn't change.
     *
     * Basic exception guarantee: if moving the memoized value throws, then the memoization
     * will be cleared and recalculated on the next request.
     */
    MemoizedMember& operator= (const MemoizedMember && r)
    {
      std::lock_guard<std::mutex> guard(m_lock);

      m_valid = false;
      m_value = std::move (r.m_value);
      m_valid = r.m_valid;
      return *this;
    }

    /**
     * \brief Key conversion operator.
     *
     * \details
     *  This is the meat of this class.  This is how the MemoizedMember behaves like a Key object.
     * If the value has not yet been calculated, then calculate it.
     *
     * \returns	The memoized value.
     *
     * \remarks
     * Strong exception guarantee:  If the calculation of the value to be memoized fails, then
     * it will be reattempted next time.
     */
    operator Key() const
    {
      std::lock_guard<std::mutex> guard(m_lock);

      if (!m_valid)
      {
        m_value = (m_instance.*evaluate) ();
        m_valid = true;
      }

      return m_value;
    }

    /**
     * If the owning object is mutated in a way that should change the value of the memoized
     * member, then reset() it.  After reset(), a re-computation will occur the next time the value
     * of the member is requested.
     */
    void reset() noexcept { m_valid = false; }

  private:
    Class const& m_instance;
    mutable Key m_value {};
    mutable bool m_valid {false};
    mutable std::mutex m_lock;
};
<commit_msg>Fixes #5.  Make the mutex type a template parameter.<commit_after>/**
 *	\author    John Szwast
 *	\year      2014-2016
 *	\copyright MIT
 */

#pragma once

#include <mutex>
#include <type_traits>
#include <utility>

/**
 * \brief MemoizedMember is a C++ class that caches the result of a computation.
 *
 * \details
 *  If your class `A` has an attribute `b` with a value you want to memoize:
 *
 * 1. Write a `private`, `const` computation method, `type compute_b() const`.
 *
 * 2. Add a `MemoizedMember` member using the computation method.
 *
 * 3. Write a `public` getter for the `MemoizedMember`, `type get_b() const`.
 *
 * Here is an example memoizing an `int` type attribute.
 *
 *     class A
 *     {
 *       public:
 *         int get_b() const {return b;}
 *       private:
 *         int compute_b() const;
 *         MemoizedMember<int, A, &A::compute_b> b{*this};
 *     };
 */
template<typename Key, class Class, Key (Class::*evaluate) () const, typename Mutex = std::mutex>
class MemoizedMember
{
  public:
    /**
     * \brief  "Default" constructor
     * \param[in]  instance  The Class instance in which *this is a member
     * \remarks  We require a reference to the Class of which we are a member.
     */
    MemoizedMember (Class const& instance)
    noexcept (std::is_nothrow_default_constructible<Key>::value)
      : m_instance (instance)
    {
    }

    /**
    * \brief  "Copy" constructor
    * \param[in]  instance  The Class instance in which *this is a member
    * \param[in]  r         The source of the copy
    * \remarks  We require a reference to the Class of which we are a member.
    *   We do not want to copy the reference to the class of which `r` is a member.
    */
    MemoizedMember (Class const& instance, const MemoizedMember& r)
    noexcept (std::is_nothrow_copy_constructible<Key>::value)
      : m_instance (instance)
      , m_value (r.m_value)
      , m_valid (r.m_valid)
    {
    }

    /**
    * \brief  "Move" constructor
    * \param[in]  instance  The Class instance in which *this is a member
    * \param[in]  r         The source of the copy
    * \remarks  We require a reference to the Class of which we are a member.
    *   We do not want to copy the reference to the class of which `r` is a member.
    */
    MemoizedMember (Class const& instance, MemoizedMember && r)
    noexcept (std::is_nothrow_move_constructible<Key>::value)
      : m_instance (instance)
      , m_value (std::move (r.m_value))
      , m_valid (r.m_valid)
    {
    }

    MemoizedMember(const MemoizedMember&) = delete;
    MemoizedMember(MemoizedMember&&) = delete;
    ~MemoizedMember() = default;

    /**
     * A memoized member should be affiliated with an object.  If that object is being
     * assigned we want to copy the memoization state, but m_instance shouldn't change.
     *
     * Basic exception guarantee: if copying the memoized value throws, then the memoization
     * will be cleared and recalculated on the next request.
     */
    MemoizedMember& operator= (const MemoizedMember& r)
    {
      std::lock_guard<Mutex> guard(m_lock);

      m_valid = false;
      m_value = r.m_value;
      m_valid = r.m_valid;
      return *this;
    }

    /**
     * A memoized member should be affiliated with an object.  If that object is being
     * (move) assigned we want to move the memoization state, but m_instance shouldn't change.
     *
     * Basic exception guarantee: if moving the memoized value throws, then the memoization
     * will be cleared and recalculated on the next request.
     */
    MemoizedMember& operator= (const MemoizedMember && r)
    {
      std::lock_guard<Mutex> guard(m_lock);

      m_valid = false;
      m_value = std::move (r.m_value);
      m_valid = r.m_valid;
      return *this;
    }

    /**
     * \brief Key conversion operator.
     *
     * \details
     *  This is the meat of this class.  This is how the MemoizedMember behaves like a Key object.
     * If the value has not yet been calculated, then calculate it.
     *
     * \returns	The memoized value.
     *
     * \remarks
     * Strong exception guarantee:  If the calculation of the value to be memoized fails, then
     * it will be reattempted next time.
     */
    operator Key() const
    {
      std::lock_guard<Mutex> guard(m_lock);

      if (!m_valid)
      {
        m_value = (m_instance.*evaluate) ();
        m_valid = true;
      }

      return m_value;
    }

    /**
     * If the owning object is mutated in a way that should change the value of the memoized
     * member, then reset() it.  After reset(), a re-computation will occur the next time the value
     * of the member is requested.
     */
    void reset() noexcept { m_valid = false; }

  private:
    Class const& m_instance;
    mutable Key m_value {};
    mutable bool m_valid {false};
    mutable Mutex m_lock;
};
<|endoftext|>


<commit_before>#include <boost/algorithm/string.hpp>
#include <functional>
#include <string>
#include <vector>
#include <map>
#include "collectfunctions.h"
#include "vvvptreehelper.hpp"
#include "myparamnames.hpp"

using namespace clang;

std::string
getDoxyBrief(const ASTContext& ctx, const RawComment* comment)
{
    return comment ? comment->getBriefText(ctx)
                   : "";
}

/**
 * Return strings of doxygen comment without comment opening and closing.
 * From eahch line also removed decoration * from begining if exist */
std::vector<std::string> removeDecorations(const std::string& str)
{
    using namespace boost::algorithm;
    std::vector<std::string> ret;
    auto docstring = erase_tail_copy(erase_head_copy(str,3), 2);
    split(ret, docstring, is_any_of("\n"), token_compress_on);
    std::transform( ret.begin(), ret.end(), ret.begin(),
                    [](const auto& str)
                    { return boost::algorithm::trim_copy(str);} );
    std::transform( ret.begin(), ret.end(), ret.begin(),
                    [](const auto& str)
                    { return str[0]=='*' ? erase_head_copy(str,1)
                                         : str; } );
    return ret;
}

std::vector<std::string> splitToTrimmedWords(const std::string& str)
{
    using namespace boost::algorithm;
    std::vector<std::string> splited;

    split(splited, str, is_any_of(" \t"), token_compress_on );
    return filter(splited, [](const auto& str) {return !str.empty();});
}

/**
 * Function join elements from 'c' using sep omitting n first elements.
 * @param c container
 * @param n number of head elements to exclude
 * @param sep separator to insert
 */
template<class T, typename S>
auto joinTail(const T& c, size_t n, const S& sep)
{
    const auto& tail = std::vector<std::string>(c.begin() + n, c.end());
    const auto& comment = boost::algorithm::join(tail, sep);
    return comment;
}

std::map<std::string, std::string>
getDoxyParams(const ASTContext& ctx, const RawComment* rawcomment)
{
    using namespace boost::algorithm;
    std::map<std::string, std::string> ret;
    if(rawcomment == nullptr) return ret;

    const SourceManager& sm = ctx.getSourceManager();
    const auto& text = rawcomment->getRawText(sm).str();
    const auto& lines = removeDecorations(text);

    static const auto paramTags = {"@param", "\\param"};
    static const auto returnTags = {"@return", "\\return"};

    for(const auto& l: lines)
    {
        const auto words = splitToTrimmedWords(l);
        const size_t splitedsize = words.size();
        if(splitedsize < 2) continue;

        const auto& Tag = words[0];
        if(contain(paramTags, Tag) && splitedsize>2)
        {
            const auto& paramName = words[1];
            const auto& comment = joinTail(words, 2, " ");
            ret[paramName] = comment;
        }
        else if(contain(returnTags, Tag))
        {
            const auto& comment = joinTail(words, 1, " ");
            ret["return"] = comment;
        }
    }

    return ret;
}

void printFunctionDecls(clang::ASTContext& Context,
                        boost::property_tree::ptree& tree,
                        const printFunctionsParam& params)
{
    const auto declsInMain = contain(params, PARAM_NAME_MAIN_ONLY)
                            ? getMainFileDeclarations(Context)
                            : getNonSystemDeclarations(Context);
    const auto functionsDecls = filterFunctions(declsInMain);
    using boost::property_tree::ptree;

    for(const auto& d: functionsDecls)
    {
        using namespace std;
        const auto& fs = getFunctionParams( d );
        ptree functiondesc;
        ptree params;
        const RawComment* rc = Context.getRawCommentForDeclNoCache(d);
        const auto& brief    = getDoxyBrief(Context, rc);
        auto paramsComments  = getDoxyParams(Context, rc);
        for(const auto& f: fs) {
            const auto& name = f->getNameAsString();
            const auto& t    = f->getType().getAsString();
            //const auto& comment = getComment((Decl*)f);
            ptree param;
            ptree_add_value(param, "param", name);
            ptree_add_value(param, "type", t);
            const std::string& comment = paramsComments.count(name) ?
                                         paramsComments[name] :
                                         "";
            ptree_add_value(param, "comment", comment);
            ptree_array_add_node(params, param);
        }
        const auto functionName = d->getName().str();

        ptree_add_value(functiondesc, "name", functionName);
        ptree_add_value(functiondesc, "retval", d->getReturnType().getAsString() );
        ptree_add_value(functiondesc, "retcomment", paramsComments["return"]);
        ptree_add_value(functiondesc, "comment", brief);
        if(!fs.empty())
            ptree_add_subnode(functiondesc, "params", params);
        ptree_array_add_node(tree, functiondesc);
    }
}

<commit_msg>refactoring<commit_after>#include <boost/algorithm/string.hpp>
#include <functional>
#include <string>
#include <vector>
#include <map>
#include "collectfunctions.h"
#include "vvvptreehelper.hpp"
#include "myparamnames.hpp"

using namespace clang;

std::string
getDoxyBrief(const ASTContext& ctx, const RawComment* comment)
{
    return comment ? comment->getBriefText(ctx)
                   : "";
}

/**
 * Return strings of doxygen comment without comment opening and closing.
 * From eahch line also removed decoration * from begining if exist */
std::vector<std::string> removeDecorations(const std::string& str)
{
    using namespace boost::algorithm;
    std::vector<std::string> ret;
    auto docstring = erase_tail_copy(erase_head_copy(str,3), 2);
    split(ret, docstring, is_any_of("\n"), token_compress_on);
    std::transform( ret.begin(), ret.end(), ret.begin(),
                    [](const auto& str)
                    { return boost::algorithm::trim_copy(str);} );
    std::transform( ret.begin(), ret.end(), ret.begin(),
                    [](const auto& str)
                    { return str[0]=='*' ? erase_head_copy(str,1)
                                         : str; } );
    return ret;
}

std::vector<std::string> splitToTrimmedWords(const std::string& str)
{
    using namespace boost::algorithm;
    std::vector<std::string> splited;

    split(splited, str, is_any_of(" \t"), token_compress_on );
    return filter(splited, [](const auto& str) {return !str.empty();});
}

/**
 * Function join elements from 'c' using sep omitting n first elements.
 * @param c container
 * @param n number of head elements to exclude
 * @param sep separator to insert
 */
template<class T, typename S>
auto joinTail(const T& c, size_t n, const S& sep)
{
    const auto& tail = std::vector<std::string>(c.begin() + n, c.end());
    const auto& comment = boost::algorithm::join(tail, sep);
    return comment;
}

std::map<std::string, std::string>
getDoxyParams(const ASTContext& ctx, const RawComment* rawcomment)
{
    using namespace boost::algorithm;
    std::map<std::string, std::string> ret;
    if(rawcomment == nullptr) return ret;

    const SourceManager& sm = ctx.getSourceManager();
    const auto& text = rawcomment->getRawText(sm).str();
    const auto& lines = removeDecorations(text);

    static const auto paramTags = {"@param", "\\param"};
    static const auto returnTags = {"@return", "\\return"};

    for(const auto& l: lines)
    {
        const auto words = splitToTrimmedWords(l);
        const size_t splitedsize = words.size();
        if(splitedsize < 2) continue;

        const auto& Tag = words[0];
        if(contain(paramTags, Tag) && splitedsize>2)
        {
            const auto& paramName = words[1];
            const auto& comment = joinTail(words, 2, " ");
            ret[paramName] = comment;
        }
        else if(contain(returnTags, Tag))
        {
            const auto& comment = joinTail(words, 1, " ");
            ret["return"] = comment;
        }
    }

    return ret;
}

void printFunctionDecls(clang::ASTContext& Context,
                        boost::property_tree::ptree& tree,
                        const printFunctionsParam& params)
{
    const auto declsInMain = contain(params, PARAM_NAME_MAIN_ONLY)
                            ? getMainFileDeclarations(Context)
                            : getNonSystemDeclarations(Context);
    const auto functionsDecls = filterFunctions(declsInMain);
    using boost::property_tree::ptree;

    for(const auto& d: functionsDecls)
    {
        using namespace std;
        ptree functiondesc;
        ptree params;
        const RawComment* rc = Context.getRawCommentForDeclNoCache(d);
        const auto& brief    = getDoxyBrief(Context, rc);
        auto paramsComments  = getDoxyParams(Context, rc);
        const auto& paramDecls = getFunctionParams( d );
        for(const auto& f: paramDecls) {
            const auto& name = f->getNameAsString();
            const auto& t    = f->getType().getAsString();
            ptree param;
            ptree_add_value(param, "param", name);
            ptree_add_value(param, "type", t);
            const std::string& comment = paramsComments.count(name) ?
                                         paramsComments[name] :
                                         "";
            ptree_add_value(param, "comment", comment);
            ptree_array_add_node(params, param);
        }
        const auto functionName = d->getName().str();

        ptree_add_value(functiondesc, "name", functionName);
        ptree_add_value(functiondesc, "retval", d->getReturnType().getAsString() );
        ptree_add_value(functiondesc, "retcomment", paramsComments["return"]);
        ptree_add_value(functiondesc, "comment", brief);
        if(!paramDecls.empty())
            ptree_add_subnode(functiondesc, "params", params);
        ptree_array_add_node(tree, functiondesc);
    }
}

<|endoftext|>


<commit_before>#include <cstdio>
#include <string>
#include <regex>
#include <fstream>
#include <sys/stat.h>
#include <unistd.h>
// http://tclap.sourceforge.net/manual.html
#include "tclap/CmdLine.h"
#include "HCIDumpParser.h"
#include "MsgPublisherTypeConstraint.h"
#include "../lcd/LcdDisplay.h"
#include "MockScannerView.h"

static HCIDumpParser parserLogic;

#define STOP_MARKER_FILE "/var/run/scannerd.STOP"

inline bool stopMarkerExists() {
    struct stat buffer;
    bool stop = (stat (STOP_MARKER_FILE, &buffer) == 0);
    if(stop) {
        printf("Found STOP marker file, will exit...\n");
        fflush(stdout);
    }
    return stop;
}
static long eventCount = 0;
static long maxEventCount = 0;
static int64_t lastMarkerCheckTime = 0;

/**
* Callback invoked by the hdidumpinternal.c code when a LE_ADVERTISING_REPORT event is seen on the stack
*/
extern "C" bool beacon_event_callback(beacon_info * info) {
#ifdef PRINT_DEBUG
    printf("beacon_event_callback(%ld: %s, code=%d, time=%lld)\n", eventCount, info->uuid, info->code, info->time);
#endif
    parserLogic.beaconEvent(*info);
    eventCount ++;
    // Check for a termination marker every 1000 events or 5 seconds
    bool stop = false;
    int64_t elapsed = info->time - lastMarkerCheckTime;
    if((eventCount % 1000) == 0 || elapsed > 5000) {
        lastMarkerCheckTime = info->time;
        stop = stopMarkerExists();
        printf("beacon_event_callback, status eventCount=%ld, stop=%d\n", eventCount, stop);
        fflush(stdout);
    }
    // Check max event count limit
    if(maxEventCount > 0 && eventCount >= maxEventCount)
        stop = true;
    return stop;
}

using namespace std;

static ScannerView *getDisplayInstance() {
    ScannerView *view = nullptr;
#ifdef HAVE_LCD_DISPLAY
    LcdDisplay *lcd = LcdDisplay::getLcdDisplayInstance();
    lcd->init();
    view = lcd;
#else
    view = new MockScannerView();
#endif
}

/**
* A version of the native scanner that directly integrates with the bluez stack hcidump command rather than parsing
* the hcidump output.
*/
int main(int argc, const char **argv) {

    printf("NativeScanner starting up...\n");
    for(int n = 0; n < argc; n ++) {
        printf("    argv[%d] = %s\n", n, argv[n]);
    }
    fflush(stdout);
    TCLAP::CmdLine cmd("NativeScanner command line options", ' ', "0.1");
    //
    TCLAP::ValueArg<std::string> scannerID("s", "scannerID",
            "Specify the ID of the scanner reading the beacon events",
            true, "DEFAULT", "string", cmd);
    TCLAP::ValueArg<std::string> heartbeatUUID("H", "heartbeatUUID",
            "Specify the UUID of the beacon used to signal the scanner heartbeat event",
            false, "DEFAULT", "string", cmd);
    TCLAP::ValueArg<std::string> rawDumpFile("d", "rawDumpFile",
            "Specify a path to an hcidump file to parse for testing",
            false, "", "string", cmd);
    TCLAP::ValueArg<std::string> clientID("c", "clientID",
            "Specify the clientID to connect to the MQTT broker with",
            false, "", "string", cmd);
    TCLAP::ValueArg<std::string> username("u", "username",
            "Specify the username to connect to the MQTT broker with",
            false, "", "string", cmd);
    TCLAP::ValueArg<std::string> password("p", "password",
            "Specify the password to connect to the MQTT broker with",
            false, "", "string", cmd);
    TCLAP::ValueArg<std::string> brokerURL("b", "brokerURL",
            "Specify the brokerURL to connect to the message broker with; default tcp://localhost:5672",
            false, "tcp://localhost:5672", "string", cmd);
    TCLAP::ValueArg<std::string> destinationName("t", "destinationName",
            "Specify the name of the destination on the message broker to publish to; default beaconEvents",
            false, "beaconEvents", "string", cmd);
    TCLAP::ValueArg<int> analyzeWindow("W", "analyzeWindow",
            "Specify the number of seconds in the analyzeMode time window",
            false, 1, "int", cmd);
    TCLAP::ValueArg<std::string> hciDev("D", "hciDev",
            "Specify the name of the host controller interface to use; default hci0",
            false, "hci0", "string", cmd);
    MsgPublisherTypeConstraint pubTypeConstraint;
    TCLAP::ValueArg<std::string> pubType("P", "pubType",
            "Specify the MsgPublisherType enum for the publisher implementation to use; default AMQP_QPID",
            false, "AMQP_QPID", &pubTypeConstraint, cmd, nullptr);
    TCLAP::ValueArg<int> maxCount("C", "maxCount",
            "Specify a maxium number of events the scanner should process before exiting; default 0 means no limit",
            false, 0, "int", cmd);
    TCLAP::ValueArg<int> batchCount("B", "batchCount",
            "Specify a maxium number of events the scanner should combine before sending to broker; default 0 means no batching",
            false, 0, "int", cmd);
    TCLAP::ValueArg<int> statusInterval("I", "statusInterval",
            "Specify the interval in seconds between health status messages, <= 0 means no messages; default 30",
            false, 30, "int", cmd);
    TCLAP::ValueArg<int> rebootAfterNoReply("r", "rebootAfterNoReply",
            "Specify the interval in seconds after which a failure to hear our own heartbeat triggers a reboot, <= 0 means no reboot; default -1",
            false, -1, "int", cmd);
    TCLAP::ValueArg<std::string> statusQueue("q", "statusQueue",
            "Specify the name of the status health queue destination; default scannerHealth",
            false, "scannerHealth", "string", cmd);
    TCLAP::SwitchArg skipPublish("S", "skipPublish",
            "Indicate that the parsed beacons should not be published",
            false);
    TCLAP::SwitchArg asyncMode("A", "asyncMode",
            "Indicate that the parsed beacons should be published using async delivery mode",
            false);
    TCLAP::SwitchArg useQueues("Q", "useQueues",
            "Indicate that the destination type is a queue. If not given the default type is a topic.",
            false);
    TCLAP::SwitchArg skipHeartbeat("K", "skipHeartbeat",
            "Don't publish the heartbeat messages. Useful to limit the noise when testing the scanner.",
            false);
    TCLAP::SwitchArg analzyeMode("", "analzyeMode",
            "Run the scanner in a mode that simply collects beacon readings and reports unique beacons seen in a time window",
             false);
    TCLAP::SwitchArg generateTestData("T", "generateTestData",
             "Indicate that test data should be generated",
             false);
    TCLAP::SwitchArg noBrokerReconnect("", "noBrokerReconnect",
             "Don't try to reconnect to the broker on failure, just exit",
             false);
    TCLAP::SwitchArg batteryTestMode("", "batteryTestMode",
              "Simply monitor the raw heartbeat beacon events and publish them to the destinationName",
              false);

    try {
        // Add the flag arguments
        cmd.add(skipPublish);
        cmd.add(asyncMode);
        cmd.add(useQueues);
        cmd.add(skipHeartbeat);
        cmd.add(analzyeMode);
        cmd.add(generateTestData);
        cmd.add(noBrokerReconnect);
        cmd.add(batteryTestMode);
        // Parse the argv array.
        printf("Parsing command line...\n");
        cmd.parse( argc, argv );
        printf("done\n");
    }
    catch (TCLAP::ArgException &e) {
        fprintf(stderr, "error: %s for arg: %s\n", e.error().c_str(), e.argId().c_str());
    }

    // Remove any stop marker file
    if(remove(STOP_MARKER_FILE) == 0) {
        printf("Removed existing %s marker file\n", STOP_MARKER_FILE);
    }

    HCIDumpCommand command(scannerID.getValue(), brokerURL.getValue(), clientID.getValue(), destinationName.getValue());
    command.setUseQueues(useQueues.getValue());
    command.setSkipPublish(skipPublish.getValue());
    command.setSkipHeartbeat(skipHeartbeat.getValue());
    command.setHciDev(hciDev.getValue());
    command.setAsyncMode(asyncMode.getValue());
    command.setAnalyzeMode(analzyeMode.getValue());
    command.setAnalyzeWindow(analyzeWindow.getValue());
    command.setPubType(pubTypeConstraint.toType(pubType.getValue()));
    command.setStatusInterval(statusInterval.getValue());
    command.setStatusQueue(statusQueue.getValue());
    command.setGenerateTestData(generateTestData.getValue());
    command.setBatteryTestMode(batteryTestMode.getValue());
    if(maxCount.getValue() > 0) {
        maxEventCount = maxCount.getValue();
        printf("Set maxEventCount: %ld\n", maxEventCount);
    }
    parserLogic.setBatchCount(batchCount.getValue());
    if(heartbeatUUID.isSet()) {
        parserLogic.setScannerUUID(heartbeatUUID.getValue());
        printf("Set heartbeatUUID: %s\n", heartbeatUUID.getValue().c_str());
    }
    shared_ptr<ScannerView> lcd(getDisplayInstance());
    parserLogic.setScannerView(lcd);
    char cwd[256];
    getcwd(cwd, sizeof(cwd));
    printf("Begin scanning, cwd=%s...\n", cwd);
    fflush(stdout);
    parserLogic.processHCI(command);
    parserLogic.cleanup();
    printf("End scanning\n");
    fflush(stdout);
    return 0;
}
<commit_msg> Install default terminate handler to make sure we exit with non-zero status<commit_after>#include <cstdio>
#include <string>
#include <regex>
#include <fstream>
#include <sys/stat.h>
#include <unistd.h>
#include <execinfo.h>
// http://tclap.sourceforge.net/manual.html
#include "tclap/CmdLine.h"
#include "HCIDumpParser.h"
#include "MsgPublisherTypeConstraint.h"
#include "../lcd/LcdDisplay.h"
#include "MockScannerView.h"

static HCIDumpParser parserLogic;

#define STOP_MARKER_FILE "/var/run/scannerd.STOP"

inline bool stopMarkerExists() {
    struct stat buffer;
    bool stop = (stat (STOP_MARKER_FILE, &buffer) == 0);
    if(stop) {
        printf("Found STOP marker file, will exit...\n");
        fflush(stdout);
    }
    return stop;
}
static long eventCount = 0;
static long maxEventCount = 0;
static int64_t lastMarkerCheckTime = 0;

/**
* Callback invoked by the hdidumpinternal.c code when a LE_ADVERTISING_REPORT event is seen on the stack
*/
extern "C" bool beacon_event_callback(beacon_info * info) {
#ifdef PRINT_DEBUG
    printf("beacon_event_callback(%ld: %s, code=%d, time=%lld)\n", eventCount, info->uuid, info->code, info->time);
#endif
    parserLogic.beaconEvent(*info);
    eventCount ++;
    // Check for a termination marker every 1000 events or 5 seconds
    bool stop = false;
    int64_t elapsed = info->time - lastMarkerCheckTime;
    if((eventCount % 1000) == 0 || elapsed > 5000) {
        lastMarkerCheckTime = info->time;
        stop = stopMarkerExists();
        printf("beacon_event_callback, status eventCount=%ld, stop=%d\n", eventCount, stop);
        fflush(stdout);
    }
    // Check max event count limit
    if(maxEventCount > 0 && eventCount >= maxEventCount)
        stop = true;
    return stop;
}

using namespace std;

static ScannerView *getDisplayInstance() {
    ScannerView *view = nullptr;
#ifdef HAVE_LCD_DISPLAY
    LcdDisplay *lcd = LcdDisplay::getLcdDisplayInstance();
    lcd->init();
    view = lcd;
#else
    view = new MockScannerView();
#endif
}

void printStacktrace() {
    void *array[20];
    int size = backtrace(array, sizeof(array) / sizeof(array[0]));
    backtrace_symbols_fd(array, size, STDERR_FILENO);
}

static void terminateHandler() {
    std::exception_ptr exptr = std::current_exception();
    if (exptr != nullptr) {
        // the only useful feature of std::exception_ptr is that it can be rethrown...
        try {
            std::rethrow_exception(exptr);
        } catch (std::exception &ex) {
            std::fprintf(stderr, "Terminated due to exception: %s\n", ex.what());
        }
        catch (...) {
            std::fprintf(stderr, "Terminated due to unknown exception\n");
        }
    }
    else {
        std::fprintf(stderr, "Terminated due to unknown reason :(\n");
    }
    printStacktrace();
    exit(100);
}

/**
* A version of the native scanner that directly integrates with the bluez stack hcidump command rather than parsing
* the hcidump output.
*/
int main(int argc, const char **argv) {

    printf("NativeScanner starting up...\n");
    for(int n = 0; n < argc; n ++) {
        printf("    argv[%d] = %s\n", n, argv[n]);
    }
    fflush(stdout);
    TCLAP::CmdLine cmd("NativeScanner command line options", ' ', "0.1");
    //
    TCLAP::ValueArg<std::string> scannerID("s", "scannerID",
            "Specify the ID of the scanner reading the beacon events",
            true, "DEFAULT", "string", cmd);
    TCLAP::ValueArg<std::string> heartbeatUUID("H", "heartbeatUUID",
            "Specify the UUID of the beacon used to signal the scanner heartbeat event",
            false, "DEFAULT", "string", cmd);
    TCLAP::ValueArg<std::string> rawDumpFile("d", "rawDumpFile",
            "Specify a path to an hcidump file to parse for testing",
            false, "", "string", cmd);
    TCLAP::ValueArg<std::string> clientID("c", "clientID",
            "Specify the clientID to connect to the MQTT broker with",
            false, "", "string", cmd);
    TCLAP::ValueArg<std::string> username("u", "username",
            "Specify the username to connect to the MQTT broker with",
            false, "", "string", cmd);
    TCLAP::ValueArg<std::string> password("p", "password",
            "Specify the password to connect to the MQTT broker with",
            false, "", "string", cmd);
    TCLAP::ValueArg<std::string> brokerURL("b", "brokerURL",
            "Specify the brokerURL to connect to the message broker with; default tcp://localhost:5672",
            false, "tcp://localhost:5672", "string", cmd);
    TCLAP::ValueArg<std::string> destinationName("t", "destinationName",
            "Specify the name of the destination on the message broker to publish to; default beaconEvents",
            false, "beaconEvents", "string", cmd);
    TCLAP::ValueArg<int> analyzeWindow("W", "analyzeWindow",
            "Specify the number of seconds in the analyzeMode time window",
            false, 1, "int", cmd);
    TCLAP::ValueArg<std::string> hciDev("D", "hciDev",
            "Specify the name of the host controller interface to use; default hci0",
            false, "hci0", "string", cmd);
    MsgPublisherTypeConstraint pubTypeConstraint;
    TCLAP::ValueArg<std::string> pubType("P", "pubType",
            "Specify the MsgPublisherType enum for the publisher implementation to use; default AMQP_QPID",
            false, "AMQP_QPID", &pubTypeConstraint, cmd, nullptr);
    TCLAP::ValueArg<int> maxCount("C", "maxCount",
            "Specify a maxium number of events the scanner should process before exiting; default 0 means no limit",
            false, 0, "int", cmd);
    TCLAP::ValueArg<int> batchCount("B", "batchCount",
            "Specify a maxium number of events the scanner should combine before sending to broker; default 0 means no batching",
            false, 0, "int", cmd);
    TCLAP::ValueArg<int> statusInterval("I", "statusInterval",
            "Specify the interval in seconds between health status messages, <= 0 means no messages; default 30",
            false, 30, "int", cmd);
    TCLAP::ValueArg<int> rebootAfterNoReply("r", "rebootAfterNoReply",
            "Specify the interval in seconds after which a failure to hear our own heartbeat triggers a reboot, <= 0 means no reboot; default -1",
            false, -1, "int", cmd);
    TCLAP::ValueArg<std::string> statusQueue("q", "statusQueue",
            "Specify the name of the status health queue destination; default scannerHealth",
            false, "scannerHealth", "string", cmd);
    TCLAP::SwitchArg skipPublish("S", "skipPublish",
            "Indicate that the parsed beacons should not be published",
            false);
    TCLAP::SwitchArg asyncMode("A", "asyncMode",
            "Indicate that the parsed beacons should be published using async delivery mode",
            false);
    TCLAP::SwitchArg useQueues("Q", "useQueues",
            "Indicate that the destination type is a queue. If not given the default type is a topic.",
            false);
    TCLAP::SwitchArg skipHeartbeat("K", "skipHeartbeat",
            "Don't publish the heartbeat messages. Useful to limit the noise when testing the scanner.",
            false);
    TCLAP::SwitchArg analzyeMode("", "analzyeMode",
            "Run the scanner in a mode that simply collects beacon readings and reports unique beacons seen in a time window",
             false);
    TCLAP::SwitchArg generateTestData("T", "generateTestData",
             "Indicate that test data should be generated",
             false);
    TCLAP::SwitchArg noBrokerReconnect("", "noBrokerReconnect",
             "Don't try to reconnect to the broker on failure, just exit",
             false);
    TCLAP::SwitchArg batteryTestMode("", "batteryTestMode",
              "Simply monitor the raw heartbeat beacon events and publish them to the destinationName",
              false);

    try {
        // Add the flag arguments
        cmd.add(skipPublish);
        cmd.add(asyncMode);
        cmd.add(useQueues);
        cmd.add(skipHeartbeat);
        cmd.add(analzyeMode);
        cmd.add(generateTestData);
        cmd.add(noBrokerReconnect);
        cmd.add(batteryTestMode);
        // Parse the argv array.
        printf("Parsing command line...\n");
        cmd.parse( argc, argv );
        printf("done\n");
    }
    catch (TCLAP::ArgException &e) {
        fprintf(stderr, "error: %s for arg: %s\n", e.error().c_str(), e.argId().c_str());
    }

    // Remove any stop marker file
    if(remove(STOP_MARKER_FILE) == 0) {
        printf("Removed existing %s marker file\n", STOP_MARKER_FILE);
    }

    HCIDumpCommand command(scannerID.getValue(), brokerURL.getValue(), clientID.getValue(), destinationName.getValue());
    command.setUseQueues(useQueues.getValue());
    command.setSkipPublish(skipPublish.getValue());
    command.setSkipHeartbeat(skipHeartbeat.getValue());
    command.setHciDev(hciDev.getValue());
    command.setAsyncMode(asyncMode.getValue());
    command.setAnalyzeMode(analzyeMode.getValue());
    command.setAnalyzeWindow(analyzeWindow.getValue());
    command.setPubType(pubTypeConstraint.toType(pubType.getValue()));
    command.setStatusInterval(statusInterval.getValue());
    command.setStatusQueue(statusQueue.getValue());
    command.setGenerateTestData(generateTestData.getValue());
    command.setBatteryTestMode(batteryTestMode.getValue());
    if(maxCount.getValue() > 0) {
        maxEventCount = maxCount.getValue();
        printf("Set maxEventCount: %ld\n", maxEventCount);
    }
    parserLogic.setBatchCount(batchCount.getValue());
    if(heartbeatUUID.isSet()) {
        parserLogic.setScannerUUID(heartbeatUUID.getValue());
        printf("Set heartbeatUUID: %s\n", heartbeatUUID.getValue().c_str());
    }

    // Install default terminate handler to make sure we exit with non-zero status
    std::set_terminate(terminateHandler);

    shared_ptr<ScannerView> lcd(getDisplayInstance());
    parserLogic.setScannerView(lcd);
    char cwd[256];
    getcwd(cwd, sizeof(cwd));
    printf("Begin scanning, cwd=%s...\n", cwd);
    fflush(stdout);
    parserLogic.processHCI(command);
    parserLogic.cleanup();
    printf("End scanning\n");
    fflush(stdout);
    return 0;
}
<|endoftext|>


<commit_before>/*
 * author: Max Kellermann <mk@cm4all.com>
 */

#ifndef EXPANDABLE_STRING_LIST_HXX
#define EXPANDABLE_STRING_LIST_HXX

#include "util/ShallowCopy.hxx"

#include <inline/compiler.h>

#include <iterator>

struct pool;
class MatchInfo;
class Error;
template<typename T> struct ConstBuffer;

class ExpandableStringList final {
    struct Item {
        Item *next = nullptr;

        const char *value;

        bool expandable;

        Item(const char *_value, bool _expandable)
            :value(_value), expandable(_expandable) {}
    };

    Item *head = nullptr;

public:
    ExpandableStringList() = default;
    ExpandableStringList(ExpandableStringList &&) = default;
    ExpandableStringList &operator=(ExpandableStringList &&src) = default;

    constexpr ExpandableStringList(ShallowCopy,
                                   const ExpandableStringList &src)
        :head(src.head) {}

    ExpandableStringList(struct pool &pool, const ExpandableStringList &src);

    gcc_pure
    bool IsEmpty() const {
        return head == nullptr;
    }

    class const_iterator final
        : public std::iterator<std::forward_iterator_tag, const char *> {

        const Item *cursor;

    public:
        const_iterator(const Item *_cursor):cursor(_cursor) {}

        bool operator!=(const const_iterator &other) const {
            return cursor != other.cursor;
        }

        const char *operator*() const {
            return cursor->value;
        }

        const_iterator &operator++() {
            cursor = cursor->next;
            return *this;
        }
    };

    const_iterator begin() const {
        return {head};
    }

    const_iterator end() const {
        return {nullptr};
    }

    gcc_pure
    bool IsExpandable() const;

    bool Expand(struct pool *pool,
                const MatchInfo &match_info, Error &error_r);

    class Builder final {
        ExpandableStringList *list;

        Item **tail_r;

        Item *last;

    public:
        Builder() = default;

        Builder(ExpandableStringList &_list)
            :list(&_list), tail_r(&_list.head), last(nullptr) {}

        void Add(struct pool &pool, const char *value, bool expandable);

        bool CanSetExpand() const {
            return last != nullptr && !last->expandable;
        }

        void SetExpand(const char *value) const {
            last->value = value;
            last->expandable = true;
        }
    };

    ConstBuffer<const char *> ToArray(struct pool &pool) const;
};

#endif
<commit_msg>ExpandableStringList: add Builder::Add() documentation<commit_after>/*
 * author: Max Kellermann <mk@cm4all.com>
 */

#ifndef EXPANDABLE_STRING_LIST_HXX
#define EXPANDABLE_STRING_LIST_HXX

#include "util/ShallowCopy.hxx"

#include <inline/compiler.h>

#include <iterator>

struct pool;
class MatchInfo;
class Error;
template<typename T> struct ConstBuffer;

class ExpandableStringList final {
    struct Item {
        Item *next = nullptr;

        const char *value;

        bool expandable;

        Item(const char *_value, bool _expandable)
            :value(_value), expandable(_expandable) {}
    };

    Item *head = nullptr;

public:
    ExpandableStringList() = default;
    ExpandableStringList(ExpandableStringList &&) = default;
    ExpandableStringList &operator=(ExpandableStringList &&src) = default;

    constexpr ExpandableStringList(ShallowCopy,
                                   const ExpandableStringList &src)
        :head(src.head) {}

    ExpandableStringList(struct pool &pool, const ExpandableStringList &src);

    gcc_pure
    bool IsEmpty() const {
        return head == nullptr;
    }

    class const_iterator final
        : public std::iterator<std::forward_iterator_tag, const char *> {

        const Item *cursor;

    public:
        const_iterator(const Item *_cursor):cursor(_cursor) {}

        bool operator!=(const const_iterator &other) const {
            return cursor != other.cursor;
        }

        const char *operator*() const {
            return cursor->value;
        }

        const_iterator &operator++() {
            cursor = cursor->next;
            return *this;
        }
    };

    const_iterator begin() const {
        return {head};
    }

    const_iterator end() const {
        return {nullptr};
    }

    gcc_pure
    bool IsExpandable() const;

    bool Expand(struct pool *pool,
                const MatchInfo &match_info, Error &error_r);

    class Builder final {
        ExpandableStringList *list;

        Item **tail_r;

        Item *last;

    public:
        Builder() = default;

        Builder(ExpandableStringList &_list)
            :list(&_list), tail_r(&_list.head), last(nullptr) {}

        /**
         * Add a new item to the end of the list.  The pool is only
         * used to allocate the item structure, it does not copy the
         * string.
         */
        void Add(struct pool &pool, const char *value, bool expandable);

        bool CanSetExpand() const {
            return last != nullptr && !last->expandable;
        }

        void SetExpand(const char *value) const {
            last->value = value;
            last->expandable = true;
        }
    };

    ConstBuffer<const char *> ToArray(struct pool &pool) const;
};

#endif
<|endoftext|>


<commit_before>#include "Globals.h"
#include "Application.h"
#include "PhysBody3D.h"
#include "ModuleCamera3D.h"

ModuleCamera3D::ModuleCamera3D(Application* app, bool start_enabled) : Module(app, start_enabled)
{

	name = "Camera3D";

	CalculateViewMatrix();

	X = vec3(1.0f, 0.0f, 0.0f);
	Y = vec3(0.0f, 1.0f, 0.0f);
	Z = vec3(0.0f, 0.0f, 1.0f);

	Position = vec3(0.0f, 0.0f, 5.0f);
	Reference = vec3(0.0f, 0.0f, 0.0f);
}

ModuleCamera3D::~ModuleCamera3D()
{}

// -----------------------------------------------------------------
bool ModuleCamera3D::Start()
{
	LOG("Setting up the camera");
	bool ret = true;

	return ret;
}

// -----------------------------------------------------------------
bool ModuleCamera3D::CleanUp()
{
	LOG("Cleaning camera");

	return true;
}

// -----------------------------------------------------------------
update_status ModuleCamera3D::Update(float dt)
{

	vec3 newPos(0,0,0);
	float speed = 3.0f * dt;
	if(App->input->GetKey(SDL_SCANCODE_LSHIFT) == KEY_REPEAT)
		speed = 8.0f * dt;

	if(App->input->GetKey(SDL_SCANCODE_R) == KEY_REPEAT) newPos.y += speed;
	if(App->input->GetKey(SDL_SCANCODE_F) == KEY_REPEAT) newPos.y -= speed;

	if(App->input->GetKey(SDL_SCANCODE_W) == KEY_REPEAT) newPos -= Z * speed;
	if(App->input->GetKey(SDL_SCANCODE_S) == KEY_REPEAT) newPos += Z * speed;

	if(App->input->GetKey(SDL_SCANCODE_A) == KEY_REPEAT) newPos -= X * speed;
	if(App->input->GetKey(SDL_SCANCODE_D) == KEY_REPEAT) newPos += X * speed;

	Position += newPos;
	Reference += newPos;

	// Mouse motion ----------------

	if(App->input->GetMouseButton(SDL_BUTTON_RIGHT) == KEY_REPEAT)
	{
		int dx = -App->input->GetMouseXMotion();
		int dy = -App->input->GetMouseYMotion();

		float Sensitivity = 0.25f;

		if(dx != 0)
		{
			float DeltaX = (float)dx * Sensitivity;

			X = rotate(X, DeltaX, vec3(0.0f, 1.0f, 0.0f));
			Y = rotate(Y, DeltaX, vec3(0.0f, 1.0f, 0.0f));
			Z = rotate(Z, DeltaX, vec3(0.0f, 1.0f, 0.0f));

		}

		if(dy != 0)
		{
			float DeltaY = (float)dy * Sensitivity;

			Y = rotate(Y, DeltaY, X);
			Z = rotate(Z, DeltaY, X);

			if(Y.y < 0.0f)
			{
				Z = vec3(0.0f, Z.y > 0.0f ? 1.0f : -1.0f, 0.0f);
				Y = cross(Z, X);
			}
		}

		//Position = Reference + Z * length(Position);
	}

	// Recalculate matrix -------------
	CalculateViewMatrix();

	return UPDATE_CONTINUE;
}

// -----------------------------------------------------------------
void ModuleCamera3D::Look(const vec3 &Position, const vec3 &Reference, bool RotateAroundReference)
{
	this->Position = Position;
	this->Reference = Reference;

	Z = normalize(Position - Reference);
	X = normalize(cross(vec3(0.0f, 1.0f, 0.0f), Z));
	Y = cross(Z, X);

	if(!RotateAroundReference)
	{
		this->Reference = this->Position;
		this->Position += Z * 0.05f;
	}

	CalculateViewMatrix();
}

// -----------------------------------------------------------------
void ModuleCamera3D::LookAt( const vec3 &Spot)
{
	Reference = Spot;

	Z = normalize(Position - Reference);
	X = normalize(cross(vec3(0.0f, 1.0f, 0.0f), Z));
	Y = cross(Z, X);

	CalculateViewMatrix();
}

// -----------------------------------------------------------------
void ModuleCamera3D::Move(const vec3 &Movement)
{
	Position += Movement;
	Reference += Movement;

	CalculateViewMatrix();
}

// -----------------------------------------------------------------
float* ModuleCamera3D::GetViewMatrix()
{
	return &ViewMatrix;
}

// -----------------------------------------------------------------
void ModuleCamera3D::CalculateViewMatrix()
{
	ViewMatrix = mat4x4(X.x, Y.x, Z.x, 0.0f, X.y, Y.y, Z.y, 0.0f, X.z, Y.z, Z.z, 0.0f, -dot(X, Position), -dot(Y, Position), -dot(Z, Position), 1.0f);
	ViewMatrixInverse = inverse(ViewMatrix);
}<commit_msg>Right Click activates WASD - fps like movement<commit_after>#include "Globals.h"
#include "Application.h"
#include "PhysBody3D.h"
#include "ModuleCamera3D.h"

ModuleCamera3D::ModuleCamera3D(Application* app, bool start_enabled) : Module(app, start_enabled)
{

	name = "Camera3D";

	CalculateViewMatrix();

	X = vec3(1.0f, 0.0f, 0.0f);
	Y = vec3(0.0f, 1.0f, 0.0f);
	Z = vec3(0.0f, 0.0f, 1.0f);

	Position = vec3(0.0f, 0.0f, 5.0f);
	Reference = vec3(0.0f, 0.0f, 0.0f);
}

ModuleCamera3D::~ModuleCamera3D()
{}

// -----------------------------------------------------------------
bool ModuleCamera3D::Start()
{
	LOG("Setting up the camera");
	bool ret = true;

	return ret;
}

// -----------------------------------------------------------------
bool ModuleCamera3D::CleanUp()
{
	LOG("Cleaning camera");

	return true;
}

// -----------------------------------------------------------------
update_status ModuleCamera3D::Update(float dt)
{

	// Mouse motion ----------------

	if(App->input->GetMouseButton(SDL_BUTTON_RIGHT) == KEY_REPEAT)
	{

		vec3 newPos(0, 0, 0);
		float speed = 3.0f * dt;
		if (App->input->GetKey(SDL_SCANCODE_LSHIFT) == KEY_REPEAT)
			speed = 8.0f * dt;

		if (App->input->GetKey(SDL_SCANCODE_R) == KEY_REPEAT) newPos.y += speed;
		if (App->input->GetKey(SDL_SCANCODE_F) == KEY_REPEAT) newPos.y -= speed;

		if (App->input->GetKey(SDL_SCANCODE_W) == KEY_REPEAT) newPos -= Z * speed;
		if (App->input->GetKey(SDL_SCANCODE_S) == KEY_REPEAT) newPos += Z * speed;

		if (App->input->GetKey(SDL_SCANCODE_A) == KEY_REPEAT) newPos -= X * speed;
		if (App->input->GetKey(SDL_SCANCODE_D) == KEY_REPEAT) newPos += X * speed;

		Position += newPos;
		Reference += newPos;

		int dx = -App->input->GetMouseXMotion();
		int dy = -App->input->GetMouseYMotion();

		float Sensitivity = 0.25f;

		if(dx != 0)
		{
			float DeltaX = (float)dx * Sensitivity;

			X = rotate(X, DeltaX, vec3(0.0f, 1.0f, 0.0f));
			Y = rotate(Y, DeltaX, vec3(0.0f, 1.0f, 0.0f));
			Z = rotate(Z, DeltaX, vec3(0.0f, 1.0f, 0.0f));

		}

		if(dy != 0)
		{
			float DeltaY = (float)dy * Sensitivity;

			Y = rotate(Y, DeltaY, X);
			Z = rotate(Z, DeltaY, X);

			if(Y.y < 0.0f)
			{
				Z = vec3(0.0f, Z.y > 0.0f ? 1.0f : -1.0f, 0.0f);
				Y = cross(Z, X);
			}
		}

		//Position = Reference + Z * length(Position);
	}

	// Recalculate matrix -------------
	CalculateViewMatrix();

	return UPDATE_CONTINUE;
}

// -----------------------------------------------------------------
void ModuleCamera3D::Look(const vec3 &Position, const vec3 &Reference, bool RotateAroundReference)
{
	this->Position = Position;
	this->Reference = Reference;

	Z = normalize(Position - Reference);
	X = normalize(cross(vec3(0.0f, 1.0f, 0.0f), Z));
	Y = cross(Z, X);

	if(!RotateAroundReference)
	{
		this->Reference = this->Position;
		this->Position += Z * 0.05f;
	}

	CalculateViewMatrix();
}

// -----------------------------------------------------------------
void ModuleCamera3D::LookAt( const vec3 &Spot)
{
	Reference = Spot;

	Z = normalize(Position - Reference);
	X = normalize(cross(vec3(0.0f, 1.0f, 0.0f), Z));
	Y = cross(Z, X);

	CalculateViewMatrix();
}

// -----------------------------------------------------------------
void ModuleCamera3D::Move(const vec3 &Movement)
{
	Position += Movement;
	Reference += Movement;

	CalculateViewMatrix();
}

// -----------------------------------------------------------------
float* ModuleCamera3D::GetViewMatrix()
{
	return &ViewMatrix;
}

// -----------------------------------------------------------------
void ModuleCamera3D::CalculateViewMatrix()
{
	ViewMatrix = mat4x4(X.x, Y.x, Z.x, 0.0f, X.y, Y.y, Z.y, 0.0f, X.z, Y.z, Z.z, 0.0f, -dot(X, Position), -dot(Y, Position), -dot(Z, Position), 1.0f);
	ViewMatrixInverse = inverse(ViewMatrix);
}<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: cancelcommandexecution.cxx,v $
 *
 *  $Revision: 1.11 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 16:36:02 $
 *
 *  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
 *
 ************************************************************************/

/**************************************************************************
                                TODO
 **************************************************************************

 *************************************************************************/

#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _CPPUHELPER_EXC_HLP_HXX_
#include <cppuhelper/exc_hlp.hxx>
#endif
#ifndef _COM_SUN_STAR_UCB_COMMANDFAILEDEXCEPTION_HPP_
#include <com/sun/star/ucb/CommandFailedException.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_XCOMMANDENVIRONMENT_HPP_
#include <com/sun/star/ucb/XCommandEnvironment.hpp>
#endif
#ifndef _UCBHELPER_INTERACTIONREQUEST_HXX
#include <ucbhelper/interactionrequest.hxx>
#endif
#ifndef _UCBHELPER_CANCELCOMMANDEXECUTION_HXX_
#include <ucbhelper/cancelcommandexecution.hxx>
#endif
#ifndef _UCBHELPER_SIMPLEIOERRORREQUEST_HXX
#include <ucbhelper/simpleioerrorrequest.hxx>
#endif

using namespace com::sun::star;

namespace ucbhelper
{

//=========================================================================
void cancelCommandExecution( const uno::Any & rException,
                             const uno::Reference<
                                        ucb::XCommandEnvironment > & xEnv )
    throw( uno::Exception )
{
    if ( xEnv.is() )
    {
        uno::Reference<
            task::XInteractionHandler > xIH = xEnv->getInteractionHandler();
        if ( xIH.is() )
        {
            rtl::Reference< ucbhelper::InteractionRequest > xRequest
                = new ucbhelper::InteractionRequest( rException );

            uno::Sequence< uno::Reference< task::XInteractionContinuation > >
                aContinuations( 1 );
            aContinuations[ 0 ]
                = new ucbhelper::InteractionAbort( xRequest.get() );

            xRequest->setContinuations( aContinuations );

            xIH->handle( xRequest.get() );

            rtl::Reference< ucbhelper::InteractionContinuation > xSelection
                = xRequest->getSelection();

            if ( xSelection.is() )
                throw ucb::CommandFailedException(
                                    rtl::OUString(),
                                    uno::Reference< uno::XInterface >(),
                                    rException );
        }
    }

    cppu::throwException( rException );

    OSL_ENSURE( sal_False, "Return from cppu::throwException call!!!" );
    throw uno::RuntimeException();
}

#if SUPD < 641
//=========================================================================
void cancelCommandExecution( const ucb::IOErrorCode eError,
                             const rtl::OUString & rArg,
                             const uno::Reference<
                                ucb::XCommandEnvironment > & xEnv,
                             const rtl::OUString & rMessage,
                             const uno::Reference<
                                    ucb::XCommandProcessor > & xContext )
    throw( uno::Exception )
{
    uno::Sequence< uno::Any > aArgs( 1 );
    aArgs[ 0 ] <<= rArg;

    rtl::Reference< ucbhelper::SimpleIOErrorRequest > xRequest
        = new ucbhelper::SimpleIOErrorRequest(
                                    eError, aArgs, rMessage, xContext );
    if ( xEnv.is() )
    {
        uno::Reference<
            task::XInteractionHandler > xIH = xEnv->getInteractionHandler();
        if ( xIH.is() )
        {
            xIH->handle( xRequest.get() );

            rtl::Reference< ucbhelper::InteractionContinuation > xSelection
                = xRequest->getSelection();

            if ( xSelection.is() )
                throw ucb::CommandFailedException( rtl::OUString(),
                                                   xContext,
                                                   xRequest->getRequest() );
        }
    }

    cppu::throwException( xRequest->getRequest() );

    OSL_ENSURE( sal_False, "Return from cppu::throwException call!!!" );
    throw uno::RuntimeException();
}

//=========================================================================
void cancelCommandExecution( const ucb::IOErrorCode eError,
                             const rtl::OUString & rArg1,
                             const rtl::OUString & rArg2,
                             const uno::Reference<
                                ucb::XCommandEnvironment > & xEnv,
                             const rtl::OUString & rMessage,
                             const uno::Reference<
                                    ucb::XCommandProcessor > & xContext )
    throw( uno::Exception )
{
    uno::Sequence< uno::Any > aArgs( 2 );
    aArgs[ 0 ] <<= rArg1;
    aArgs[ 1 ] <<= rArg2;

    rtl::Reference< ucbhelper::SimpleIOErrorRequest > xRequest
        = new ucbhelper::SimpleIOErrorRequest(
                                    eError, aArgs, rMessage, xContext );
    if ( xEnv.is() )
    {
        uno::Reference<
            task::XInteractionHandler > xIH = xEnv->getInteractionHandler();
        if ( xIH.is() )
        {
            xIH->handle( xRequest.get() );

            rtl::Reference< ucbhelper::InteractionContinuation > xSelection
                = xRequest->getSelection();

            if ( xSelection.is() )
                throw ucb::CommandFailedException( rtl::OUString(),
                                                   xContext,
                                                   xRequest->getRequest() );
        }
    }

    cppu::throwException( xRequest->getRequest() );

    OSL_ENSURE( sal_False, "Return from cppu::throwException call!!!" );
    throw uno::RuntimeException();
}
#endif // SUPD, 641

//=========================================================================
void cancelCommandExecution( const ucb::IOErrorCode eError,
                             const uno::Sequence< uno::Any > & rArgs,
                             const uno::Reference<
                                ucb::XCommandEnvironment > & xEnv,
                             const rtl::OUString & rMessage,
                             const uno::Reference<
                                    ucb::XCommandProcessor > & xContext )
    throw( uno::Exception )
{
    rtl::Reference< ucbhelper::SimpleIOErrorRequest > xRequest
        = new ucbhelper::SimpleIOErrorRequest(
                                    eError, rArgs, rMessage, xContext );
    if ( xEnv.is() )
    {
        uno::Reference<
            task::XInteractionHandler > xIH = xEnv->getInteractionHandler();
        if ( xIH.is() )
        {
            xIH->handle( xRequest.get() );

            rtl::Reference< ucbhelper::InteractionContinuation > xSelection
                = xRequest->getSelection();

            if ( xSelection.is() )
                throw ucb::CommandFailedException( rtl::OUString(),
                                                   xContext,
                                                   xRequest->getRequest() );
        }
    }

    cppu::throwException( xRequest->getRequest() );

    OSL_ENSURE( sal_False, "Return from cppu::throwException call!!!" );
    throw uno::RuntimeException();
}

}
<commit_msg>INTEGRATION: CWS pchfix02 (1.11.34); FILE MERGED 2006/09/01 17:56:06 kaib 1.11.34.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: cancelcommandexecution.cxx,v $
 *
 *  $Revision: 1.12 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-16 17:20:48 $
 *
 *  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_ucbhelper.hxx"

/**************************************************************************
                                TODO
 **************************************************************************

 *************************************************************************/

#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _CPPUHELPER_EXC_HLP_HXX_
#include <cppuhelper/exc_hlp.hxx>
#endif
#ifndef _COM_SUN_STAR_UCB_COMMANDFAILEDEXCEPTION_HPP_
#include <com/sun/star/ucb/CommandFailedException.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_XCOMMANDENVIRONMENT_HPP_
#include <com/sun/star/ucb/XCommandEnvironment.hpp>
#endif
#ifndef _UCBHELPER_INTERACTIONREQUEST_HXX
#include <ucbhelper/interactionrequest.hxx>
#endif
#ifndef _UCBHELPER_CANCELCOMMANDEXECUTION_HXX_
#include <ucbhelper/cancelcommandexecution.hxx>
#endif
#ifndef _UCBHELPER_SIMPLEIOERRORREQUEST_HXX
#include <ucbhelper/simpleioerrorrequest.hxx>
#endif

using namespace com::sun::star;

namespace ucbhelper
{

//=========================================================================
void cancelCommandExecution( const uno::Any & rException,
                             const uno::Reference<
                                        ucb::XCommandEnvironment > & xEnv )
    throw( uno::Exception )
{
    if ( xEnv.is() )
    {
        uno::Reference<
            task::XInteractionHandler > xIH = xEnv->getInteractionHandler();
        if ( xIH.is() )
        {
            rtl::Reference< ucbhelper::InteractionRequest > xRequest
                = new ucbhelper::InteractionRequest( rException );

            uno::Sequence< uno::Reference< task::XInteractionContinuation > >
                aContinuations( 1 );
            aContinuations[ 0 ]
                = new ucbhelper::InteractionAbort( xRequest.get() );

            xRequest->setContinuations( aContinuations );

            xIH->handle( xRequest.get() );

            rtl::Reference< ucbhelper::InteractionContinuation > xSelection
                = xRequest->getSelection();

            if ( xSelection.is() )
                throw ucb::CommandFailedException(
                                    rtl::OUString(),
                                    uno::Reference< uno::XInterface >(),
                                    rException );
        }
    }

    cppu::throwException( rException );

    OSL_ENSURE( sal_False, "Return from cppu::throwException call!!!" );
    throw uno::RuntimeException();
}

#if SUPD < 641
//=========================================================================
void cancelCommandExecution( const ucb::IOErrorCode eError,
                             const rtl::OUString & rArg,
                             const uno::Reference<
                                ucb::XCommandEnvironment > & xEnv,
                             const rtl::OUString & rMessage,
                             const uno::Reference<
                                    ucb::XCommandProcessor > & xContext )
    throw( uno::Exception )
{
    uno::Sequence< uno::Any > aArgs( 1 );
    aArgs[ 0 ] <<= rArg;

    rtl::Reference< ucbhelper::SimpleIOErrorRequest > xRequest
        = new ucbhelper::SimpleIOErrorRequest(
                                    eError, aArgs, rMessage, xContext );
    if ( xEnv.is() )
    {
        uno::Reference<
            task::XInteractionHandler > xIH = xEnv->getInteractionHandler();
        if ( xIH.is() )
        {
            xIH->handle( xRequest.get() );

            rtl::Reference< ucbhelper::InteractionContinuation > xSelection
                = xRequest->getSelection();

            if ( xSelection.is() )
                throw ucb::CommandFailedException( rtl::OUString(),
                                                   xContext,
                                                   xRequest->getRequest() );
        }
    }

    cppu::throwException( xRequest->getRequest() );

    OSL_ENSURE( sal_False, "Return from cppu::throwException call!!!" );
    throw uno::RuntimeException();
}

//=========================================================================
void cancelCommandExecution( const ucb::IOErrorCode eError,
                             const rtl::OUString & rArg1,
                             const rtl::OUString & rArg2,
                             const uno::Reference<
                                ucb::XCommandEnvironment > & xEnv,
                             const rtl::OUString & rMessage,
                             const uno::Reference<
                                    ucb::XCommandProcessor > & xContext )
    throw( uno::Exception )
{
    uno::Sequence< uno::Any > aArgs( 2 );
    aArgs[ 0 ] <<= rArg1;
    aArgs[ 1 ] <<= rArg2;

    rtl::Reference< ucbhelper::SimpleIOErrorRequest > xRequest
        = new ucbhelper::SimpleIOErrorRequest(
                                    eError, aArgs, rMessage, xContext );
    if ( xEnv.is() )
    {
        uno::Reference<
            task::XInteractionHandler > xIH = xEnv->getInteractionHandler();
        if ( xIH.is() )
        {
            xIH->handle( xRequest.get() );

            rtl::Reference< ucbhelper::InteractionContinuation > xSelection
                = xRequest->getSelection();

            if ( xSelection.is() )
                throw ucb::CommandFailedException( rtl::OUString(),
                                                   xContext,
                                                   xRequest->getRequest() );
        }
    }

    cppu::throwException( xRequest->getRequest() );

    OSL_ENSURE( sal_False, "Return from cppu::throwException call!!!" );
    throw uno::RuntimeException();
}
#endif // SUPD, 641

//=========================================================================
void cancelCommandExecution( const ucb::IOErrorCode eError,
                             const uno::Sequence< uno::Any > & rArgs,
                             const uno::Reference<
                                ucb::XCommandEnvironment > & xEnv,
                             const rtl::OUString & rMessage,
                             const uno::Reference<
                                    ucb::XCommandProcessor > & xContext )
    throw( uno::Exception )
{
    rtl::Reference< ucbhelper::SimpleIOErrorRequest > xRequest
        = new ucbhelper::SimpleIOErrorRequest(
                                    eError, rArgs, rMessage, xContext );
    if ( xEnv.is() )
    {
        uno::Reference<
            task::XInteractionHandler > xIH = xEnv->getInteractionHandler();
        if ( xIH.is() )
        {
            xIH->handle( xRequest.get() );

            rtl::Reference< ucbhelper::InteractionContinuation > xSelection
                = xRequest->getSelection();

            if ( xSelection.is() )
                throw ucb::CommandFailedException( rtl::OUString(),
                                                   xContext,
                                                   xRequest->getRequest() );
        }
    }

    cppu::throwException( xRequest->getRequest() );

    OSL_ENSURE( sal_False, "Return from cppu::throwException call!!!" );
    throw uno::RuntimeException();
}

}
<|endoftext|>