<commit_before>/*************************************************************************
 *
 *  $RCSfile: mailtodispatcher.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: as $ $Date: 2002-05-03 08:01:45 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef __FRAMEWORK_DISPATCH_MAILTODISPATCHER_HXX_
#define __FRAMEWORK_DISPATCH_MAILTODISPATCHER_HXX_

//_________________________________________________________________________________________________________________
//  my own includes
//_________________________________________________________________________________________________________________

#ifndef __FRAMEWORK_MACROS_GENERIC_HXX_
#include <macros/generic.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_
#include <macros/xinterface.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_
#include <macros/xtypeprovider.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_XSERVICEINFO_HXX_
#include <macros/xserviceinfo.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_DEBUG_HXX_
#include <macros/debug.hxx>
#endif

#ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_
#include <threadhelp/threadhelpbase.hxx>
#endif

#ifndef __FRAMEWORK_GENERAL_H_
#include <general.h>
#endif

#ifndef __FRAMEWORK_STDTYPES_H_
#include <stdtypes.h>
#endif

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

#ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_
#include <com/sun/star/lang/XTypeProvider.hpp>
#endif

#ifndef _COM_SUN_STAR_FRAME_XNOTIFYINGDISPATCH_HPP_
#include <com/sun/star/frame/XNotifyingDispatch.hpp>
#endif

#ifndef _COM_SUN_STAR_FRAME_XDISPATCH_HPP_
#include <com/sun/star/frame/XDispatch.hpp>
#endif

#ifndef _COM_SUN_STAR_FRAME_XDISPATCHPROVIDER_HPP_
#include <com/sun/star/frame/XDispatchProvider.hpp>
#endif

#ifndef _COM_SUN_STAR_UTIL_URL_HPP_
#include <com/sun/star/util/URL.hpp>
#endif

#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif

#ifndef _COM_SUN_STAR_FRAME_XSTATUSLISTENER_HPP_
#include <com/sun/star/frame/XStatusListener.hpp>
#endif

//_________________________________________________________________________________________________________________
//  other includes
//_________________________________________________________________________________________________________________

#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif

//_________________________________________________________________________________________________________________
//  namespace
//_________________________________________________________________________________________________________________

namespace framework{

//_________________________________________________________________________________________________________________
//  exported const
//_________________________________________________________________________________________________________________

//_________________________________________________________________________________________________________________
//  exported definitions
//_________________________________________________________________________________________________________________

/**
    @short          protocol handler for "mailto:" URLs
    @descr          It's a special dispatch object which is used registered for "mailto:*" URLs and
                    will be automaticly used from the framework dispatch mechanism if such URL occured.

    @base           ThreadHelpBase
                        exports a lock member to guarantee right initialize value of it
    @base           OWeakObject
                        provides XWeak and ref count mechanism

    @devstatus      ready to use

    @modified       02.05.2002 08:12, as96863
*/
class MailToDispatcher : // interfaces
                         public  css::lang::XTypeProvider      ,
                         public  css::lang::XServiceInfo       ,
                         public  css::frame::XDispatchProvider ,
                         public  css::frame::XNotifyingDispatch, // => XDispatch
                         // baseclasses
                         // Order is neccessary for right initialization!
                         private ThreadHelpBase                ,
                         public  cppu::OWeakObject
{
    /* member */
    private:

        /// reference to global uno service manager which had created us
        css::uno::Reference< css::lang::XMultiServiceFactory > m_xFactory;

    /* interface */
    public:

        // ctor/dtor
                 MailToDispatcher( const css::uno::Reference< css::lang::XMultiServiceFactory >& xFactory );
        virtual ~MailToDispatcher(                                                                        );

        // XInterface, XTypeProvider, XServiceInfo
        DECLARE_XINTERFACE
        DECLARE_XTYPEPROVIDER
        DECLARE_XSERVICEINFO

        // XDispatchProvider
        virtual css::uno::Reference< css::frame::XDispatch > SAL_CALL                       queryDispatch  ( const css::util::URL&                                       aURL        ,
                                                                                const ::rtl::OUString&                                      sTarget     ,
                                                                                sal_Int32                                             nFlags      ) throw( css::uno::RuntimeException );
        virtual css::uno::Sequence< css::uno::Reference< css::frame::XDispatch > > SAL_CALL queryDispatches( const css::uno::Sequence< css::frame::DispatchDescriptor >& lDescriptor ) throw( css::uno::RuntimeException );

        // XNotifyingDispatch
        virtual void SAL_CALL dispatchWithNotification( const css::util::URL&                                             aURL      ,
                                                        const css::uno::Sequence< css::beans::PropertyValue >&            lArguments,
                                                        const css::uno::Reference< css::frame::XDispatchResultListener >& xListener ) throw( css::uno::RuntimeException );

        // XDispatch
        virtual void SAL_CALL dispatch            ( const css::util::URL&                                     aURL       ,
                                                    const css::uno::Sequence< css::beans::PropertyValue >&    lArguments ) throw( css::uno::RuntimeException );
        virtual void SAL_CALL addStatusListener   ( const css::uno::Reference< css::frame::XStatusListener >& xListener  ,
                                                    const css::util::URL&                                     aURL       ) throw( css::uno::RuntimeException );
        virtual void SAL_CALL removeStatusListener( const css::uno::Reference< css::frame::XStatusListener >& xListener  ,
                                                    const css::util::URL&                                     aURL       ) throw( css::uno::RuntimeException );

    /* internal */
    private:

        sal_Bool implts_dispatch( const css::util::URL&                                  aURL       ,
                                  const css::uno::Sequence< css::beans::PropertyValue >& lArguments ) throw( css::uno::RuntimeException );

};      //  class MailToDispatcher

}       //  namespace framework

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

#ifndef __FRAMEWORK_DISPATCH_MAILTODISPATCHER_HXX_
#define __FRAMEWORK_DISPATCH_MAILTODISPATCHER_HXX_

//_________________________________________________________________________________________________________________
//  my own includes
//_________________________________________________________________________________________________________________

#ifndef __FRAMEWORK_MACROS_GENERIC_HXX_
#include <macros/generic.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_
#include <macros/xinterface.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_
#include <macros/xtypeprovider.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_XSERVICEINFO_HXX_
#include <macros/xserviceinfo.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_DEBUG_HXX_
#include <macros/debug.hxx>
#endif

#ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_
#include <threadhelp/threadhelpbase.hxx>
#endif

#ifndef __FRAMEWORK_GENERAL_H_
#include <general.h>
#endif

#ifndef __FRAMEWORK_STDTYPES_H_
#include <stdtypes.h>
#endif

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

#ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_
#include <com/sun/star/lang/XTypeProvider.hpp>
#endif

#ifndef _COM_SUN_STAR_FRAME_XNOTIFYINGDISPATCH_HPP_
#include <com/sun/star/frame/XNotifyingDispatch.hpp>
#endif

#ifndef _COM_SUN_STAR_FRAME_XDISPATCH_HPP_
#include <com/sun/star/frame/XDispatch.hpp>
#endif

#ifndef _COM_SUN_STAR_FRAME_XDISPATCHPROVIDER_HPP_
#include <com/sun/star/frame/XDispatchProvider.hpp>
#endif

#ifndef _COM_SUN_STAR_UTIL_URL_HPP_
#include <com/sun/star/util/URL.hpp>
#endif

#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif

#ifndef _COM_SUN_STAR_FRAME_XSTATUSLISTENER_HPP_
#include <com/sun/star/frame/XStatusListener.hpp>
#endif

//_________________________________________________________________________________________________________________
//  other includes
//_________________________________________________________________________________________________________________

#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif

//_________________________________________________________________________________________________________________
//  namespace
//_________________________________________________________________________________________________________________

namespace framework{

//_________________________________________________________________________________________________________________
//  exported const
//_________________________________________________________________________________________________________________

//_________________________________________________________________________________________________________________
//  exported definitions
//_________________________________________________________________________________________________________________

/**
    @short          protocol handler for "mailto:" URLs
    @descr          It's a special dispatch object which is used registered for "mailto:*" URLs and
                    will be automaticly used from the framework dispatch mechanism if such URL occured.

    @base           ThreadHelpBase
                        exports a lock member to guarantee right initialize value of it
    @base           OWeakObject
                        provides XWeak and ref count mechanism

    @devstatus      ready to use

    @modified       02.05.2002 08:12, as96863
*/
class MailToDispatcher : // interfaces
                         public  css::lang::XTypeProvider      ,
                         public  css::lang::XServiceInfo       ,
                         public  css::frame::XDispatchProvider ,
                         public  css::frame::XNotifyingDispatch, // => XDispatch
                         // baseclasses
                         // Order is neccessary for right initialization!
                         private ThreadHelpBase                ,
                         public  cppu::OWeakObject
{
    /* member */
    private:

        /// reference to global uno service manager which had created us
        css::uno::Reference< css::lang::XMultiServiceFactory > m_xFactory;

    /* interface */
    public:

        // ctor/dtor
                 MailToDispatcher( const css::uno::Reference< css::lang::XMultiServiceFactory >& xFactory );
        virtual ~MailToDispatcher(                                                                        );

        // XInterface, XTypeProvider, XServiceInfo
        DECLARE_XINTERFACE
        DECLARE_XTYPEPROVIDER
        DECLARE_XSERVICEINFO

        // XDispatchProvider
        virtual css::uno::Reference< css::frame::XDispatch > SAL_CALL                       queryDispatch  ( const css::util::URL&                                       aURL        ,
                                                                                const ::rtl::OUString&                                      sTarget     ,
                                                                                sal_Int32                                             nFlags      ) throw( css::uno::RuntimeException );
        virtual css::uno::Sequence< css::uno::Reference< css::frame::XDispatch > > SAL_CALL queryDispatches( const css::uno::Sequence< css::frame::DispatchDescriptor >& lDescriptor ) throw( css::uno::RuntimeException );

        // XNotifyingDispatch
        virtual void SAL_CALL dispatchWithNotification( const css::util::URL&                                             aURL      ,
                                                        const css::uno::Sequence< css::beans::PropertyValue >&            lArguments,
                                                        const css::uno::Reference< css::frame::XDispatchResultListener >& xListener ) throw( css::uno::RuntimeException );

        // XDispatch
        virtual void SAL_CALL dispatch            ( const css::util::URL&                                     aURL       ,
                                                    const css::uno::Sequence< css::beans::PropertyValue >&    lArguments ) throw( css::uno::RuntimeException );
        virtual void SAL_CALL addStatusListener   ( const css::uno::Reference< css::frame::XStatusListener >& xListener  ,
                                                    const css::util::URL&                                     aURL       ) throw( css::uno::RuntimeException );
        virtual void SAL_CALL removeStatusListener( const css::uno::Reference< css::frame::XStatusListener >& xListener  ,
                                                    const css::util::URL&                                     aURL       ) throw( css::uno::RuntimeException );

    /* internal */
    private:

        sal_Bool implts_dispatch( const css::util::URL&                                  aURL       ,
                                  const css::uno::Sequence< css::beans::PropertyValue >& lArguments ) throw( css::uno::RuntimeException );

};      //  class MailToDispatcher

}       //  namespace framework

#endif  //  #ifndef __FRAMEWORK_DISPATCH_MAILTODISPATCHER_HXX_
<|endoftext|>


<commit_before>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1        *
*                (c) 2006-2011 MGH, INRIA, USTL, UJF, CNRS                    *
*                                                                             *
* This library is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU Lesser General Public License as published by    *
* the Free Software Foundation; either version 2.1 of the License, or (at     *
* your option) any later version.                                             *
*                                                                             *
* 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.          *
*******************************************************************************
*                               SOFA :: Modules                               *
*                                                                             *
* This component is open-source                                               *
*                                                                             *
* Authors: Damien Marchal                                                     *
*          Bruno Carrez                                                       *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/
/*****************************************************************************
* User of this library should read the documentation
* in the TextMessaging.h file.
******************************************************************************/
#include <sstream>
using std::ostringstream ;

#include <iostream>
using std::endl ;

#include <string>
using std::string ;

#include <sofa/core/objectmodel/Base.h>
using sofa::core::objectmodel::Base ;

//#include "Messagehandler.h"
#include "Message.h"

namespace sofa
{

namespace helper
{

namespace messaging
{

Message::Message():
    m_sender(0),
    m_sendername("none"),
    m_source("none"),
    m_lineno(0),
    m_message("none"),
    m_class("DEV"),
    m_type("INFO"),
    m_id(-1)
{

}
Message::Message(string mclass, string type,  Base* sender, string source, int lineno){
    m_sender = sender ;
    m_source = source ;
    m_lineno = lineno ;
    m_message = "undefined" ;
    m_class   = mclass;
    m_type    = type ;
    m_id      = -1 ;

    if(sender!=nullptr){
        ostringstream s;
        s << "[" << sender->getName() << "(" << sender->getClassName() <<   ")]: ";
        m_sendername = s.str();
    }else{
        m_sendername = "undefined" ;
    }
}

Message::Message(string mclass, string type,  const string& sendername, string source, int lineno){
    m_sender = nullptr ;
    m_sendername = sendername ;
    m_source = source ;
    m_lineno = lineno ;
    m_message = "undefined" ;
    m_class   = mclass;
    m_type    = type ;
    m_id      = -1 ;
}

Message& Message::operator<=(const std::ostream& s)
{
    ostringstream tmp ;
    tmp << s.rdbuf() ;

    m_message = tmp.str() ;
    return *this ;
}

const string& Message::source() const {
    return m_source;
}

int Message::lineno() const  {
    return m_lineno;
}

const string& Message::message() const  {
    return m_message;
}

Base*  Message::sender() const  {
    return m_sender;
}

const std::string&  Message::sendername() const  {
    return m_sendername;
}

const string& Message::context() const  {
    return m_class;
}

const string& Message::type() const {
    return m_type;
}

int Message::id() const  {
    return m_id;
}

void Message::setId(int id){
    m_id = id;
}

std::ostream& operator<< (std::ostream& s, const Message& m){
    s << "[" << m.sendername() << "]: " << endl ;
    s << "         Message id: " << m.id() << endl ;
    s << "       Message type: " << m.type() << endl ;
    s << "    Message content: " << m.message() << endl ;
    s << "    source code loc: " << m.source() << ":" << m.lineno() << endl ;
    return s;
}

Message Message::empty = Message() ;

} // messaging
} // helper
} // sofa
<commit_msg>FIX some remaining C++11 things in the code<commit_after>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1        *
*                (c) 2006-2011 MGH, INRIA, USTL, UJF, CNRS                    *
*                                                                             *
* This library is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU Lesser General Public License as published by    *
* the Free Software Foundation; either version 2.1 of the License, or (at     *
* your option) any later version.                                             *
*                                                                             *
* 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.          *
*******************************************************************************
*                               SOFA :: Modules                               *
*                                                                             *
* This component is open-source                                               *
*                                                                             *
* Authors: Damien Marchal                                                     *
*          Bruno Carrez                                                       *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/
/*****************************************************************************
* User of this library should read the documentation
* in the TextMessaging.h file.
******************************************************************************/
#include <sstream>
using std::ostringstream ;

#include <iostream>
using std::endl ;

#include <string>
using std::string ;

#include <sofa/core/objectmodel/Base.h>
using sofa::core::objectmodel::Base ;

//#include "Messagehandler.h"
#include "Message.h"

namespace sofa
{

namespace helper
{

namespace messaging
{

Message::Message():
    m_sender(0),
    m_sendername("none"),
    m_source("none"),
    m_lineno(0),
    m_message("none"),
    m_class("DEV"),
    m_type("INFO"),
    m_id(-1)
{

}
Message::Message(string mclass, string type,  Base* sender, string source, int lineno){
    m_sender = sender ;
    m_source = source ;
    m_lineno = lineno ;
    m_message = "undefined" ;
    m_class   = mclass;
    m_type    = type ;
    m_id      = -1 ;

    if(sender!=0){
        ostringstream s;
        s << "[" << sender->getName() << "(" << sender->getClassName() <<   ")]: ";
        m_sendername = s.str();
    }else{
        m_sendername = "undefined" ;
    }
}

Message::Message(string mclass, string type,  const string& sendername, string source, int lineno){
    m_sender = 0 ;
    m_sendername = sendername ;
    m_source = source ;
    m_lineno = lineno ;
    m_message = "undefined" ;
    m_class   = mclass;
    m_type    = type ;
    m_id      = -1 ;
}

Message& Message::operator<=(const std::ostream& s)
{
    ostringstream tmp ;
    tmp << s.rdbuf() ;

    m_message = tmp.str() ;
    return *this ;
}

const string& Message::source() const {
    return m_source;
}

int Message::lineno() const  {
    return m_lineno;
}

const string& Message::message() const  {
    return m_message;
}

Base*  Message::sender() const  {
    return m_sender;
}

const std::string&  Message::sendername() const  {
    return m_sendername;
}

const string& Message::context() const  {
    return m_class;
}

const string& Message::type() const {
    return m_type;
}

int Message::id() const  {
    return m_id;
}

void Message::setId(int id){
    m_id = id;
}

std::ostream& operator<< (std::ostream& s, const Message& m){
    s << "[" << m.sendername() << "]: " << endl ;
    s << "         Message id: " << m.id() << endl ;
    s << "       Message type: " << m.type() << endl ;
    s << "    Message content: " << m.message() << endl ;
    s << "    source code loc: " << m.source() << ":" << m.lineno() << endl ;
    return s;
}

Message Message::empty = Message() ;

} // messaging
} // helper
} // sofa
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: statusindicator.cxx,v $
 *
 *  $Revision: 1.1 $
 *
 *  last change: $Author: as $ $Date: 2001-08-10 11:54: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 WARRUNTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRUNTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc..
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

//_________________________________________________________________________________________________________________
//  my own includes
//_________________________________________________________________________________________________________________

#ifndef __FRAMEWORK_HELPER_STATUSINDICATOR_HXX_
#include <helper/statusindicator.hxx>
#endif

#ifndef __FRAMEWORK_THREADHELP_RESETABLEGUARD_HXX_
#include <threadhelp/resetableguard.hxx>
#endif

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

//_________________________________________________________________________________________________________________
//  includes of other projects
//_________________________________________________________________________________________________________________

#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif

//_________________________________________________________________________________________________________________
//  namespace
//_________________________________________________________________________________________________________________

namespace framework{

//_________________________________________________________________________________________________________________
//  non exported const
//_________________________________________________________________________________________________________________

//_________________________________________________________________________________________________________________
//  non exported definitions
//_________________________________________________________________________________________________________________

//_________________________________________________________________________________________________________________
//  declarations
//_________________________________________________________________________________________________________________

//*****************************************************************************************************************
//  XInterface, XTypeProvider
//*****************************************************************************************************************
DEFINE_XINTERFACE_2     (   StatusIndicator                             ,
                            OWeakObject                                 ,
                            DIRECT_INTERFACE(css::lang::XTypeProvider   ),
                            DIRECT_INTERFACE(css::task::XStatusIndicator)
                        )

DEFINE_XTYPEPROVIDER_2  (   StatusIndicator                             ,
                            css::lang::XTypeProvider                    ,
                            css::task::XStatusIndicator
                        )

/*-************************************************************************************************************//**
    @short      standard ctor
    @descr      These initialize a new instance of this class with all needed informations for work.

    @seealso    -

    @param      "pFactory", pointer to factory, which has created this instance (XStatusIndicatorFactory!)
    @return     -

    @onerror    -
    @threadsafe yes
*//*-*************************************************************************************************************/
StatusIndicator::StatusIndicator( StatusIndicatorFactory* pFactory )
        //  Init baseclasses first
        :   ThreadHelpBase      ( &Application::GetSolarMutex() )
        ,   ::cppu::OWeakObject (                               )
        // Init member
        ,   m_pFactory          ( pFactory                      )
        ,   m_xFactoryWeak      ( pFactory                      )
{
    // Safe impossible cases
    // Method not defined for all incoming parameter.
    LOG_ASSERT2( implcp_StatusIndicator( pFactory ), "StatusIndicator::StatusIndicator()", "Invalid parameter detected!" )
}

/*-************************************************************************************************************//**
    @short      standard dtor
    @descr      Forget all references and pointer ... let they die.

    @seealso    -

    @param      -
    @return     -

    @onerror    -
    @threadsafe yes
*//*-*************************************************************************************************************/
StatusIndicator::~StatusIndicator()
{
    m_pFactory     = NULL                                                           ;
    m_xFactoryWeak = css::uno::WeakReference< css::task::XStatusIndicatorFactory >();
}

/*-************************************************************************************************************//**
    @interface  XStatusIndicator
    @short      These methods implement the functionality of this interface.
    @descr      But instances of this class are wrapper only. They try to get a right references from saved weak reference
                to her StatusIndicatorFactory. If it was successfully - they forward her calls to this factory only.
                These factory decide, which of the caller objects is the most active one and can show his informations.
                Other calls are ignored.

    @seealso    class StatusIndicatorFactory

    @param      "sText" , new text to show it in dialog
    @param      "nRange", new range for progress
    @param      "nValue", new value to show the progress
    @return     -

    @onerror    We do nothing!
    @threadsafe yes
*//*-*************************************************************************************************************/
void SAL_CALL StatusIndicator::start( const ::rtl::OUString& sText  ,
                                            sal_Int32        nRange ) throw( css::uno::RuntimeException )
{
    /* UNSAFE AREA --------------------------------------------------------------------------------------------- */
    // Safe impossible cases
    // Method not defined for all incoming parameter.
    LOG_ASSERT2( implcp_start( sText, nRange ), "StatusIndicator::start()", "Invalid parameter detected!" )

    /* SAFE AREA ----------------------------------------------------------------------------------------------- */
    // Ready for multithreading
    ResetableGuard aLock( m_aLock );

    css::uno::Reference< css::task::XStatusIndicatorFactory > xFactory( m_xFactoryWeak.get(), css::uno::UNO_QUERY );
    if( xFactory.is() == sal_True )
    {
        m_pFactory->start( this, sText, nRange );
    }
}

//*****************************************************************************************************************
void SAL_CALL StatusIndicator::end() throw( css::uno::RuntimeException )
{
    /* SAFE AREA ----------------------------------------------------------------------------------------------- */
    // Ready for multithreading
    ResetableGuard aLock( m_aLock );

    // Attention: Our factory forget our reference after calling "end()". So we must protect us against
    // dieing during this operation!
    css::uno::Reference< css::uno::XInterface > xThis( static_cast< ::cppu::OWeakObject* >(this), css::uno::UNO_QUERY );

    css::uno::Reference< css::task::XStatusIndicatorFactory > xFactory( m_xFactoryWeak.get(), css::uno::UNO_QUERY );
    if( xFactory.is() == sal_True )
    {
        m_pFactory->end( this );
    }
}

//*****************************************************************************************************************
void SAL_CALL StatusIndicator::reset() throw( css::uno::RuntimeException )
{
    /* SAFE AREA ----------------------------------------------------------------------------------------------- */
    // Ready for multithreading
    ResetableGuard aLock( m_aLock );

    css::uno::Reference< css::task::XStatusIndicatorFactory > xFactory( m_xFactoryWeak.get(), css::uno::UNO_QUERY );
    if( xFactory.is() == sal_True )
    {
        m_pFactory->reset( this );
    }
}

//*****************************************************************************************************************
void SAL_CALL StatusIndicator::setText( const ::rtl::OUString& sText ) throw( css::uno::RuntimeException )
{
    /* UNSAFE AREA --------------------------------------------------------------------------------------------- */
    // Safe impossible cases
    // Method not defined for all incoming parameter.
    LOG_ASSERT2( implcp_setText( sText ), "StatusIndicator::setText()", "Invalid parameter detected!" )

    /* SAFE AREA ----------------------------------------------------------------------------------------------- */
    // Ready for multithreading
    ResetableGuard aLock( m_aLock );

    css::uno::Reference< css::task::XStatusIndicatorFactory > xFactory( m_xFactoryWeak.get(), css::uno::UNO_QUERY );
    if( xFactory.is() == sal_True )
    {
        m_pFactory->setText( this, sText );
    }
}

//*****************************************************************************************************************
void SAL_CALL StatusIndicator::setValue( sal_Int32 nValue ) throw( css::uno::RuntimeException )
{
    /* UNSAFE AREA --------------------------------------------------------------------------------------------- */
    // Safe impossible cases
    // Method not defined for all incoming parameter.
    LOG_ASSERT2( implcp_setValue( nValue ), "StatusIndicator::setValue()", "Invalid parameter detected!" )

    /* SAFE AREA ----------------------------------------------------------------------------------------------- */
    // Ready for multithreading
    ResetableGuard aLock( m_aLock );

    css::uno::Reference< css::task::XStatusIndicatorFactory > xFactory( m_xFactoryWeak.get(), css::uno::UNO_QUERY );
    if( xFactory.is() == sal_True )
    {
        m_pFactory->setValue( this, nValue );
    }
}

//_________________________________________________________________________________________________________________
//  debug methods
//_________________________________________________________________________________________________________________

/*-************************************************************************************************************//**
    @short      debug-method to check incoming parameter of some other mehods of this class
    @descr      The following methods are used to check parameters for other methods
                of this class. The return value is used directly for an ASSERT(...).

    @seealso    ASSERTs in implementation!

    @param      references to checking variables
    @return     sal_False ,on invalid parameter
    @return     sal_True  ,otherwise

    @onerror    -
*//*-*************************************************************************************************************/
#ifdef ENABLE_ASSERTIONS

//*****************************************************************************************************************
sal_Bool StatusIndicator::implcp_StatusIndicator( StatusIndicatorFactory* pFactory )
{
    return( pFactory == NULL );
}

//*****************************************************************************************************************
sal_Bool StatusIndicator::implcp_start( const ::rtl::OUString&  sText   ,
                                              sal_Int32         nRange  )
{
    return(
            ( &sText  == NULL ) ||
            ( &nRange == NULL ) ||
            ( nRange  <  1    )     // We count from 0 to range ... and range should be greater then 0 ...!
          );
}

//*****************************************************************************************************************
sal_Bool StatusIndicator::implcp_setText( const ::rtl::OUString& sText )
{
    return( &sText == NULL );
}

//*****************************************************************************************************************
sal_Bool StatusIndicator::implcp_setValue( sal_Int32 nValue )
{
    return( nValue < 0 );
}

#endif  //  #ifdef ENABLE_ASSERTIONS

}       //  namespace framework
<commit_msg>INTEGRATION: CWS imprec01 (1.1.408); FILE MERGED 2004/12/15 06:51:20 as 1.1.408.1: #i35842# implement intelligent reschedule<commit_after>/*************************************************************************
 *
 *  $RCSfile: statusindicator.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2005-02-02 13:53:13 $
 *
 *  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 WARRUNTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRUNTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc..
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

//_______________________________________________
// include files of own module

#ifndef __FRAMEWORK_HELPER_STATUSINDICATOR_HXX_
#include <helper/statusindicator.hxx>
#endif

#ifndef __FRAMEWORK_THREADHELP_READGUARD_HXX_
#include <threadhelp/readguard.hxx>
#endif

#ifndef __FRAMEWORK_THREADHELP_WRITEGUARD_HXX_
#include <threadhelp/writeguard.hxx>
#endif

//_______________________________________________
// namespace

namespace framework{

//_______________________________________________
// declarations

//***********************************************
// XInterface
DEFINE_XINTERFACE_2(StatusIndicator                              ,
                    OWeakObject                                  ,
                    DIRECT_INTERFACE(css::lang::XTypeProvider   ),
                    DIRECT_INTERFACE(css::task::XStatusIndicator))

//***********************************************
// XInterface
DEFINE_XTYPEPROVIDER_2(StatusIndicator            ,
                       css::lang::XTypeProvider   ,
                       css::task::XStatusIndicator)

//***********************************************
StatusIndicator::StatusIndicator(StatusIndicatorFactory* pFactory)
    : ThreadHelpBase     (        )
    , ::cppu::OWeakObject(        )
    , m_xFactory         (pFactory)
{
}

//***********************************************
StatusIndicator::~StatusIndicator()
{
}

//***********************************************
void SAL_CALL StatusIndicator::start(const ::rtl::OUString& sText ,
                                           sal_Int32        nRange)
    throw(css::uno::RuntimeException)
{
    // SAFE ->
    ReadGuard aReadLock(m_aLock);
    css::uno::Reference< css::task::XStatusIndicatorFactory > xFactory(m_xFactory.get(), css::uno::UNO_QUERY);
    aReadLock.unlock();
    // <- SAFE
    if (xFactory.is())
    {
        StatusIndicatorFactory* pFactory = (StatusIndicatorFactory*)xFactory.get();
        pFactory->start(this, sText, nRange);
    }
}

//***********************************************
void SAL_CALL StatusIndicator::end()
    throw(css::uno::RuntimeException)
{
    // SAFE ->
    ReadGuard aReadLock(m_aLock);
    css::uno::Reference< css::task::XStatusIndicatorFactory > xFactory(m_xFactory.get(), css::uno::UNO_QUERY);
    aReadLock.unlock();
    // <- SAFE
    if (xFactory.is())
    {
        StatusIndicatorFactory* pFactory = (StatusIndicatorFactory*)xFactory.get();
        pFactory->end(this);
    }
}

//***********************************************
void SAL_CALL StatusIndicator::reset()
    throw(css::uno::RuntimeException)
{
    // SAFE ->
    ReadGuard aReadLock(m_aLock);
    css::uno::Reference< css::task::XStatusIndicatorFactory > xFactory(m_xFactory.get(), css::uno::UNO_QUERY);
    aReadLock.unlock();
    // <- SAFE
    if (xFactory.is())
    {
        StatusIndicatorFactory* pFactory = (StatusIndicatorFactory*)xFactory.get();
        pFactory->reset(this);
    }
}

//***********************************************
void SAL_CALL StatusIndicator::setText(const ::rtl::OUString& sText)
    throw(css::uno::RuntimeException)
{
    // SAFE ->
    ReadGuard aReadLock(m_aLock);
    css::uno::Reference< css::task::XStatusIndicatorFactory > xFactory(m_xFactory.get(), css::uno::UNO_QUERY);
    aReadLock.unlock();
    // <- SAFE
    if (xFactory.is())
    {
        StatusIndicatorFactory* pFactory = (StatusIndicatorFactory*)xFactory.get();
        pFactory->setText(this, sText);
    }
}

//***********************************************
void SAL_CALL StatusIndicator::setValue(sal_Int32 nValue)
    throw(css::uno::RuntimeException)
{
    // SAFE ->
    ReadGuard aReadLock(m_aLock);
    css::uno::Reference< css::task::XStatusIndicatorFactory > xFactory(m_xFactory.get(), css::uno::UNO_QUERY);
    aReadLock.unlock();
    // <- SAFE
    if (xFactory.is())
    {
        StatusIndicatorFactory* pFactory = (StatusIndicatorFactory*)xFactory.get();
        pFactory->setValue(this, nValue);
    }
}

} // namespace framework
<|endoftext|>


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

#include "entity_name.hpp"

#include "main.hpp"

#include <cstdint>
#include <cstring>
#include <filesystem>
#include <fstream>
#include <nlohmann/json.hpp>
#include <phosphor-logging/elog-errors.hpp>
#include <phosphor-logging/log.hpp>
#include <regex>
#include <sstream>
#include <string>
#include <system_error>
#include <unordered_map>
#include <vector>
#include <xyz/openbmc_project/Common/error.hpp>

namespace google
{
namespace ipmi
{
namespace fs = std::filesystem;

namespace
{

// TODO (jaghu) : Add a call to get getChannelMaxTransferSize.
#ifndef MAX_IPMI_BUFFER
#define MAX_IPMI_BUFFER 64
#endif

using Json = nlohmann::json;

using namespace phosphor::logging;
using InternalFailure =
    sdbusplus::xyz::openbmc_project::Common::Error::InternalFailure;

static constexpr auto configFile =
    "/usr/share/ipmi-entity-association/entity_association_map.json";

static const std::map<uint8_t, std::string> entityIdToName{
    {0x03, "cpu"},
    {0x04, "storage_device"},
    {0x06, "system_management_module"},
    {0x08, "memory_module"},
    {0x0B, "add_in_card"},
    {0x17, "system_chassis"},
    {0x20, "memory_device"}};

Json parse_config()
{
    std::ifstream jsonFile(configFile);
    if (!jsonFile.is_open())
    {
        log<level::ERR>("Entity association JSON file not found");
        elog<InternalFailure>();
    }

    auto data = Json::parse(jsonFile, nullptr, false);
    if (data.is_discarded())
    {
        log<level::ERR>("Entity association JSON parser failure");
        elog<InternalFailure>();
    }

    return data;
}

std::string read(const std::string& type, uint8_t instance, const Json& config)
{
    static const std::vector<Json> empty{};
    std::vector<Json> readings = config.value(type, empty);
    std::string name = "";
    for (const auto& j : readings)
    {
        uint8_t instanceNum = j.value("instance", 0);
        // Not the instance we're interested in
        if (instanceNum != instance)
        {
            continue;
        }

        // Found the instance we're interested in
        name = j.value("name", "");

        break;
    }
    return name;
}

} // namespace

struct GetEntityNameRequest
{
    uint8_t subcommand;
    uint8_t entity_id;
    uint8_t entity_instance;
} __attribute__((packed));

struct GetEntityNameReply
{
    uint8_t subcommand;
    uint8_t entity_name_len;
    uint8_t entity_name[0];
} __attribute__((packed));

ipmi_ret_t GetEntityName(const uint8_t* reqBuf, uint8_t* replyBuf,
                         size_t* dataLen)
{
    struct GetEntityNameRequest request;

    if ((*dataLen) < sizeof(request))
    {
        std::fprintf(stderr, "Invalid command length: %u\n",
                     static_cast<uint32_t>(*dataLen));
        return IPMI_CC_REQ_DATA_LEN_INVALID;
    }

    std::memcpy(&request, &reqBuf[0], sizeof(request));

    // Check if we support this Entity ID.
    auto it = entityIdToName.find(request.entity_id);
    if (it == entityIdToName.end())
    {
        log<level::ERR>("Unknown Entity ID",
                        entry("ENTITY_ID=%d", request.entity_id));
        return IPMI_CC_INVALID_FIELD_REQUEST;
    }

    static Json config{};
    static bool parsed = false;

    std::string entityName;
    try
    {
        // Parse the JSON config file.
        if (!parsed)
        {
            config = parse_config();
            parsed = true;
        }

        // Find the "entity id:entity instance" mapping to entity name.
        entityName = read(it->second, request.entity_instance, config);
        if (entityName.empty())
            return IPMI_CC_INVALID_FIELD_REQUEST;
    }
    catch (InternalFailure& e)
    {
        return IPMI_CC_UNSPECIFIED_ERROR;
    }

    int length = sizeof(struct GetEntityNameReply) + entityName.length();

    // TODO (jaghu) : Add a call to get getChannelMaxTransferSize.
    if (length > MAX_IPMI_BUFFER)
    {
        std::fprintf(stderr, "Response would overflow response buffer\n");
        return IPMI_CC_INVALID;
    }

    auto reply = reinterpret_cast<struct GetEntityNameReply*>(&replyBuf[0]);
    reply->subcommand = SysEntityName;
    reply->entity_name_len = entityName.length();
    std::memcpy(reply->entity_name, entityName.c_str(), entityName.length());

    (*dataLen) = length;
    return IPMI_CC_OK;
}
} // namespace ipmi
} // namespace google
<commit_msg>entity_name: cleanup headers<commit_after>/*
 * Copyright 2018 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "entity_name.hpp"

#include "main.hpp"

#include <cstdint>
#include <cstring>
#include <filesystem>
#include <fstream>
#include <map>
#include <nlohmann/json.hpp>
#include <phosphor-logging/elog-errors.hpp>
#include <phosphor-logging/log.hpp>
#include <string>
#include <vector>
#include <xyz/openbmc_project/Common/error.hpp>

namespace google
{
namespace ipmi
{
namespace fs = std::filesystem;

namespace
{

// TODO (jaghu) : Add a call to get getChannelMaxTransferSize.
#ifndef MAX_IPMI_BUFFER
#define MAX_IPMI_BUFFER 64
#endif

using Json = nlohmann::json;

using namespace phosphor::logging;
using InternalFailure =
    sdbusplus::xyz::openbmc_project::Common::Error::InternalFailure;

static constexpr auto configFile =
    "/usr/share/ipmi-entity-association/entity_association_map.json";

static const std::map<uint8_t, std::string> entityIdToName{
    {0x03, "cpu"},
    {0x04, "storage_device"},
    {0x06, "system_management_module"},
    {0x08, "memory_module"},
    {0x0B, "add_in_card"},
    {0x17, "system_chassis"},
    {0x20, "memory_device"}};

Json parse_config()
{
    std::ifstream jsonFile(configFile);
    if (!jsonFile.is_open())
    {
        log<level::ERR>("Entity association JSON file not found");
        elog<InternalFailure>();
    }

    auto data = Json::parse(jsonFile, nullptr, false);
    if (data.is_discarded())
    {
        log<level::ERR>("Entity association JSON parser failure");
        elog<InternalFailure>();
    }

    return data;
}

std::string read(const std::string& type, uint8_t instance, const Json& config)
{
    static const std::vector<Json> empty{};
    std::vector<Json> readings = config.value(type, empty);
    std::string name = "";
    for (const auto& j : readings)
    {
        uint8_t instanceNum = j.value("instance", 0);
        // Not the instance we're interested in
        if (instanceNum != instance)
        {
            continue;
        }

        // Found the instance we're interested in
        name = j.value("name", "");

        break;
    }
    return name;
}

} // namespace

struct GetEntityNameRequest
{
    uint8_t subcommand;
    uint8_t entity_id;
    uint8_t entity_instance;
} __attribute__((packed));

struct GetEntityNameReply
{
    uint8_t subcommand;
    uint8_t entity_name_len;
    uint8_t entity_name[0];
} __attribute__((packed));

ipmi_ret_t GetEntityName(const uint8_t* reqBuf, uint8_t* replyBuf,
                         size_t* dataLen)
{
    struct GetEntityNameRequest request;

    if ((*dataLen) < sizeof(request))
    {
        std::fprintf(stderr, "Invalid command length: %u\n",
                     static_cast<uint32_t>(*dataLen));
        return IPMI_CC_REQ_DATA_LEN_INVALID;
    }

    std::memcpy(&request, &reqBuf[0], sizeof(request));

    // Check if we support this Entity ID.
    auto it = entityIdToName.find(request.entity_id);
    if (it == entityIdToName.end())
    {
        log<level::ERR>("Unknown Entity ID",
                        entry("ENTITY_ID=%d", request.entity_id));
        return IPMI_CC_INVALID_FIELD_REQUEST;
    }

    static Json config{};
    static bool parsed = false;

    std::string entityName;
    try
    {
        // Parse the JSON config file.
        if (!parsed)
        {
            config = parse_config();
            parsed = true;
        }

        // Find the "entity id:entity instance" mapping to entity name.
        entityName = read(it->second, request.entity_instance, config);
        if (entityName.empty())
            return IPMI_CC_INVALID_FIELD_REQUEST;
    }
    catch (InternalFailure& e)
    {
        return IPMI_CC_UNSPECIFIED_ERROR;
    }

    int length = sizeof(struct GetEntityNameReply) + entityName.length();

    // TODO (jaghu) : Add a call to get getChannelMaxTransferSize.
    if (length > MAX_IPMI_BUFFER)
    {
        std::fprintf(stderr, "Response would overflow response buffer\n");
        return IPMI_CC_INVALID;
    }

    auto reply = reinterpret_cast<struct GetEntityNameReply*>(&replyBuf[0]);
    reply->subcommand = SysEntityName;
    reply->entity_name_len = entityName.length();
    std::memcpy(reply->entity_name, entityName.c_str(), entityName.length());

    (*dataLen) = length;
    return IPMI_CC_OK;
}
} // namespace ipmi
} // namespace google
<|endoftext|>


<commit_before>#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/opencv.hpp>
#include "opencv2/nonfree/nonfree.hpp"
#include "opencv2/features2d/features2d.hpp"
#include "opencv2/nonfree/features2d.hpp"
#include "opencv2/calib3d/calib3d.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <opencv2/legacy/legacy.hpp>

#include <math.h>
#include <iostream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <fstream>

//--------------------- Classes ---------------------

class Opt_flow {
  private:
    cv::VideoCapture video;
    cv::String filename;
    cv::Mat frame;
    cv::Mat opt_flow,flow_mask;
    cv::Mat prev_frame,next_frame;
    cv::Mat x_vals,y_vals;
    std::vector<float> vel_x;
    std::vector<float> vel_y;
    float std_error;
    cv::Vec3b frame_intensity,next_frame_intensity;
    float errors;
    int counter;
    CvSize win_size;
    int step,interval_pixels,tam_vel;
    int kernel_size;
    int threshold,ratio;

  public:

    Opt_flow(cv::VideoCapture video_ , cv::String filename_) {
      cv::namedWindow("Video");
      cv::namedWindow("OPT_FLOW");
      //cv::namedWindow("OPT_FLOW-X");
      //cv::namedWindow("OPT_FLOW-Y");
      video=video_;
      filename=filename_;
      std_error=80;
      counter=0;
      std_error=(std_error/100);
      win_size.height=3;
      win_size.width=3;
      kernel_size=3;
      interval_pixels=2;
      tam_vel=1;
      step=5;
      threshold=2;
      ratio=1;

      video.open(filename);
    }

    ~Opt_flow(){
      cv::destroyWindow("Video");
      //cv::destroyWindow("OPT_FLOW-X");
      //cv::destroyWindow("OPT_FLOW-Y");
      cv::destroyWindow("OPT_FLOW");
    }

    void play(){
      int i=0;
      while (char(cv::waitKey(1))!='q'&&video.isOpened()){
        video >> frame;

        if (i==0){
          cv::cvtColor(frame,prev_frame,cv::COLOR_BGR2GRAY);
          cv::GaussianBlur(prev_frame,prev_frame,cv::Size(kernel_size,kernel_size) ,0,0,cv::BORDER_DEFAULT);
        }

        if(i!=0&&i%step==0){
          cv::cvtColor(frame,next_frame,cv::COLOR_BGR2GRAY);
          cv::GaussianBlur(next_frame,next_frame,cv::Size(kernel_size,kernel_size) ,0,0,cv::BORDER_DEFAULT);

          //std::cout << "PREV_FRAME:" << prev_frame.size() << '|' << prev_frame.channels() << '\n';
          //std::cout << "NEXT_FRAME:" << next_frame.size() << '|' << next_frame.channels() << '\n';
          //getchar();

          cv::calcOpticalFlowFarneback(prev_frame, next_frame, opt_flow, .5, 3, 15, 3, 5, 1.2, 0);
          draw_flow(opt_flow,frame);

          get_xvals(opt_flow);
          get_yvals(opt_flow);
          generate_flowmask(x_vals,y_vals);
          cv::GaussianBlur(flow_mask,flow_mask,cv::Size(kernel_size,kernel_size) ,0,0,cv::BORDER_DEFAULT);
          cv::threshold(flow_mask,flow_mask,threshold, threshold*ratio,cv::THRESH_BINARY);

          show_frame();

          prev_frame=next_frame.clone();
        }

        std::cout << "i = " << i << '\n';
        i++;
      }
    }

    void show_frame(){
      cv::imshow("Video",frame);
      cv::imshow("OPT_FLOW",flow_mask);
    }

    void background_extr(){
      int i,j,aux_error;

      for(i=0;i<(frame.rows)-1;i++){
        for(j=0;j<(frame.cols)-1;j++){
          counter++;

          frame_intensity = frame.at<uint>(i,j);
          next_frame_intensity = next_frame.at<uint>(i,j);

          if (next_frame_intensity.val[0]==0){
            next_frame_intensity.val[0]=1;
          }
          errors=frame_intensity.val[0]/next_frame_intensity.val[0];

          if(errors<1-std_error||errors>1+std_error){
            opt_flow.at<uint>(i,j)=255;
            //std::cout << "MUDOU O PIXEL" << '\n';
          }
        }
      }
      //std::cout << "TROCOU FRAME" << '\n';

    }

    void blackfy(cv::Mat input){
      for(int i=0;i<input.rows;i++){
        for(int j=0;j<input.cols;j++){
          input.at<uint>(i,j)=0;
          //std::cout << "(" << i << "," << j << ")" << '\n';
        }
      }
    }

    void draw_flow(cv::Mat input, cv::Mat output){
      for (int y = 0; y < output.rows; y += interval_pixels) {
          for (int x = 0; x < output.cols; x += interval_pixels)
          {
              const cv::Point2f flowatxy = input.at<cv::Point2f>(y, x) * tam_vel;
              cv::line(output, cv::Point(x, y), cv::Point(cvRound(x + flowatxy.x), cvRound(y + flowatxy.y)), cv::Scalar(255, 0, 0));
              cv::circle(output, cv::Point(x, y), 1, cv::Scalar(0, 0, 0), -1);
          }
      }
    }

    void get_xvals(cv::Mat input){
      x_vals=cv::Mat::zeros(input.rows,input.cols, CV_32F);

      for (int i=0;i<input.rows;i++){
        for(int j=0;j<input.cols;j++){
          //std::cout << "X_VALS:" << x_vals.size() << '|' << x_vals.channels() << '|' << x_vals.type() << '\n';

          x_vals.at<float>(i,j)=input.at<cv::Point2f>(i,j).x;
        }
      }
    }

    void get_yvals(cv::Mat input){
      y_vals=cv::Mat::zeros(input.rows,input.cols, CV_32F);

      for (int i=0;i<input.rows;i++){
        for(int j=0;j<input.cols;j++){
          //std::cout << "Y_VALS:" << y_vals.size() << '|' << y_vals.channels() << '|' << y_vals.type() << '\n';

          y_vals.at<float>(i,j)=input.at<cv::Point2f>(i,j).y;
        }
      }
    }

    void generate_flowmask(cv::Mat x_matrix,cv::Mat y_matrix) {

      flow_mask=cv::Mat::zeros(x_matrix.rows,x_matrix.cols, CV_32F);

      for (int i=0;i<x_matrix.rows;i++){
        for(int j=0;j<x_matrix.cols;j++){
          flow_mask.at<float>(i,j)=magnitude(x_matrix.at<float>(i,j), y_matrix.at<float>(i,j));
        }
      }
    }

    float magnitude(float a, float b){
      float mag;

      mag=sqrt((a*a)+(b*b));

      return(mag);
    }
};

//--------------------- Global Variables ---------------------

//--------------------- Main Function ---------------------

int main(int argc, char *argv[]){
  cv::String filename;
  cv::VideoCapture video;

  if (argc<=1){
    std::cout << "\n\nThere was no input video to run.\nPress ENTER to quit.\n>>";
    getchar();
    return(-1);
  }

  filename=argv[1];

  Opt_flow opt_flow(video,filename);
  opt_flow.play();

  return(0);
}
<commit_msg>Find contour and mass center (beta)<commit_after>#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/opencv.hpp>
#include "opencv2/nonfree/nonfree.hpp"
#include "opencv2/features2d/features2d.hpp"
#include "opencv2/nonfree/features2d.hpp"
#include "opencv2/calib3d/calib3d.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <opencv2/legacy/legacy.hpp>

#include <math.h>
#include <iostream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <fstream>

//--------------------- Classes ---------------------

class Opt_flow {
  private:
    cv::VideoCapture video;
    cv::String filename;
    cv::Mat frame;
    cv::Mat opt_flow,flow_mask;
    cv::Mat prev_frame,next_frame;
    cv::Mat x_vals,y_vals;
    std::vector<float> vel_x;
    std::vector<float> vel_y;
    float std_error;
    cv::Vec3b frame_intensity,next_frame_intensity;
    float errors;
    int counter;
    CvSize win_size;
    int step,interval_pixels,tam_vel;
    int kernel_size;
    int threshold,ratio;
    std::vector<cv::Vec4i> hierarchy;
    std::vector<std::vector<cv::Point> > contours;

  public:

    Opt_flow(cv::VideoCapture video_ , cv::String filename_) {
      cv::namedWindow("Video");
      cv::namedWindow("OPT_FLOW");
      //cv::namedWindow("OPT_FLOW-X");
      //cv::namedWindow("OPT_FLOW-Y");
      video=video_;
      filename=filename_;
      std_error=80;
      counter=0;
      std_error=(std_error/100);
      win_size.height=3;
      win_size.width=3;
      kernel_size=3;
      interval_pixels=2;
      tam_vel=1;
      step=5;
      threshold=2;
      ratio=1;

      video.open(filename);
    }

    ~Opt_flow(){
      cv::destroyWindow("Video");
      //cv::destroyWindow("OPT_FLOW-X");
      //cv::destroyWindow("OPT_FLOW-Y");
      cv::destroyWindow("OPT_FLOW");
    }

    void play(){
      int i=0;
      while (char(cv::waitKey(1))!='q'&&video.isOpened()){
        video >> frame;

        if (i==0){
          cv::cvtColor(frame,prev_frame,cv::COLOR_BGR2GRAY);
          cv::GaussianBlur(prev_frame,prev_frame,cv::Size(kernel_size,kernel_size) ,0,0,cv::BORDER_DEFAULT);
        }

        if(i!=0&&i%step==0){
          cv::cvtColor(frame,next_frame,cv::COLOR_BGR2GRAY);
          cv::GaussianBlur(next_frame,next_frame,cv::Size(kernel_size,kernel_size) ,0,0,cv::BORDER_DEFAULT);

          //std::cout << "PREV_FRAME:" << prev_frame.size() << '|' << prev_frame.channels() << '\n';
          //std::cout << "NEXT_FRAME:" << next_frame.size() << '|' << next_frame.channels() << '\n';
          //getchar();

          cv::calcOpticalFlowFarneback(prev_frame, next_frame, opt_flow, .5, 3, 15, 3, 5, 1.2, 0);
          draw_flow(opt_flow,frame);

          get_xvals(opt_flow);
          get_yvals(opt_flow);
          generate_flowmask(x_vals,y_vals);
          cv::GaussianBlur(flow_mask,flow_mask,cv::Size(kernel_size,kernel_size) ,0,0,cv::BORDER_DEFAULT);
          cv::threshold(flow_mask,flow_mask,threshold, threshold*ratio,cv::THRESH_BINARY);
          cv::findContours(flow_mask,contours, hierarchy, CV_RETR_EXTERNAL,CV_CHAIN_APPROX_NONE);
          get_mass_centers(flow_mask);
          show_frame();

          prev_frame=next_frame.clone();
        }

        std::cout << "i = " << i << '\n';
        i++;
      }
    }

    void show_frame(){
      cv::imshow("Video",frame);
      cv::imshow("OPT_FLOW",flow_mask);
    }

    void background_extr(){
      int i,j,aux_error;

      for(i=0;i<(frame.rows)-1;i++){
        for(j=0;j<(frame.cols)-1;j++){
          counter++;

          frame_intensity = frame.at<uint>(i,j);
          next_frame_intensity = next_frame.at<uint>(i,j);

          if (next_frame_intensity.val[0]==0){
            next_frame_intensity.val[0]=1;
          }
          errors=frame_intensity.val[0]/next_frame_intensity.val[0];

          if(errors<1-std_error||errors>1+std_error){
            opt_flow.at<uint>(i,j)=255;
            //std::cout << "MUDOU O PIXEL" << '\n';
          }
        }
      }
      //std::cout << "TROCOU FRAME" << '\n';

    }

    void blackfy(cv::Mat input){
      for(int i=0;i<input.rows;i++){
        for(int j=0;j<input.cols;j++){
          input.at<uint>(i,j)=0;
          //std::cout << "(" << i << "," << j << ")" << '\n';
        }
      }
    }

    void draw_flow(cv::Mat input, cv::Mat output){
      for (int y = 0; y < output.rows; y += interval_pixels) {
          for (int x = 0; x < output.cols; x += interval_pixels)
          {
              const cv::Point2f flowatxy = input.at<cv::Point2f>(y, x) * tam_vel;
              cv::line(output, cv::Point(x, y), cv::Point(cvRound(x + flowatxy.x), cvRound(y + flowatxy.y)), cv::Scalar(255, 0, 0));
              cv::circle(output, cv::Point(x, y), 1, cv::Scalar(0, 0, 0), -1);
          }
      }
    }

    void get_xvals(cv::Mat input){
      x_vals=cv::Mat::zeros(input.rows,input.cols, CV_32F);

      for (int i=0;i<input.rows;i++){
        for(int j=0;j<input.cols;j++){
          //std::cout << "X_VALS:" << x_vals.size() << '|' << x_vals.channels() << '|' << x_vals.type() << '\n';

          x_vals.at<float>(i,j)=input.at<cv::Point2f>(i,j).x;
        }
      }
    }

    void get_yvals(cv::Mat input){
      y_vals=cv::Mat::zeros(input.rows,input.cols, CV_32F);

      for (int i=0;i<input.rows;i++){
        for(int j=0;j<input.cols;j++){
          //std::cout << "Y_VALS:" << y_vals.size() << '|' << y_vals.channels() << '|' << y_vals.type() << '\n';

          y_vals.at<float>(i,j)=input.at<cv::Point2f>(i,j).y;
        }
      }
    }

    void generate_flowmask(cv::Mat x_matrix,cv::Mat y_matrix) {

      flow_mask=cv::Mat::zeros(x_matrix.rows,x_matrix.cols, CV_32F);

      for (int i=0;i<x_matrix.rows;i++){
        for(int j=0;j<x_matrix.cols;j++){
          flow_mask.at<float>(i,j)=magnitude(x_matrix.at<float>(i,j), y_matrix.at<float>(i,j));
        }
      }
    }

    float magnitude(float a, float b){
      float mag;

      mag=sqrt((a*a)+(b*b));

      return(mag);
    }

    void get_mass_centers(cv::Mat input){
      vector<Moments> moments(contours.size());

      for(int i=0;i<contours.size();i++){
        moments[i] = moments(contours[i],false);
      }

      vector<Point2f> mass(contours.size());
      for(int i=0;i<contours.size();i++){
        mass[i] = Point2f(mu[i].m10/mu[i].m00,mu[i].m01/mu[i].m00);
      }

      draw_mass_centers(input);
    }

    void draw_mass_centers(cv::Mat input){
      for(int i=0;i<mass.size();i++){
        input.at<float>(mass[i].x,mass[j].y)=cv::Scalar(0,255,0);
      }
    }
};

class Moments {
  public:
      Moments();
      Moments(double m00, double m10, double m01, double m20, double m11,
              double m02, double m30, double m21, double m12, double m03 );
      Moments( const CvMoments& moments );
      operator CvMoments() const;

      // spatial moments
      double  m00, m10, m01, m20, m11, m02, m30, m21, m12, m03;
      // central moments
      double  mu20, mu11, mu02, mu30, mu21, mu12, mu03;
      // central normalized moments
      double  nu20, nu11, nu02, nu30, nu21, nu12, nu03;
};

//--------------------- Global Variables ---------------------

//--------------------- Main Function ---------------------

int main(int argc, char *argv[]){
  cv::String filename;
  cv::VideoCapture video;

  if (argc<=1){
    std::cout << "\n\nThere was no input video to run.\nPress ENTER to quit.\n>>";
    getchar();
    return(-1);
  }

  filename=argv[1];

  Opt_flow opt_flow(video,filename);
  opt_flow.play();

  return(0);
}
<|endoftext|>


<commit_before>/* --Sparse Optical Flow Demo Program--
 * Updated based on code written by David Stavens (dstavens@robotics.stanford.edu)
 */

#include "opencv2/opencv.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"

using namespace std;
using namespace cv;

/* This is just an inline that allocates images. I did this to reduce clutter in the
 * actual computer vision algorithmic code. Basically it allocates the requested image
 * unless that image is already non-NULL. It always leaves a non-NULL image as-is even
 * if that image's size, depth, and/or channels are different than the request.
 */
inline static void allocateOnDemand( Mat **img, Size size, int depth, int channels)
{
    if ( *img != NULL ) return;
   // *img.create( size, depth, channels );
    if ( *img == NULL )
    {
        fprintf(stderr, "Error: Couldn't allocate image. Out of memory?\n");
        exit(-1);
    }
}

int main( int argc, char** argv )
{
    const string filename=argv[1];
    Mat frameForProperties;

    //Open the input video
    //changed CvCapture to VideoCapture
    VideoCapture input_video(filename);

    //Check to make sure video exists and is in a OpenCV compatible format
    if(!input_video.isOpened()) {
        cout << "Cannot open file. Check path and format" << endl;
        return -1;
    }
    //old hack to get video properties, not sure if still needed
    //changed cvQueryFrame to input_video.read
    input_video.read(frameForProperties);

    /* Read the video's frame size out of the AVI. */
    //changed CvSize to Size, changed cvGetCaptureProperty to input_video.get
    Size frame_size;
    frame_size.height=(int)input_video.get(CAP_PROP_FRAME_HEIGHT);
    frame_size.width =(int)input_video.get(CAP_PROP_FRAME_WIDTH );

    /* Determine the number of frames in the AVI. */
    long number_of_frames;

    /* Go to the end of the AVI (ie: the fraction is "1") */
    //changed cvSetCaptureProperty to input_video.set
    input_video.set(CAP_PROP_POS_AVI_RATIO, 1. );

    /* Now that we're at the end, read the AVI position in frames */
    //changed cvCaptureProperty to input_video.get
    number_of_frames = (int) input_video.get(CAP_PROP_POS_FRAMES );

    /* Return to the beginning */
    //changed cvSetCaptureProperty to input_video.set
    input_video.set(CAP_PROP_POS_FRAMES, 0. );

    //Set up windows to display output
    //changed cvNamedWindow to namedWindow
    namedWindow("Optical Flow", WINDOW_AUTOSIZE);
    long current_frame=0;

    while(true) {
        //changed IplImage to Mat
        static Mat *frame = NULL, *frame1 = NULL, *frame1_1C = NULL, *frame2_1C =
        NULL, *eig_image = NULL, *temp_image = NULL, *pyramid1 = NULL, *pyramid2 = NULL;

        /* Go to the frame we want. Important if multiple frames are queried in
         * the loop which they of course are for optical flow. Note that the very
         * first call to this is actually not needed. (Because the correct position
         * is set outsite the for() loop.)
         */
        //changed cvSetCapture Property to input_video.set
        input_video.set(CAP_PROP_POS_FRAMES, current_frame );

        /* Get the next frame of the video.*/
        //changed cvQueryFrame to input_video >> *frame
        input_video >> *frame;
        if (frame == NULL) {
            /* Why did we get a NULL frame? We shouldn't be at the end. */
            cout << "Error: Hmm. The end came sooner than we thought" << endl;
            return -1;
        }
        /* Allocate another image if not already allocated.
         * Image has ONE challenge of color (ie: monochrome) with 8-bit "color" depth.
         * This is the image format OpenCV algorithms actually operate on (mostly).
         */
        allocateOnDemand( &frame1_1C, frame_size, CV_8U, 1 );

    }
        return 0;

}<commit_msg>with more code from the stanford site converted to cpp<commit_after>/* --Sparse Optical Flow Demo Program--
 * Updated based on code written by David Stavens (dstavens@robotics.stanford.edu)
 * http://robots.stanford.edu/cs223b05/notes/CS%20223-B%20T1%20stavens_opencv_optical_flow.pdf
 */

#include "opencv2/opencv.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"

using namespace std;
using namespace cv;

/* This is just an inline that allocates images. I did this to reduce clutter in the
 * actual computer vision algorithmic code. Basically it allocates the requested image
 * unless that image is already non-NULL. It always leaves a non-NULL image as-is even
 * if that image's size, depth, and/or channels are different than the request.
 */
inline static void allocateOnDemand( Mat **img, Size size, int depth, int channels)
{
    if ( *img != NULL ) return;
    //*img=create( size, depth, channels );
    if ( *img == NULL )
    {
        fprintf(stderr, "Error: Couldn't allocate image. Out of memory?\n");
        exit(-1);
    }
}

int main( int argc, char** argv )
{
    const string filename=argv[1];
    Mat frameForProperties;

    //Open the input video
    //changed CvCapture to VideoCapture
    VideoCapture input_video(filename);

    //Check to make sure video exists and is in a OpenCV compatible format
    if(!input_video.isOpened()) {
        cout << "Cannot open file. Check path and format" << endl;
        return -1;
    }
    //old hack to get video properties, not sure if still needed
    //changed cvQueryFrame to input_video.read
    input_video.read(frameForProperties);

    /* Read the video's frame size out of the AVI. */
    //changed CvSize to Size, changed cvGetCaptureProperty to input_video.get
    Size frame_size;
    frame_size.height=(int)input_video.get(CAP_PROP_FRAME_HEIGHT);
    frame_size.width =(int)input_video.get(CAP_PROP_FRAME_WIDTH );

    /* Determine the number of frames in the AVI. */
    long number_of_frames;

    /* Go to the end of the AVI (ie: the fraction is "1") */
    //changed cvSetCaptureProperty to input_video.set
    input_video.set(CAP_PROP_POS_AVI_RATIO, 1. );

    /* Now that we're at the end, read the AVI position in frames */
    //changed cvCaptureProperty to input_video.get
    number_of_frames = (int) input_video.get(CAP_PROP_POS_FRAMES );

    /* Return to the beginning */
    //changed cvSetCaptureProperty to input_video.set
    input_video.set(CAP_PROP_POS_FRAMES, 0. );

    //Set up windows to display output
    //changed cvNamedWindow to namedWindow
    namedWindow("Optical Flow", WINDOW_AUTOSIZE);
    long current_frame=0;

    while(true) {
        //changed IplImage to Mat
        static Mat *frame = NULL, *frame1 = NULL, *frame1_1C = NULL, *frame2_1C =
        NULL, *eig_image = NULL, *temp_image = NULL, *pyramid1 = NULL, *pyramid2 = NULL;

        /* Go to the frame we want. Important if multiple frames are queried in
         * the loop which they of course are for optical flow. Note that the very
         * first call to this is actually not needed. (Because the correct position
         * is set outsite the for() loop.)
         */
        //changed cvSetCapture Property to input_video.set
        input_video.set(CAP_PROP_POS_FRAMES, current_frame );

        /* Get the next frame of the video.*/
        //changed cvQueryFrame to input_video >> *frame
        input_video >> *frame;
        if (frame == NULL) {
            /* Why did we get a NULL frame? We shouldn't be at the end. */
            cout << "Error: Hmm. The end came sooner than we thought" << endl;
            return -1;
        }
        /* Allocate another image if not already allocated.
         * Image has ONE challenge of color (ie: monochrome) with 8-bit "color" depth.
         * This is the image format OpenCV algorithms actually operate on (mostly).
         */
        //probably take out allocate on demand in favor of making a Mat image with constructor
        //allocateOnDemand( &frame1_1C, frame_size, CV_8U, 1 );
        frame1_1C->create(frame_size, CV_8U);
        /* Convert whatever the AVI image format is into OpenCV's preferred format.
         * AND flip the image vertically. Flip is a shameless hack. OpenCV reads
         * in AVIs upside-down by default. (No comment :-))
         */

        //change cvConvertImage to flip
        cv::flip(*frame, *frame1_1C, 0);

        /* We'll make a full color backup of this frame so that we can draw on it.
         * (It's not the best idea to draw on the static memory space of cvQueryFrame().)
         */
        frame1->create(frame_size, CV_8U);
        cv::flip(*frame, *frame1, 0);

        /* Get the second frame of video. Sample principles as the first. */
        //changed cvQueryFrame to input_video >> *frame, followed frame1_1C procedure
        input_video >> *frame;
        if (frame == NULL)
        {
            fprintf(stderr, "Error: Hmm. The end came sooner than we thought.\n");
            return -1;
        }
        frame2_1C->create(frame_size, CV_8U );
        cv::flip(*frame, *frame2_1C, 0);

        /* Shi and Tomasi Feature Tracking! */
        /* Preparation: Allocate the necessary storage. */
        //change allocateOnDemand to ->create
        eig_image->create(frame_size, CV_32F);
        temp_image->create( frame_size, CV_32F);

        /* Preparation: This array will contain the features found in frame 1. */
        Point frame1_features[400];

        /* Preparation: BEFORE the function call this variable is the array size
         * (or the maximum number of features to find). AFTER the function call
         * this variable is the number of features actually found.
         */
        int number_of_features;

        /* I'm hardcoding this at 400. But you should make this a #define so that you can
         * change the number of features you use for an accuracy/speed tradeoff analysis.
         */
        number_of_features = 400;

        /* Actually run the Shi and Tomasi algorithm!!
         * "frame1_1C" is the input image.
         * "eig_image" and "temp_image" are just workspace for the algorithm.
         * The first ".01" specifies the minimum quality of the features (based on the
         eigenvalues).
         * The second ".01" specifies the minimum Euclidean distance between features.
         * "NULL" means use the entire input image. You could point to a part of the
         image.
         * WHEN THE ALGORITHM RETURNS:
         * "frame1_features" will contain the feature points.
         * "number_of_features" will be set to a value <= 400 indicating the number of
         feature points found.
         */
        goodFeaturesToTrack(frame1_1C, frame1_features, number_of_features, .01, .01);

        /* Pyramidal Lucas Kanade Optical Flow! */
        /* This array will contain the locations of the points from frame 1 in frame 2. */
        Point frame2_features[400];

        /* The i-th element of this array will be non-zero if and only if the i-th feature
         of
         * frame 1 was found in frame 2.
         */
        char optical_flow_found_feature[400];

        /* The i-th element of this array is the error in the optical flow for the i-th
         feature
         * of frame1 as found in frame 2. If the i-th feature was not found (see the
         array above)
         * I think the i-th entry in this array is undefined.
         */
        float optical_flow_feature_error[400];

        /* This is the window size to use to avoid the aperture problem (see slide
         "Optical Flow: Overview"). */
        Size optical_flow_window = Size(3,3);

        /* This termination criteria tells the algorithm to stop when it has either done
         20 iterations or when
         * epsilon is better than .3. You can play with these parameters for speed vs.
         accuracy but these values
         * work pretty well in many situations.
         */
        TermCriteria optical_flow_termination_criteria
        = cvTermCriteria( CV_TERMCRIT_ITER | CV_TERMCRIT_EPS, 20, .3 );

    }
        return 0;

}<|endoftext|>


<commit_before>/*********************************************************************************
 *
 * Inviwo - Interactive Visualization Workshop
 *
 * Copyright (c) 2014-2019 Inviwo Foundation
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *********************************************************************************/

#include <modules/hdf5/hdf5utils.h>

namespace inviwo {

namespace hdf5 {

Paths findpaths(const H5::Group& grp, const Path& path, const std::string& type) {
    Paths paths;

    if (isOfType(grp, type)) {
        paths.push_back(path);
    } else {
        for (hsize_t i = 0; i < grp.getNumObjs(); i++) {
            std::string childName = grp.getObjnameByIdx(i);
            if (grp.getObjTypeByIdx(i) == H5G_GROUP) {
                H5::Group child = grp.openGroup(childName);
                Paths newpaths = findpaths(child, path + childName, type);
                paths.insert(paths.end(), newpaths.begin(), newpaths.end());
            }
        }
    }
    return paths;
}

VolumeInfos getVolumeInfo(const H5::DataSet& ds, const Path& path) {
    auto size = std::make_unique<hsize_t[]>(ds.getSpace().getSimpleExtentNdims());
    ds.getSpace().getSimpleExtentDims(size.get());
    int sub_densities = (int)size[0];

    VolumeInfos paths;

    for (int i = 0; i < sub_densities; i++) {
        VolumeInfo info;
        info.path_ = path;
        info.index_ = i;
        info.dim_.x = size[1];
        info.dim_.y = size[2];
        info.dim_.z = size[3];

        paths.push_back(info);
    }

    return paths;
}

bool isOfType(const H5::Group& grp, const std::string& type) {
    bool result = false;
    try {
        if (grp.attrExists("type")) {
            H5::Attribute attr = grp.openAttribute("type");
            H5::DataType dt = attr.getDataType();

            if (dt.getClass() == H5T_STRING && dt.isVariableStr()) {
                H5std_string val;
                attr.read(dt, val);
                if (val == type) {
                    result = true;
                }
            }
            dt.close();
            attr.close();
        }
    } catch (const H5::AttributeIException& error) {
    }
    return result;
}

}  // namespace hdf5

}  // namespace inviwo
<commit_msg>HDF5: warning fix<commit_after>/*********************************************************************************
 *
 * Inviwo - Interactive Visualization Workshop
 *
 * Copyright (c) 2014-2019 Inviwo Foundation
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *********************************************************************************/

#include <modules/hdf5/hdf5utils.h>

namespace inviwo {

namespace hdf5 {

Paths findpaths(const H5::Group& grp, const Path& path, const std::string& type) {
    Paths paths;

    if (isOfType(grp, type)) {
        paths.push_back(path);
    } else {
        for (hsize_t i = 0; i < grp.getNumObjs(); i++) {
            std::string childName = grp.getObjnameByIdx(i);
            if (grp.getObjTypeByIdx(i) == H5G_GROUP) {
                H5::Group child = grp.openGroup(childName);
                Paths newpaths = findpaths(child, path + childName, type);
                paths.insert(paths.end(), newpaths.begin(), newpaths.end());
            }
        }
    }
    return paths;
}

VolumeInfos getVolumeInfo(const H5::DataSet& ds, const Path& path) {
    auto size = std::make_unique<hsize_t[]>(ds.getSpace().getSimpleExtentNdims());
    ds.getSpace().getSimpleExtentDims(size.get());
    int sub_densities = (int)size[0];

    VolumeInfos paths;

    for (int i = 0; i < sub_densities; i++) {
        VolumeInfo info;
        info.path_ = path;
        info.index_ = i;
        info.dim_.x = size[1];
        info.dim_.y = size[2];
        info.dim_.z = size[3];

        paths.push_back(info);
    }

    return paths;
}

bool isOfType(const H5::Group& grp, const std::string& type) {
    bool result = false;
    try {
        if (grp.attrExists("type")) {
            H5::Attribute attr = grp.openAttribute("type");
            H5::DataType dt = attr.getDataType();

            if (dt.getClass() == H5T_STRING && dt.isVariableStr()) {
                H5std_string val;
                attr.read(dt, val);
                if (val == type) {
                    result = true;
                }
            }
            dt.close();
            attr.close();
        }
    } catch (const H5::AttributeIException&) {
    }
    return result;
}

}  // namespace hdf5

}  // namespace inviwo
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "testing/gtest/include/gtest/gtest.h"
#include "webrtc/modules/audio_coding/neteq/tools/neteq_performance_test.h"
#include "webrtc/test/testsupport/perf_test.h"
#include "webrtc/typedefs.h"

// Disabled on Android since all tests currently fail (webrtc:3770).
#ifndef WEBRTC_ANDROID

// Runs a test with 10% packet losses and 10% clock drift, to exercise
// both loss concealment and time-stretching code.
TEST(NetEqPerformanceTest, Run) {
  const int kSimulationTimeMs = 10000000;
  const int kLossPeriod = 10;  // Drop every 10th packet.
  const double kDriftFactor = 0.1;
  int64_t runtime = webrtc::test::NetEqPerformanceTest::Run(
      kSimulationTimeMs, kLossPeriod, kDriftFactor);
  ASSERT_GT(runtime, 0);
  webrtc::test::PrintResult(
      "neteq_performance", "", "10_pl_10_drift", runtime, "ms", true);
}

// Runs a test with neither packet losses nor clock drift, to put
// emphasis on the "good-weather" code path, which is presumably much
// more lightweight.
TEST(NetEqPerformanceTest, RunClean) {
  const int kSimulationTimeMs = 10000000;
  const int kLossPeriod = 0;  // No losses.
  const double kDriftFactor = 0.0;  // No clock drift.
  int64_t runtime = webrtc::test::NetEqPerformanceTest::Run(
      kSimulationTimeMs, kLossPeriod, kDriftFactor);
  ASSERT_GT(runtime, 0);
  webrtc::test::PrintResult(
      "neteq_performance", "", "0_pl_0_drift", runtime, "ms", true);
}

#endif // !WEBRTC_ANDROID
<commit_msg>Re-enable neteq_performance_unittest.cc for android.<commit_after>/*
 *  Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "testing/gtest/include/gtest/gtest.h"
#include "webrtc/modules/audio_coding/neteq/tools/neteq_performance_test.h"
#include "webrtc/test/testsupport/perf_test.h"
#include "webrtc/typedefs.h"

// Runs a test with 10% packet losses and 10% clock drift, to exercise
// both loss concealment and time-stretching code.
TEST(NetEqPerformanceTest, Run) {
  const int kSimulationTimeMs = 10000000;
  const int kLossPeriod = 10;  // Drop every 10th packet.
  const double kDriftFactor = 0.1;
  int64_t runtime = webrtc::test::NetEqPerformanceTest::Run(
      kSimulationTimeMs, kLossPeriod, kDriftFactor);
  ASSERT_GT(runtime, 0);
  webrtc::test::PrintResult(
      "neteq_performance", "", "10_pl_10_drift", runtime, "ms", true);
}

// Runs a test with neither packet losses nor clock drift, to put
// emphasis on the "good-weather" code path, which is presumably much
// more lightweight.
TEST(NetEqPerformanceTest, RunClean) {
  const int kSimulationTimeMs = 10000000;
  const int kLossPeriod = 0;  // No losses.
  const double kDriftFactor = 0.0;  // No clock drift.
  int64_t runtime = webrtc::test::NetEqPerformanceTest::Run(
      kSimulationTimeMs, kLossPeriod, kDriftFactor);
  ASSERT_GT(runtime, 0);
  webrtc::test::PrintResult(
      "neteq_performance", "", "0_pl_0_drift", runtime, "ms", true);
}
<|endoftext|>