<commit_before>/******************************************************************************
 *       SOFA, Simulation Open-Framework Architecture, version 1.0 beta 3      *
 *                (c) 2006-2008 MGH, INRIA, USTL, UJF, CNRS                    *
 *                                                                             *
 * This program is free software; you can redistribute it and/or modify it     *
 * under the terms of the GNU General Public License as published by the Free  *
 * Software Foundation; either version 2 of the License, or (at your option)   *
 * any later version.                                                          *
 *                                                                             *
 * This program is distributed in the hope that it will be useful, but WITHOUT *
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       *
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for    *
 * more details.                                                               *
 *                                                                             *
 * You should have received a copy of the GNU General Public License along     *
 * with this program; if not, write to the Free Software Foundation, Inc., 51  *
 * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.                   *
 *******************************************************************************
 *                            SOFA :: Applications                             *
 *                                                                             *
 * Authors: M. Adam, J. Allard, B. Andre, P-J. Bensoussan, S. Cotin, C. Duriez,*
 * H. Delingette, F. Falipou, F. Faure, S. Fonteneau, L. Heigeas, C. Mendoza,  *
 * M. Nesme, P. Neumann, J-P. de la Plata Alcade, F. Poyer and F. Roy          *
 *                                                                             *
 * Contact information: contact@sofa-framework.org                             *
 ******************************************************************************/
#include "SofaPluginManager.h"
#include "FileManagement.h"

#ifdef SOFA_QT4
//#include <Q3Header>
//#include <Q3PopupMenu>
#include <QMessageBox>
#include <QLibrary>
#include <QSettings>
#include <QTextEdit>
#include <QPushButton>
#else
//#include <qheader.h>
//#include <qpopupmenu.h>
#include <qmessagebox.h>
#include <qlibrary.h>
#include <qsettings.h>
#include <qtextedit.h>
#include <qpushbutton.h>
#endif

#include <iostream>

#ifndef SOFA_QT4
typedef QListViewItem Q3ListViewItem;
#endif

namespace sofa
{
namespace gui
{
namespace qt
{

SofaPluginManager::SofaPluginManager()
{
    // SIGNAL / SLOTS CONNECTIONS
    this->connect(buttonAdd, SIGNAL(clicked() ),  this, SLOT( addLibrary() ));
    this->connect(buttonRemove, SIGNAL(clicked() ),  this, SLOT( removeLibrary() ));
#ifdef SOFA_QT4
    this->connect(listPlugins, SIGNAL(selectionChanged(Q3ListViewItem*) ), this, SLOT(updateComponentList(Q3ListViewItem*) ));
    this->connect(listPlugins, SIGNAL(selectionChanged(Q3ListViewItem*) ), this, SLOT(updateDescription(Q3ListViewItem*) ));
#else
    this->connect(listPlugins, SIGNAL(selectionChanged(QListViewItem*) ), this, SLOT(updateComponentList(QListViewItem*) ));
    this->connect(listPlugins, SIGNAL(selectionChanged(QListViewItem*) ), this, SLOT(updateDescription(QListViewItem*) ));
#endif
    //read the plugin list in the settings
    QSettings settings;
    settings.setPath( "SOFA-FRAMEWORK", "SOFA",QSettings::User);

// 			int size = settings.beginReadArray("plugins");
    settings.beginGroup("/plugins");
    int size = settings.readNumEntry("/size");

    listPlugins->clear();
    typedef void (*componentLoader)();
    typedef char* (*componentStr)();

    for (int i=1 ; i<=size; i++)
    {
// 				settings.setArrayIndex(i);
        QString titi;
        titi = titi.setNum(i);

        settings.beginGroup(titi);
        QString sfile = settings.readEntry("/location");
        settings.endGroup();

        //load the plugin libs
        QLibrary lib(sfile);
        componentLoader componentLoaderFunc = (componentLoader) lib.resolve("initExternalModule");
        componentStr componentNameFunc = (componentStr) lib.resolve("getModuleName");

        //fill the list view
        if (componentLoaderFunc && componentNameFunc)
        {
            componentLoaderFunc();
            QString sname(componentNameFunc());

            Q3ListViewItem * item = new Q3ListViewItem(listPlugins, sname, sfile);
            item->setSelectable(true);
        }
    }
// 			settings.endArray();
    settings.endGroup();
}

void SofaPluginManager::addLibrary()
{
    //get the lib to load
    QString sfile = getOpenFileName ( this, NULL, "dynamic library (*.dll *.so *.dylib)", "load library dialog",  "Choose the component library to load" );
    if(sfile=="")
        return;

    //try to load the lib
    QLibrary lib(sfile);
    if (!lib.load())
        std::cout<<"Error loading library " << sfile.latin1() <<std::endl;

    //get the functions
    typedef void (*componentLoader)();
    typedef char* (*componentStr)();
    componentLoader componentLoaderFunc = (componentLoader) lib.resolve("initExternalModule");
    componentStr componentNameFunc = (componentStr) lib.resolve("getModuleName");

    if (componentLoaderFunc && componentNameFunc)
    {
        //fill the list view
        componentLoaderFunc();
        QString sname(componentNameFunc());
        Q3ListViewItem * item = new Q3ListViewItem(listPlugins, sname, sfile);
        item->setSelectable(true);

        //add to the settings (to record it)
        QSettings settings;
        settings.setPath( "SOFA-FRAMEWORK", "SOFA",QSettings::User);
        settings.beginGroup("/plugins");
        int size = settings.readNumEntry("/size");
        QString titi;
        titi = titi.setNum(size+1);
        settings.beginGroup(titi);
        settings.writeEntry("/location", sfile);
        settings.endGroup();
        settings.writeEntry("/size", size+1);
        settings.endGroup();
    }
    else
    {
        QMessageBox * mbox = new QMessageBox(this,"library loading error");
        mbox->setText("Unable to load this library");
        mbox->show();
    }
}

void SofaPluginManager::removeLibrary()
{
    //get the selected item
    Q3ListViewItem * curItem = listPlugins->selectedItem();
    QString location = curItem->text(1); //get the location value
    //remove it from the list view
    listPlugins->removeItem(curItem);

    //remove it from the settings
    QSettings settings;
    settings.setPath( "SOFA-FRAMEWORK", "SOFA",QSettings::User);
    settings.beginGroup("/plugins");
    int size = settings.readNumEntry("/size");

    for (int i=1 ; i<=size; i++)
    {
        QString titi;
        titi = titi.setNum(i);
        settings.beginGroup(titi);
        QString sfile = settings.readEntry("/location");
        if (sfile == location)
            settings.removeEntry("/location");
        settings.endGroup();
    }

    settings.endGroup();
}

void SofaPluginManager::updateComponentList(Q3ListViewItem* curItem)
{
    //update the component list when an item is selected
    listComponents->clear();
    QString location = curItem->text(1); //get the location value
    QLibrary lib(location);
    typedef char* (*componentStr)();
    componentStr componentListFunc = (componentStr) lib.resolve("getModuleComponentList");
    if(componentListFunc)
    {
        QString cpts( componentListFunc() );
        cpts.replace(", ","\n");
        cpts.replace(",","\n");
        listComponents->setText(cpts);
    }
}

void SofaPluginManager::updateDescription(Q3ListViewItem* curItem)
{
    //update the component list when an item is selected
    description->clear();
    QString location = curItem->text(1); //get the location value
    QLibrary lib(location);
    typedef char* (*componentStr)();
    componentStr componentDescFunc = (componentStr) lib.resolve("getModuleDescription");
    if(componentDescFunc)
    {
        description->setText(QString(componentDescFunc()));
    }
}

}
}
}

<commit_msg>r4171/sofa-dev : CHANGE: minor changes in the API of the SofaPluginManager<commit_after>/******************************************************************************
 *       SOFA, Simulation Open-Framework Architecture, version 1.0 beta 3      *
 *                (c) 2006-2008 MGH, INRIA, USTL, UJF, CNRS                    *
 *                                                                             *
 * This program is free software; you can redistribute it and/or modify it     *
 * under the terms of the GNU General Public License as published by the Free  *
 * Software Foundation; either version 2 of the License, or (at your option)   *
 * any later version.                                                          *
 *                                                                             *
 * This program is distributed in the hope that it will be useful, but WITHOUT *
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       *
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for    *
 * more details.                                                               *
 *                                                                             *
 * You should have received a copy of the GNU General Public License along     *
 * with this program; if not, write to the Free Software Foundation, Inc., 51  *
 * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.                   *
 *******************************************************************************
 *                            SOFA :: Applications                             *
 *                                                                             *
 * Authors: M. Adam, J. Allard, B. Andre, P-J. Bensoussan, S. Cotin, C. Duriez,*
 * H. Delingette, F. Falipou, F. Faure, S. Fonteneau, L. Heigeas, C. Mendoza,  *
 * M. Nesme, P. Neumann, J-P. de la Plata Alcade, F. Poyer and F. Roy          *
 *                                                                             *
 * Contact information: contact@sofa-framework.org                             *
 ******************************************************************************/
#include "SofaPluginManager.h"
#include "FileManagement.h"

#ifdef SOFA_QT4
//#include <Q3Header>
//#include <Q3PopupMenu>
#include <QMessageBox>
#include <QLibrary>
#include <QSettings>
#include <QTextEdit>
#include <QPushButton>
#else
//#include <qheader.h>
//#include <qpopupmenu.h>
#include <qmessagebox.h>
#include <qlibrary.h>
#include <qsettings.h>
#include <qtextedit.h>
#include <qpushbutton.h>
#endif

#include <iostream>

#ifndef SOFA_QT4
typedef QListViewItem Q3ListViewItem;
#endif

namespace sofa
{
namespace gui
{
namespace qt
{

SofaPluginManager::SofaPluginManager()
{
    // SIGNAL / SLOTS CONNECTIONS
    this->connect(buttonAdd, SIGNAL(clicked() ),  this, SLOT( addLibrary() ));
    this->connect(buttonRemove, SIGNAL(clicked() ),  this, SLOT( removeLibrary() ));
#ifdef SOFA_QT4
    this->connect(listPlugins, SIGNAL(selectionChanged(Q3ListViewItem*) ), this, SLOT(updateComponentList(Q3ListViewItem*) ));
    this->connect(listPlugins, SIGNAL(selectionChanged(Q3ListViewItem*) ), this, SLOT(updateDescription(Q3ListViewItem*) ));
#else
    this->connect(listPlugins, SIGNAL(selectionChanged(QListViewItem*) ), this, SLOT(updateComponentList(QListViewItem*) ));
    this->connect(listPlugins, SIGNAL(selectionChanged(QListViewItem*) ), this, SLOT(updateDescription(QListViewItem*) ));
#endif
    //read the plugin list in the settings
    QSettings settings;
    settings.setPath( "SOFA-FRAMEWORK", "SOFA",QSettings::User);

// 			int size = settings.beginReadArray("plugins");
    settings.beginGroup("/plugins");
    int size = settings.readNumEntry("/size");

    listPlugins->clear();
    typedef void (*componentLoader)();
    typedef const char* (*componentStr)();

    for (int i=1 ; i<=size; i++)
    {
// 				settings.setArrayIndex(i);
        QString titi;
        titi = titi.setNum(i);

        settings.beginGroup(titi);
        QString sfile = settings.readEntry("/location");
        settings.endGroup();

        //load the plugin libs
        QLibrary lib(sfile);
        componentLoader componentLoaderFunc = (componentLoader) lib.resolve("initExternalModule");
        componentStr componentNameFunc = (componentStr) lib.resolve("getModuleName");

        //fill the list view
        if (componentLoaderFunc && componentNameFunc)
        {
            componentLoaderFunc();
            QString sname(componentNameFunc());

            Q3ListViewItem * item = new Q3ListViewItem(listPlugins, sname, sfile);
            item->setSelectable(true);
        }
    }
// 			settings.endArray();
    settings.endGroup();
}

void SofaPluginManager::addLibrary()
{
    //get the lib to load
    QString sfile = getOpenFileName ( this, NULL, "dynamic library (*.dll *.so *.dylib)", "load library dialog",  "Choose the component library to load" );
    if(sfile=="")
        return;

    //try to load the lib
    QLibrary lib(sfile);
    if (!lib.load())
        std::cout<<"Error loading library " << sfile.latin1() <<std::endl;

    //get the functions
    typedef void (*componentLoader)();
    typedef const char* (*componentStr)();
    componentLoader componentLoaderFunc = (componentLoader) lib.resolve("initExternalModule");
    componentStr componentNameFunc = (componentStr) lib.resolve("getModuleName");

    if (componentLoaderFunc && componentNameFunc)
    {
        //fill the list view
        componentLoaderFunc();
        QString sname(componentNameFunc());
        Q3ListViewItem * item = new Q3ListViewItem(listPlugins, sname, sfile);
        item->setSelectable(true);

        //add to the settings (to record it)
        QSettings settings;
        settings.setPath( "SOFA-FRAMEWORK", "SOFA",QSettings::User);
        settings.beginGroup("/plugins");
        int size = settings.readNumEntry("/size");
        QString titi;
        titi = titi.setNum(size+1);
        settings.beginGroup(titi);
        settings.writeEntry("/location", sfile);
        settings.endGroup();
        settings.writeEntry("/size", size+1);
        settings.endGroup();
    }
    else
    {
        QMessageBox * mbox = new QMessageBox(this,"library loading error");
        mbox->setText("Unable to load this library");
        mbox->show();
    }
}

void SofaPluginManager::removeLibrary()
{
    //get the selected item
    Q3ListViewItem * curItem = listPlugins->selectedItem();
    QString location = curItem->text(1); //get the location value
    //remove it from the list view
    listPlugins->removeItem(curItem);

    //remove it from the settings
    QSettings settings;
    settings.setPath( "SOFA-FRAMEWORK", "SOFA",QSettings::User);
    settings.beginGroup("/plugins");
    int size = settings.readNumEntry("/size");

    for (int i=1 ; i<=size; i++)
    {
        QString titi;
        titi = titi.setNum(i);
        settings.beginGroup(titi);
        QString sfile = settings.readEntry("/location");
        if (sfile == location)
            settings.removeEntry("/location");
        settings.endGroup();
    }

    settings.endGroup();
}

void SofaPluginManager::updateComponentList(Q3ListViewItem* curItem)
{
    //update the component list when an item is selected
    listComponents->clear();
    QString location = curItem->text(1); //get the location value
    QLibrary lib(location);
    typedef const char* (*componentStr)();
    componentStr componentListFunc = (componentStr) lib.resolve("getModuleComponentList");
    if(componentListFunc)
    {
        QString cpts( componentListFunc() );
        cpts.replace(", ","\n");
        cpts.replace(",","\n");
        listComponents->setText(cpts);
    }
}

void SofaPluginManager::updateDescription(Q3ListViewItem* curItem)
{
    //update the component list when an item is selected
    description->clear();
    QString location = curItem->text(1); //get the location value
    QLibrary lib(location);
    typedef const char* (*componentStr)();
    componentStr componentDescFunc = (componentStr) lib.resolve("getModuleDescription");
    if(componentDescFunc)
    {
        description->setText(QString(componentDescFunc()));
    }
}

}
}
}

<|endoftext|>


<commit_before>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_MAPPER_FINITEVOLUME_HH
#define DUNE_GDT_MAPPER_FINITEVOLUME_HH

#include <type_traits>

#include <dune/common/dynvector.hh>
#include <dune/common/typetraits.hh>

#include "../../mapper/interface.hh"

namespace Dune {
namespace GDT {
namespace Mapper {

// forward, to be used in the traits
template <class GridViewImp, int rangeDim = 1, int rangeDimCols = 1>
class FiniteVolume;

template <class GridViewImp, int rangeDim, int rangeDimCols>
class FiniteVolumeTraits
{
  static_assert(rangeDim >= 1, "Really?");
  static_assert(rangeDimCols >= 1, "Really?");

public:
  typedef GridViewImp GridViewType;
  typedef FiniteVolume<GridViewType, rangeDim, rangeDimCols> derived_type;
  typedef typename GridViewImp::IndexSet BackendType;
};

template <class GridViewImp>
class FiniteVolume<GridViewImp, 1, 1> : public MapperInterface<FiniteVolumeTraits<GridViewImp, 1, 1>>
{
  typedef MapperInterface<FiniteVolumeTraits<GridViewImp, 1, 1>> InterfaceType;

public:
  typedef FiniteVolumeTraits<GridViewImp, 1, 1> Traits;
  typedef typename Traits::GridViewType GridViewType;
  typedef typename Traits::BackendType BackendType;

  typedef typename GridViewType::template Codim<0>::Entity EntityType;

  FiniteVolume(const GridViewType& grid_view)
    : backend_(grid_view.indexSet())
  {
  }

  const BackendType& backend() const
  {
    return backend_;
  }

  size_t size() const
  {
    return backend_.size(0);
  }

  size_t numDofs(const EntityType& /*entity*/) const
  {
    return 1;
  }

  size_t maxNumDofs() const
  {
    return 1;
  }

  void globalIndices(const EntityType& entity, Dune::DynamicVector<size_t>& ret) const
  {
    if (ret.size() < 1)
      ret.resize(1);
    ret[0] = mapToGlobal(entity, 0);
  } // ... globalIndices(...)

  using InterfaceType::globalIndices;

  size_t mapToGlobal(const EntityType& entity, const size_t&
#ifndef NDEBUG
                                                   localIndex
#else
/*localIndex*/
#endif
                     ) const
  {
    assert(localIndex == 0);
    return backend_.index(entity);
  } // ... mapToGlobal(...)

private:
  const BackendType& backend_;
}; // class FiniteVolume< ..., 1, 1 >

template <class GridViewImp, int rangeDim>
class FiniteVolume<GridViewImp, rangeDim, 1> : public MapperInterface<FiniteVolumeTraits<GridViewImp, rangeDim, 1>>
{
  typedef MapperInterface<FiniteVolumeTraits<GridViewImp, rangeDim, 1>> InterfaceType;
  static const unsigned int dimRange = rangeDim;

public:
  typedef FiniteVolumeTraits<GridViewImp, rangeDim, 1> Traits;
  typedef typename Traits::GridViewType GridViewType;
  typedef typename Traits::BackendType BackendType;

  typedef typename GridViewType::template Codim<0>::Entity EntityType;

  FiniteVolume(const GridViewType& grid_view)
    : backend_(grid_view.indexSet())
  {
  }

  const BackendType& backend() const
  {
    return backend_;
  }

  size_t size() const
  {
    return dimRange * backend_.size(0);
  }

  size_t numDofs(const EntityType& /*entity*/) const
  {
    return dimRange;
  }

  size_t maxNumDofs() const
  {
    return dimRange;
  }

  void globalIndices(const EntityType& entity, Dune::DynamicVector<size_t>& ret) const
  {
    if (ret.size() < dimRange)
      ret.resize(dimRange);
    const size_t base = dimRange * backend_.index(entity);
    for (size_t ii = 0; ii < dimRange; ++ii)
      ret[ii] = base + ii;
  } // ... globalIndices(...)

  using InterfaceType::globalIndices;

  size_t mapToGlobal(const EntityType& entity, const size_t& localIndex) const
  {
    assert(localIndex < dimRange);
    return (dimRange * backend_.index(entity)) + localIndex;
  } // ... mapToGlobal(...)

private:
  const BackendType& backend_;
}; // class FiniteVolume< ..., rangeDim, 1 >

} // namespace Mapper
} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_MAPPER_FINITEVOLUME_HH
<commit_msg>[playground.mapper.finitevolume] use UNUSED_UNLESS_DEBUG<commit_after>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_MAPPER_FINITEVOLUME_HH
#define DUNE_GDT_MAPPER_FINITEVOLUME_HH

#include <type_traits>

#include <dune/common/dynvector.hh>
#include <dune/common/typetraits.hh>

#include <dune/stuff/common/debug.hh>

#include "../../mapper/interface.hh"

namespace Dune {
namespace GDT {
namespace Mapper {

// forward, to be used in the traits
template <class GridViewImp, int rangeDim = 1, int rangeDimCols = 1>
class FiniteVolume;

template <class GridViewImp, int rangeDim, int rangeDimCols>
class FiniteVolumeTraits
{
  static_assert(rangeDim >= 1, "Really?");
  static_assert(rangeDimCols >= 1, "Really?");

public:
  typedef GridViewImp GridViewType;
  typedef FiniteVolume<GridViewType, rangeDim, rangeDimCols> derived_type;
  typedef typename GridViewImp::IndexSet BackendType;
};

template <class GridViewImp>
class FiniteVolume<GridViewImp, 1, 1> : public MapperInterface<FiniteVolumeTraits<GridViewImp, 1, 1>>
{
  typedef MapperInterface<FiniteVolumeTraits<GridViewImp, 1, 1>> InterfaceType;

public:
  typedef FiniteVolumeTraits<GridViewImp, 1, 1> Traits;
  typedef typename Traits::GridViewType GridViewType;
  typedef typename Traits::BackendType BackendType;

  typedef typename GridViewType::template Codim<0>::Entity EntityType;

  FiniteVolume(const GridViewType& grid_view)
    : backend_(grid_view.indexSet())
  {
  }

  const BackendType& backend() const
  {
    return backend_;
  }

  size_t size() const
  {
    return backend_.size(0);
  }

  size_t numDofs(const EntityType& /*entity*/) const
  {
    return 1;
  }

  size_t maxNumDofs() const
  {
    return 1;
  }

  void globalIndices(const EntityType& entity, Dune::DynamicVector<size_t>& ret) const
  {
    if (ret.size() < 1)
      ret.resize(1);
    ret[0] = mapToGlobal(entity, 0);
  } // ... globalIndices(...)

  using InterfaceType::globalIndices;

  size_t mapToGlobal(const EntityType& entity, const size_t& UNUSED_UNLESS_DEBUG(localIndex)) const
  {
    assert(localIndex == 0);
    return backend_.index(entity);
  } // ... mapToGlobal(...)

private:
  const BackendType& backend_;
}; // class FiniteVolume< ..., 1, 1 >

template <class GridViewImp, int rangeDim>
class FiniteVolume<GridViewImp, rangeDim, 1> : public MapperInterface<FiniteVolumeTraits<GridViewImp, rangeDim, 1>>
{
  typedef MapperInterface<FiniteVolumeTraits<GridViewImp, rangeDim, 1>> InterfaceType;
  static const unsigned int dimRange = rangeDim;

public:
  typedef FiniteVolumeTraits<GridViewImp, rangeDim, 1> Traits;
  typedef typename Traits::GridViewType GridViewType;
  typedef typename Traits::BackendType BackendType;

  typedef typename GridViewType::template Codim<0>::Entity EntityType;

  FiniteVolume(const GridViewType& grid_view)
    : backend_(grid_view.indexSet())
  {
  }

  const BackendType& backend() const
  {
    return backend_;
  }

  size_t size() const
  {
    return dimRange * backend_.size(0);
  }

  size_t numDofs(const EntityType& /*entity*/) const
  {
    return dimRange;
  }

  size_t maxNumDofs() const
  {
    return dimRange;
  }

  void globalIndices(const EntityType& entity, Dune::DynamicVector<size_t>& ret) const
  {
    if (ret.size() < dimRange)
      ret.resize(dimRange);
    const size_t base = dimRange * backend_.index(entity);
    for (size_t ii = 0; ii < dimRange; ++ii)
      ret[ii] = base + ii;
  } // ... globalIndices(...)

  using InterfaceType::globalIndices;

  size_t mapToGlobal(const EntityType& entity, const size_t& localIndex) const
  {
    assert(localIndex < dimRange);
    return (dimRange * backend_.index(entity)) + localIndex;
  } // ... mapToGlobal(...)

private:
  const BackendType& backend_;
}; // class FiniteVolume< ..., rangeDim, 1 >

} // namespace Mapper
} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_MAPPER_FINITEVOLUME_HH
<|endoftext|>


<commit_before>// Copyright 2010, Shuo Chen.  All rights reserved.
// http://code.google.com/p/muduo/
//
// Use of this source code is governed by a BSD-style license
// that can be found in the License file.

// Author: Shuo Chen (chenshuo at chenshuo dot com)

#include <muduo/net/TcpServer.h>

#include <muduo/base/Logging.h>
#include <muduo/net/Acceptor.h>
#include <muduo/net/EventLoop.h>
#include <muduo/net/EventLoopThreadPool.h>
#include <muduo/net/SocketsOps.h>

#include <boost/bind.hpp>

#include <stdio.h>  // snprintf

using namespace muduo;
using namespace muduo::net;

TcpServer::TcpServer(EventLoop* loop,
                     const InetAddress& listenAddr,
                     const string& nameArg)
  : loop_(CHECK_NOTNULL(loop)),
    hostport_(listenAddr.toIpPort()),
    name_(nameArg),
    acceptor_(new Acceptor(loop, listenAddr)),
    threadPool_(new EventLoopThreadPool(loop)),
    connectionCallback_(defaultConnectionCallback),
    messageCallback_(defaultMessageCallback),
    started_(false),
    nextConnId_(1)
{
  acceptor_->setNewConnectionCallback(
      boost::bind(&TcpServer::newConnection, this, _1, _2));
}

TcpServer::~TcpServer()
{
  loop_->assertInLoopThread();
  LOG_TRACE << "TcpServer::~TcpServer [" << name_ << "] destructing";

  for (ConnectionMap::iterator it(connections_.begin());
      it != connections_.end(); ++it)
  {
    TcpConnectionPtr conn = it->second;
    it->second.reset();
    conn->getLoop()->runInLoop(
      boost::bind(&TcpConnection::connectDestroyed, conn));
    conn.reset();
  }
}

void TcpServer::setThreadNum(int numThreads)
{
  assert(0 <= numThreads);
  threadPool_->setThreadNum(numThreads);
}

void TcpServer::start()
{
  if (!started_)
  {
    started_ = true;
    threadPool_->start(threadInitCallback_);
  }

  if (!acceptor_->listenning())
  {
    loop_->runInLoop(
        boost::bind(&Acceptor::listen, get_pointer(acceptor_)));
  }
}

void TcpServer::newConnection(int sockfd, const InetAddress& peerAddr)
{
  loop_->assertInLoopThread();
  EventLoop* ioLoop = threadPool_->getNextLoop();
  char buf[32];
  snprintf(buf, sizeof buf, ":%s#%d", hostport_.c_str(), nextConnId_);
  ++nextConnId_;
  string connName = name_ + buf;

  LOG_INFO << "TcpServer::newConnection [" << name_
           << "] - new connection [" << connName
           << "] from " << peerAddr.toIpPort();
  InetAddress localAddr(sockets::getLocalAddr(sockfd));
  // FIXME poll with zero timeout to double confirm the new connection
  // FIXME use make_shared if necessary
  TcpConnectionPtr conn(new TcpConnection(ioLoop,
                                          connName,
                                          sockfd,
                                          localAddr,
                                          peerAddr));
  connections_[connName] = conn;
  conn->setConnectionCallback(connectionCallback_);
  conn->setMessageCallback(messageCallback_);
  conn->setWriteCompleteCallback(writeCompleteCallback_);
  conn->setCloseCallback(
      boost::bind(&TcpServer::removeConnection, this, _1)); // FIXME: unsafe
  ioLoop->runInLoop(boost::bind(&TcpConnection::connectEstablished, conn));
}

void TcpServer::removeConnection(const TcpConnectionPtr& conn)
{
  // FIXME: unsafe
  loop_->runInLoop(boost::bind(&TcpServer::removeConnectionInLoop, this, conn));
}

void TcpServer::removeConnectionInLoop(const TcpConnectionPtr& conn)
{
  loop_->assertInLoopThread();
  LOG_INFO << "TcpServer::removeConnectionInLoop [" << name_
           << "] - connection " << conn->name();
  size_t n = connections_.erase(conn->name());
  (void)n;
  assert(n == 1);
  EventLoop* ioLoop = conn->getLoop();
  ioLoop->queueInLoop(
      boost::bind(&TcpConnection::connectDestroyed, conn));
  if (!ioLoop->isInLoopThread())
  {
    ioLoop->wakeup();
  }
}

<commit_msg>remove unnecessary code<commit_after>// Copyright 2010, Shuo Chen.  All rights reserved.
// http://code.google.com/p/muduo/
//
// Use of this source code is governed by a BSD-style license
// that can be found in the License file.

// Author: Shuo Chen (chenshuo at chenshuo dot com)

#include <muduo/net/TcpServer.h>

#include <muduo/base/Logging.h>
#include <muduo/net/Acceptor.h>
#include <muduo/net/EventLoop.h>
#include <muduo/net/EventLoopThreadPool.h>
#include <muduo/net/SocketsOps.h>

#include <boost/bind.hpp>

#include <stdio.h>  // snprintf

using namespace muduo;
using namespace muduo::net;

TcpServer::TcpServer(EventLoop* loop,
                     const InetAddress& listenAddr,
                     const string& nameArg)
  : loop_(CHECK_NOTNULL(loop)),
    hostport_(listenAddr.toIpPort()),
    name_(nameArg),
    acceptor_(new Acceptor(loop, listenAddr)),
    threadPool_(new EventLoopThreadPool(loop)),
    connectionCallback_(defaultConnectionCallback),
    messageCallback_(defaultMessageCallback),
    started_(false),
    nextConnId_(1)
{
  acceptor_->setNewConnectionCallback(
      boost::bind(&TcpServer::newConnection, this, _1, _2));
}

TcpServer::~TcpServer()
{
  loop_->assertInLoopThread();
  LOG_TRACE << "TcpServer::~TcpServer [" << name_ << "] destructing";

  for (ConnectionMap::iterator it(connections_.begin());
      it != connections_.end(); ++it)
  {
    TcpConnectionPtr conn = it->second;
    it->second.reset();
    conn->getLoop()->runInLoop(
      boost::bind(&TcpConnection::connectDestroyed, conn));
    conn.reset();
  }
}

void TcpServer::setThreadNum(int numThreads)
{
  assert(0 <= numThreads);
  threadPool_->setThreadNum(numThreads);
}

void TcpServer::start()
{
  if (!started_)
  {
    started_ = true;
    threadPool_->start(threadInitCallback_);
  }

  if (!acceptor_->listenning())
  {
    loop_->runInLoop(
        boost::bind(&Acceptor::listen, get_pointer(acceptor_)));
  }
}

void TcpServer::newConnection(int sockfd, const InetAddress& peerAddr)
{
  loop_->assertInLoopThread();
  EventLoop* ioLoop = threadPool_->getNextLoop();
  char buf[32];
  snprintf(buf, sizeof buf, ":%s#%d", hostport_.c_str(), nextConnId_);
  ++nextConnId_;
  string connName = name_ + buf;

  LOG_INFO << "TcpServer::newConnection [" << name_
           << "] - new connection [" << connName
           << "] from " << peerAddr.toIpPort();
  InetAddress localAddr(sockets::getLocalAddr(sockfd));
  // FIXME poll with zero timeout to double confirm the new connection
  // FIXME use make_shared if necessary
  TcpConnectionPtr conn(new TcpConnection(ioLoop,
                                          connName,
                                          sockfd,
                                          localAddr,
                                          peerAddr));
  connections_[connName] = conn;
  conn->setConnectionCallback(connectionCallback_);
  conn->setMessageCallback(messageCallback_);
  conn->setWriteCompleteCallback(writeCompleteCallback_);
  conn->setCloseCallback(
      boost::bind(&TcpServer::removeConnection, this, _1)); // FIXME: unsafe
  ioLoop->runInLoop(boost::bind(&TcpConnection::connectEstablished, conn));
}

void TcpServer::removeConnection(const TcpConnectionPtr& conn)
{
  // FIXME: unsafe
  loop_->runInLoop(boost::bind(&TcpServer::removeConnectionInLoop, this, conn));
}

void TcpServer::removeConnectionInLoop(const TcpConnectionPtr& conn)
{
  loop_->assertInLoopThread();
  LOG_INFO << "TcpServer::removeConnectionInLoop [" << name_
           << "] - connection " << conn->name();
  size_t n = connections_.erase(conn->name());
  (void)n;
  assert(n == 1);
  EventLoop* ioLoop = conn->getLoop();
  ioLoop->queueInLoop(
      boost::bind(&TcpConnection::connectDestroyed, conn));
}

<|endoftext|>


<commit_before>#include "realrepoclient.h"
//#define _LONG_DEBUG
#include "dbg.h"
#include <unistd.h>

#include <QDataStream>
#include <QByteArray>
#include <QStringList>

RealRepoClient::RealRepoClient( QObject *parent) : QObject(parent)
{
dbg;
	socket = new QTcpSocket(this);
	connect(socket, SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(displayError(QAbstractSocket::SocketError)));

	socket->abort();
	blockSize = 0;
	m_error = -1;
	socket->connectToHost("127.0.0.1", 6666);
        if (!socket->waitForConnected(5*1000)) {
//		emit socket->error(socket->error(), socket->errorString());
		qDebug() << "nya kawaii" << endl;
            return;
        }
	m_error = socket->error();
}

RealRepoClient::~RealRepoClient()
{
dbg;
	socket->disconnectFromHost();
	socket->waitForDisconnected();
}

QString RealRepoClient::sendData( QString data )
{
dbg;
	if( socket->state() != QAbstractSocket::ConnectedState )
		return "";

	//QString data = QString("%1\t%2\t%3\t%4\t").arg(CMD_CREATE_ENTITY).arg(type).arg(id).arg(name);
	qDebug() << "[CLIENT]: sending" << data;
	//int bytes =
	socket->write(data.toUtf8());
//	qDebug() << "written " << bytes << " bytes";
	//bool res =
	socket->waitForReadyRead();
//	qDebug() << "ready - " << res;
	QByteArray req = socket->readAll();
	qDebug() << "[CLIENT]: recvd" << req;
	return QString(req);
}

void RealRepoClient::displayError(QAbstractSocket::SocketError socketError)
{
dbg;
	switch (socketError) {
		case QAbstractSocket::RemoteHostClosedError:
			qDebug() << "QAbstractSocket::RemoteHostClosedError";
			break;
		case QAbstractSocket::ConnectionRefusedError:
			qDebug() << "ConnectionRefusedError";
			break;
		default:
			qDebug() << socket->errorString();
		break;
	}
	m_error = socketError;
}

int RealRepoClient::setName( int type, int id, QString name )
{
dbg;
	QString data = QString("%1\t%2\t%3\t%4\t").arg(CMD_SET_NAME).arg(type).arg(id).arg(name);
	return sendData(data).toInt();
}

void RealRepoClient::setPosition( int type, int id, int /*parent*/, int x, int y)
{
dbg;
	QString data = QString("%1\t%2\t%3\t%4\t%5\t").arg(CMD_SET_POSITION).arg(type).arg(id).arg(x).arg(y);
	QString resp = sendData(data);
//	qDebug() << "recvd" << resp;
}

int RealRepoClient::setPropValue( int type, int id, QString name, QString value)
{
dbg;
	QString data = QString("%1\t%2\t%3\t%4\t%5\t").arg(CMD_SET_PROPERTY).arg(type).arg(id).arg(name).arg(value);
	QString resp = sendData(data);
	return resp.toInt();
}

QString RealRepoClient::getPropValue( int type, int id, QString name )
{
dbg;
	QString data = QString("%1\t%2\t%3\t%4\t%5\t").arg(CMD_GET_PROPERTY).arg(type).arg(id).arg(name);
	QString resp = sendData(data);
	return resp;
}

int RealRepoClient::createEntity(int type, QString name)
{
dbg;
	QString data = QString("%1\t%2\t%3\t").arg(CMD_CREATE_ENTITY).arg(type).arg(name);
//	qDebug() << "requesting for" << type << name;
	QString resp = sendData(data);
	return resp.toInt();
//	qDebug() << "recvd" << resp;
}

int RealRepoClient::createEntity(int type, QString name, int parent)
{
dbg;
	QString data = QString("%1\t%2\t%3\t%4\t").arg(CMD_CREATE_ENTITY).arg(type).arg(name).arg(parent);
	QString resp = sendData(data);
	return resp.toInt();
//	qDebug() << "recvd" << resp;
}

int RealRepoClient::getTypesCount()
{
dbg;
	return sendData(QString::number(CMD_GET_TYPES_COUNT)).toInt();
}

QIntList RealRepoClient::getAllTypes()
{
dbg;
	QString res = sendData(QString::number(CMD_GET_ALL_TYPES));
	QIntList list;
	foreach( QString str, res.split('\t') )
		list += str.toInt();
	return list;
}

TypeInfo RealRepoClient::getTypeInfo( int arg )
{
dbg;
	TypeInfo info;
	QString cmd = QString("%1\t%2").arg(CMD_GET_TYPE_INFO).arg(arg);
	QString resp = sendData(cmd);
	int id = resp.section("\t",0,0).toInt();

	if( id == INVALID_ID ){
		// handle error
		// return info;
	}
//	qDebug() << "recvd info " << resp;
	info.fromString(resp);
	return info;
}

int RealRepoClient::getLastError()
{
dbg;
	return m_error;
}

QString RealRepoClient::getObjectsByType( int type )
{
	QString cmd = QString("%1\t%2").arg(CMD_GET_OBJECTS_BY_TYPE).arg(type);
	QString resp = sendData(cmd);
	return resp;
}

QIntList RealRepoClient::getObjectsListByType( int type )
{
	QString resp = getObjectsByType(type);

	QIntList list;
	foreach( QString str, resp.split('\t') )
		list += str.toInt();
	return list;
}

QString RealRepoClient::getObjectData(int id )
{
	QString cmd = QString("%1\t%2").arg(CMD_GET_OBJECT_DATA).arg(id);
	QString resp = sendData(cmd);
	return resp;
}

QString RealRepoClient::getChildren( int type, int id )
{
	QString cmd = QString("%1\t%2\t%3").arg(CMD_GET_CHILDREN).arg(type).arg(id);
	QString resp = sendData(cmd);
	return resp;
}

QString RealRepoClient::getPosition( int type, int id )
{
	QString cmd = QString("%1\t%2\t%3").arg(CMD_GET_POSITION).arg(type).arg(id);
	QString resp = sendData(cmd);
	return resp;
}

int RealRepoClient::setPosition(int type, int id, int x, int y )
{
	QString cmd = QString("%1\t%2\t%3\t%4\t%5").arg(CMD_SET_POSITION).arg(type).arg(id).arg(x).arg(y);
	QString resp = sendData(cmd);
	return resp.toInt();
}

int RealRepoClient::setConfiguration( int type, int id, QString conf)
{
dbg;
	QString cmd = QString("%1\t%2\t%3\t%4\t").arg(CMD_SET_CONFIGURATION).arg(type).arg(id).arg(conf);
	QString resp = sendData(cmd);
	return resp.toInt();
}

QString RealRepoClient::getConfiguration( int type, int id)
{
dbg;
	QString cmd = QString("%1\t%2\t%3\t").arg(CMD_GET_CONFIGURATION).arg(type).arg(id);
	QString resp = sendData(cmd);
	return resp;
}

QString RealRepoClient::getEntireObject( int type, int id )
{
dbg;
	QString cmd = QString("%1\t%2\t%3\t").arg(CMD_GET_ENTIRE_OBJECT).arg(type).arg(id);
	QString resp = sendData(cmd);
	return resp;
}

RealObject* RealRepoClient::getObjectById( int type, int id )
{
dbg;
	QString data = getEntireObject(type,id);
	RealObject *obj = new RealObject(); // really awful way to do that. need to think it over
	// TODO: add RealObject( const QString& ) constructor to make it creat itself
	obj->setTypeId(data.section("\t",0,0).toInt());
	obj->setId(data.section("\t",1,1).toInt());
	obj->setVisibility(true);
	obj->setName(data.section("\t",3,3));
	obj->setConfiguration(data.section("\t",4,4));

	int childCount = data.section("\t",5,5).toInt();
	int counter = 6;
	for( int i=0; i<childCount; i++){
		obj->addChildElement(data.section("\t",counter,counter).toInt());
		counter++;
	}

	int linksCount = data.section("\t",counter,counter).toInt();
	counter++;
	for( int i=0; i<linksCount; i++){
		obj->addLink(data.section("\t",counter,counter).toInt());
		counter++;
	}

	int propsCount = data.section("\t",counter,counter).toInt();
	counter++;
	for( int i=0; i<propsCount; i++ ){
		QString pair = data.section("\t",counter,counter);
		obj->setProperty(pair.section(";",0,0), pair.section(";",1,1));
		counter++;
	}
	return obj; // implement copy constructor
}

RealLink* RealRepoClient::getLinkById( int type, int id )
{
dbg;
	QString data = getEntireObject(type,id);
	RealLink *link = new RealLink(); // really awful way to do that. need to think it over
	// TODO: add RealLink( const QString& ) constructor to make it creat itself
	link->setTypeId(data.section("\t",0,0).toInt());
	link->setId(data.section("\t",1,1).toInt());
	link->setName(data.section("\t",3,3));

	int fromCount = data.section("\t",4,4).toInt();
	int counter = 5;
	if( fromCount > 0 )
		link->setFromId(data.section("\t",counter,counter).toInt());
	else
		link->setFromId(-1);
	counter += fromCount;

	int toCount = data.section("\t",counter,counter).toInt();
	counter++;
	if( toCount > 0 )
		link->setToId(data.section("\t",counter,counter).toInt());
	else
		link->setToId(-1);
	counter += toCount;

	int propsCount = data.section("\t",counter,counter).toInt();
	counter++;
	for( int i=0; i<propsCount; i++ ){
		QString pair = data.section("\t",counter,counter);
		link->setProperty(pair.section(";",0,0), pair.section(";",1,1));
		counter++;
	}
	return link; // implement copy constructor
}

QString RealRepoClient::getLinksByObject( int type, int id )
{
dbg;
	QString cmd = QString("%1\t%2\t%3\t").arg(CMD_GET_LINKS_BY_OBJECT).arg(type).arg(id);
	QString resp = sendData(cmd);
	return resp;
}

QString RealRepoClient::getObjectsByLink( int type, int id )
{
dbg;
	QString cmd = QString("%1\t%2\t%3\t").arg(CMD_GET_OBJECTS_BY_LINK).arg(type).arg(id);
	QString resp = sendData(cmd);
	return resp;
}

QIntList RealRepoClient::getTypesByMetatype( const MetaType arg )
{
dbg;
	QString cmd = QString("%1\t%2\t").arg(CMD_GET_TYPES_BY_METATYPE).arg(arg);
	QString resp = sendData(cmd);
	QIntList list;
	foreach( QString str, resp.split('\t') )
		list += str.toInt();
	return list;
}

RealType* RealRepoClient::getTypeById( const int id )
{
dbg;
	QString cmd = QString("%1\t%2").arg(CMD_GET_TYPE_INFO).arg(id);
	QString data = sendData(cmd);
	RealType * type = new RealType();
	// FIXME: add RealType( const QString& ) constructor to make it create itself
	type->loadFromString(data);

	return type;	 // that suxx really hard :D
}

<commit_msg>Make error message more meaningful, not just 'nya kawaii'<commit_after>#include "realrepoclient.h"
//#define _LONG_DEBUG
#include "dbg.h"
#include <unistd.h>

#include <QDataStream>
#include <QByteArray>
#include <QStringList>

RealRepoClient::RealRepoClient( QObject *parent) : QObject(parent)
{
dbg;
	socket = new QTcpSocket(this);
	connect(socket, SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(displayError(QAbstractSocket::SocketError)));

	socket->abort();
	blockSize = 0;
	m_error = -1;
	socket->connectToHost("127.0.0.1", 6666);
        if (!socket->waitForConnected(5*1000)) {
//		emit socket->error(socket->error(), socket->errorString());
		qDebug() << "cannot connect to the server" << endl;
            return;
        }
	m_error = socket->error();
}

RealRepoClient::~RealRepoClient()
{
dbg;
	socket->disconnectFromHost();
	socket->waitForDisconnected();
}

QString RealRepoClient::sendData( QString data )
{
dbg;
	if( socket->state() != QAbstractSocket::ConnectedState )
		return "";

	//QString data = QString("%1\t%2\t%3\t%4\t").arg(CMD_CREATE_ENTITY).arg(type).arg(id).arg(name);
	qDebug() << "[CLIENT]: sending" << data;
	//int bytes =
	socket->write(data.toUtf8());
//	qDebug() << "written " << bytes << " bytes";
	//bool res =
	socket->waitForReadyRead();
//	qDebug() << "ready - " << res;
	QByteArray req = socket->readAll();
	qDebug() << "[CLIENT]: recvd" << req;
	return QString(req);
}

void RealRepoClient::displayError(QAbstractSocket::SocketError socketError)
{
dbg;
	switch (socketError) {
		case QAbstractSocket::RemoteHostClosedError:
			qDebug() << "QAbstractSocket::RemoteHostClosedError";
			break;
		case QAbstractSocket::ConnectionRefusedError:
			qDebug() << "ConnectionRefusedError";
			break;
		default:
			qDebug() << socket->errorString();
		break;
	}
	m_error = socketError;
}

int RealRepoClient::setName( int type, int id, QString name )
{
dbg;
	QString data = QString("%1\t%2\t%3\t%4\t").arg(CMD_SET_NAME).arg(type).arg(id).arg(name);
	return sendData(data).toInt();
}

void RealRepoClient::setPosition( int type, int id, int /*parent*/, int x, int y)
{
dbg;
	QString data = QString("%1\t%2\t%3\t%4\t%5\t").arg(CMD_SET_POSITION).arg(type).arg(id).arg(x).arg(y);
	QString resp = sendData(data);
//	qDebug() << "recvd" << resp;
}

int RealRepoClient::setPropValue( int type, int id, QString name, QString value)
{
dbg;
	QString data = QString("%1\t%2\t%3\t%4\t%5\t").arg(CMD_SET_PROPERTY).arg(type).arg(id).arg(name).arg(value);
	QString resp = sendData(data);
	return resp.toInt();
}

QString RealRepoClient::getPropValue( int type, int id, QString name )
{
dbg;
	QString data = QString("%1\t%2\t%3\t%4\t%5\t").arg(CMD_GET_PROPERTY).arg(type).arg(id).arg(name);
	QString resp = sendData(data);
	return resp;
}

int RealRepoClient::createEntity(int type, QString name)
{
dbg;
	QString data = QString("%1\t%2\t%3\t").arg(CMD_CREATE_ENTITY).arg(type).arg(name);
//	qDebug() << "requesting for" << type << name;
	QString resp = sendData(data);
	return resp.toInt();
//	qDebug() << "recvd" << resp;
}

int RealRepoClient::createEntity(int type, QString name, int parent)
{
dbg;
	QString data = QString("%1\t%2\t%3\t%4\t").arg(CMD_CREATE_ENTITY).arg(type).arg(name).arg(parent);
	QString resp = sendData(data);
	return resp.toInt();
//	qDebug() << "recvd" << resp;
}

int RealRepoClient::getTypesCount()
{
dbg;
	return sendData(QString::number(CMD_GET_TYPES_COUNT)).toInt();
}

QIntList RealRepoClient::getAllTypes()
{
dbg;
	QString res = sendData(QString::number(CMD_GET_ALL_TYPES));
	QIntList list;
	foreach( QString str, res.split('\t') )
		list += str.toInt();
	return list;
}

TypeInfo RealRepoClient::getTypeInfo( int arg )
{
dbg;
	TypeInfo info;
	QString cmd = QString("%1\t%2").arg(CMD_GET_TYPE_INFO).arg(arg);
	QString resp = sendData(cmd);
	int id = resp.section("\t",0,0).toInt();

	if( id == INVALID_ID ){
		// handle error
		// return info;
	}
//	qDebug() << "recvd info " << resp;
	info.fromString(resp);
	return info;
}

int RealRepoClient::getLastError()
{
dbg;
	return m_error;
}

QString RealRepoClient::getObjectsByType( int type )
{
	QString cmd = QString("%1\t%2").arg(CMD_GET_OBJECTS_BY_TYPE).arg(type);
	QString resp = sendData(cmd);
	return resp;
}

QIntList RealRepoClient::getObjectsListByType( int type )
{
	QString resp = getObjectsByType(type);

	QIntList list;
	foreach( QString str, resp.split('\t') )
		list += str.toInt();
	return list;
}

QString RealRepoClient::getObjectData(int id )
{
	QString cmd = QString("%1\t%2").arg(CMD_GET_OBJECT_DATA).arg(id);
	QString resp = sendData(cmd);
	return resp;
}

QString RealRepoClient::getChildren( int type, int id )
{
	QString cmd = QString("%1\t%2\t%3").arg(CMD_GET_CHILDREN).arg(type).arg(id);
	QString resp = sendData(cmd);
	return resp;
}

QString RealRepoClient::getPosition( int type, int id )
{
	QString cmd = QString("%1\t%2\t%3").arg(CMD_GET_POSITION).arg(type).arg(id);
	QString resp = sendData(cmd);
	return resp;
}

int RealRepoClient::setPosition(int type, int id, int x, int y )
{
	QString cmd = QString("%1\t%2\t%3\t%4\t%5").arg(CMD_SET_POSITION).arg(type).arg(id).arg(x).arg(y);
	QString resp = sendData(cmd);
	return resp.toInt();
}

int RealRepoClient::setConfiguration( int type, int id, QString conf)
{
dbg;
	QString cmd = QString("%1\t%2\t%3\t%4\t").arg(CMD_SET_CONFIGURATION).arg(type).arg(id).arg(conf);
	QString resp = sendData(cmd);
	return resp.toInt();
}

QString RealRepoClient::getConfiguration( int type, int id)
{
dbg;
	QString cmd = QString("%1\t%2\t%3\t").arg(CMD_GET_CONFIGURATION).arg(type).arg(id);
	QString resp = sendData(cmd);
	return resp;
}

QString RealRepoClient::getEntireObject( int type, int id )
{
dbg;
	QString cmd = QString("%1\t%2\t%3\t").arg(CMD_GET_ENTIRE_OBJECT).arg(type).arg(id);
	QString resp = sendData(cmd);
	return resp;
}

RealObject* RealRepoClient::getObjectById( int type, int id )
{
dbg;
	QString data = getEntireObject(type,id);
	RealObject *obj = new RealObject(); // really awful way to do that. need to think it over
	// TODO: add RealObject( const QString& ) constructor to make it creat itself
	obj->setTypeId(data.section("\t",0,0).toInt());
	obj->setId(data.section("\t",1,1).toInt());
	obj->setVisibility(true);
	obj->setName(data.section("\t",3,3));
	obj->setConfiguration(data.section("\t",4,4));

	int childCount = data.section("\t",5,5).toInt();
	int counter = 6;
	for( int i=0; i<childCount; i++){
		obj->addChildElement(data.section("\t",counter,counter).toInt());
		counter++;
	}

	int linksCount = data.section("\t",counter,counter).toInt();
	counter++;
	for( int i=0; i<linksCount; i++){
		obj->addLink(data.section("\t",counter,counter).toInt());
		counter++;
	}

	int propsCount = data.section("\t",counter,counter).toInt();
	counter++;
	for( int i=0; i<propsCount; i++ ){
		QString pair = data.section("\t",counter,counter);
		obj->setProperty(pair.section(";",0,0), pair.section(";",1,1));
		counter++;
	}
	return obj; // implement copy constructor
}

RealLink* RealRepoClient::getLinkById( int type, int id )
{
dbg;
	QString data = getEntireObject(type,id);
	RealLink *link = new RealLink(); // really awful way to do that. need to think it over
	// TODO: add RealLink( const QString& ) constructor to make it creat itself
	link->setTypeId(data.section("\t",0,0).toInt());
	link->setId(data.section("\t",1,1).toInt());
	link->setName(data.section("\t",3,3));

	int fromCount = data.section("\t",4,4).toInt();
	int counter = 5;
	if( fromCount > 0 )
		link->setFromId(data.section("\t",counter,counter).toInt());
	else
		link->setFromId(-1);
	counter += fromCount;

	int toCount = data.section("\t",counter,counter).toInt();
	counter++;
	if( toCount > 0 )
		link->setToId(data.section("\t",counter,counter).toInt());
	else
		link->setToId(-1);
	counter += toCount;

	int propsCount = data.section("\t",counter,counter).toInt();
	counter++;
	for( int i=0; i<propsCount; i++ ){
		QString pair = data.section("\t",counter,counter);
		link->setProperty(pair.section(";",0,0), pair.section(";",1,1));
		counter++;
	}
	return link; // implement copy constructor
}

QString RealRepoClient::getLinksByObject( int type, int id )
{
dbg;
	QString cmd = QString("%1\t%2\t%3\t").arg(CMD_GET_LINKS_BY_OBJECT).arg(type).arg(id);
	QString resp = sendData(cmd);
	return resp;
}

QString RealRepoClient::getObjectsByLink( int type, int id )
{
dbg;
	QString cmd = QString("%1\t%2\t%3\t").arg(CMD_GET_OBJECTS_BY_LINK).arg(type).arg(id);
	QString resp = sendData(cmd);
	return resp;
}

QIntList RealRepoClient::getTypesByMetatype( const MetaType arg )
{
dbg;
	QString cmd = QString("%1\t%2\t").arg(CMD_GET_TYPES_BY_METATYPE).arg(arg);
	QString resp = sendData(cmd);
	QIntList list;
	foreach( QString str, resp.split('\t') )
		list += str.toInt();
	return list;
}

RealType* RealRepoClient::getTypeById( const int id )
{
dbg;
	QString cmd = QString("%1\t%2").arg(CMD_GET_TYPE_INFO).arg(id);
	QString data = sendData(cmd);
	RealType * type = new RealType();
	// FIXME: add RealType( const QString& ) constructor to make it create itself
	type->loadFromString(data);

	return type;	 // that suxx really hard :D
}

<|endoftext|>


<commit_before>//
// Created by Vadim N. on 16/03/2016.
//

// #include "benchutils.h"
#include <Inference>

using namespace ymir;
using namespace std;

int main(int argc, char* argv[]) {

    // if (argc < 2) {
    //   std::cout << "Please re-run the script with the data folder path supplied." << std::endl;
    //   return 1;
    // }

    // std::chrono::system_clock::time_point tp1, tp2;

    // std::vector< std::pair<std::string, size_t> > timepoints;

    // std::vector<prob_t> logLvec;

    // std::string temp_str;

    // time_t vj_single_parse, vdj_single_parse,
    //         vj_single_prob, vj_single_meta,
    //         vj_single_infer, vdj_single_prob,
    //         vdj_single_meta, vdj_single_infer;

    // time_t vj_good_parse, vdj_good_parse,
    //         vj_good_prob, vj_good_meta,
    //         vj_good_infer, vdj_good_prob,
    //         vdj_good_meta, vdj_good_infer;

    std::string BENCH_DATA_FOLDER = argv[1];

    std::cout << "Data folder:\t[" << BENCH_DATA_FOLDER << "]" << endl;

    //
    // TCR alpha chain repertoire - VJ recombination
    //
    VDJRecombinationGenes vj_single_genes("Vgene",
                                          BENCH_DATA_FOLDER + "trav.txt",
                                          "Jgene",
                                          BENCH_DATA_FOLDER + "traj.txt");

    VDJRecombinationGenes vj_single_genes2(vj_single_genes);
    VDJRecombinationGenes vj_single_genes3 = vj_single_genes;
    vj_single_genes2 = vj_single_genes;

//     string input_alpha_file = "alpha.250k.txt";
//     string input_beta_file = "beta.250k.txt";

//     CDR3NucParser parser;
//     Cloneset cloneset_vj;

//     YMIR_BENCHMARK("Parsing VJ",
//                    parser.openAndParse(BENCH_DATA_FOLDER + input_alpha_file,
//                                        &cloneset_vj,
//                                        vj_single_genes,
//                                        NUCLEOTIDE,
//                                        VJ_RECOMB,
//                                        AlignmentColumnOptions(AlignmentColumnOptions::OVERWRITE, AlignmentColumnOptions::OVERWRITE),
//                                        VDJAlignerParameters(2)))

//     //
//     // TCR beta chain repertoire - VDJ recombination
//     //
// //    VDJRecombinationGenes vdj_single_genes("Vgene",
// //                                    BENCH_DATA_FOLDER + "trbv.txt",
// //                                    "Jgene",
// //                                    BENCH_DATA_FOLDER + "trbj.txt",
// //                                    "Dgene",
// //                                    BENCH_DATA_FOLDER + "trbd.txt");
// //
// //    Cloneset cloneset_vdj;
// //    YMIR_BENCHMARK("Parsing VDJ",
// //                   parser.openAndParse(BENCH_DATA_FOLDER + input_beta_file,
// //                                       &cloneset_vdj,
// //                                       vdj_single_genes,
// //                                       NUCLEOTIDE,
// //                                       VDJ_RECOMB,
// //                                       AlignmentColumnOptions()
// //                                               .setV(AlignmentColumnOptions::USE_PROVIDED)
// //                                               .setD(AlignmentColumnOptions::OVERWRITE)
// //                                               .setJ(AlignmentColumnOptions::USE_PROVIDED),
// //                                       VDJAlignerParameters(3)))

//     //
//     // VJ MAAG
//     //
//     ProbabilisticAssemblingModel vj_single_model(BENCH_DATA_FOLDER + "../../models/hTRA", EMPTY);

//     //
//     // VDJ MAAG
//     //
// //    ProbabilisticAssemblingModel vdj_single_model(BENCH_DATA_FOLDER + "../../models/hTRB", EMPTY);

//     //
//     // Inference
//     //
//     vector<int> vec_sample = {10000, 25000, 50000, 100000, 150000};
//     vec_sample = { 100000 };
//     vector<int> vec_block = {500, 1000, 2000, 5000, 10000}; //, 2000, 5000, 10000};
// //    vec_block = {2000, 5000, 10000};
//     vec_block = { std::stoi(argv[2]) };
//     vector<double> vec_alpha = {.5, .6, .7, .8, .9};
//     vec_alpha = { std::stof(argv[3]) };
//     vector<double> vec_beta =  {.1, .5, 1, 3};
//     vec_beta = { std::stof(argv[4]) };
//     vector<double> vec_K =     {1, 2, 3};
//     vec_K = { std::stod(argv[5]) };
//     ErrorMode error_mode = COMPUTE_ERRORS;

// //    int niter, sample, block;
// //    double alpha;
// //    niter = 10;
// //    int sample = 10000;

// //    RUN_EM_INFERENCE(string("vj"), cloneset_vj, vj_single_model, niter, sample, error_mode)
// //    RUN_EM_INFERENCE(string("vdj"), cloneset_vdj, vdj_single_model, niter, sample, error_mode)
// //    for(auto val_sample: vec_sample) {
// //        RUN_EM_INFERENCE(string("vj"), cloneset_vj, vj_single_model, 40, val_sample, error_mode)
// //    }

// //    ModelParameterVector new_param_vec = vj_single_model.event_probabilities();
// //    new_param_vec.fill(1);
// //    new_param_vec.normaliseEventFamilies();
// //    vj_single_model.updateModelParameterVector(new_param_vec);
// //
// //    auto rep_nonc = cloneset_vj.noncoding().sample(2500);
// //    auto maag_rep = vj_single_model.buildGraphs(rep_nonc, SAVE_METADATA, error_mode, NUCLEOTIDE, true);
// //    vector<prob_t> prob_vec(maag_rep.size(), 0);
// //
// //    vector<bool> good_clonotypes(maag_rep.size(), true);
// //    for (size_t i = 0; i < maag_rep.size(); ++i) {
// //        if (rep_nonc[i].is_good()) {
// //            prob_vec[i] = maag_rep[i].fullProbability();
// //            if (std::isnan(prob_vec[i]) || prob_vec[i] == 0) {
// //                good_clonotypes[i] = false;
// //            }
// //        } else {
// //            good_clonotypes[i] = false;
// //        }
// //    }

//     for(auto val_sample: vec_sample) {
//         for(auto val_block: vec_block) {
//             for (auto val_alpha: vec_alpha) {
//                 for (auto val_beta: vec_beta) {
//                     for (auto val_K: vec_K) {
//                         RUN_SG_INFERENCE(string("vj"), cloneset_vj, vj_single_model, 40, val_block, val_alpha, val_beta, val_K, val_sample, error_mode)
//                     }
//                 }
//             }
//         }
//     }

}
<commit_msg>debug<commit_after>//
// Created by Vadim N. on 16/03/2016.
//

// #include "benchutils.h"
#include <Inference>

using namespace ymir;
using namespace std;

int main(int argc, char* argv[]) {

    // if (argc < 2) {
    //   std::cout << "Please re-run the script with the data folder path supplied." << std::endl;
    //   return 1;
    // }

    // std::chrono::system_clock::time_point tp1, tp2;

    // std::vector< std::pair<std::string, size_t> > timepoints;

    // std::vector<prob_t> logLvec;

    // std::string temp_str;

    // time_t vj_single_parse, vdj_single_parse,
    //         vj_single_prob, vj_single_meta,
    //         vj_single_infer, vdj_single_prob,
    //         vdj_single_meta, vdj_single_infer;

    // time_t vj_good_parse, vdj_good_parse,
    //         vj_good_prob, vj_good_meta,
    //         vj_good_infer, vdj_good_prob,
    //         vdj_good_meta, vdj_good_infer;

    // std::string BENCH_DATA_FOLDER = argv[1];

    // std::cout << "Data folder:\t[" << BENCH_DATA_FOLDER << "]" << endl;

    //
    // TCR alpha chain repertoire - VJ recombination
    //
    VDJRecombinationGenes vj_single_genes("Vgene",
                                          "/home/vadim/ymir/benchmark/data/trav.txt",
                                          "Jgene",
                                          "/home/vadim/ymir/benchmark/data/traj.txt");

    VDJRecombinationGenes vj_single_genes2(vj_single_genes);
    VDJRecombinationGenes vj_single_genes3 = vj_single_genes;
    vj_single_genes2 = vj_single_genes;

//     string input_alpha_file = "alpha.250k.txt";
//     string input_beta_file = "beta.250k.txt";

//     CDR3NucParser parser;
//     Cloneset cloneset_vj;

//     YMIR_BENCHMARK("Parsing VJ",
//                    parser.openAndParse(BENCH_DATA_FOLDER + input_alpha_file,
//                                        &cloneset_vj,
//                                        vj_single_genes,
//                                        NUCLEOTIDE,
//                                        VJ_RECOMB,
//                                        AlignmentColumnOptions(AlignmentColumnOptions::OVERWRITE, AlignmentColumnOptions::OVERWRITE),
//                                        VDJAlignerParameters(2)))

//     //
//     // TCR beta chain repertoire - VDJ recombination
//     //
// //    VDJRecombinationGenes vdj_single_genes("Vgene",
// //                                    BENCH_DATA_FOLDER + "trbv.txt",
// //                                    "Jgene",
// //                                    BENCH_DATA_FOLDER + "trbj.txt",
// //                                    "Dgene",
// //                                    BENCH_DATA_FOLDER + "trbd.txt");
// //
// //    Cloneset cloneset_vdj;
// //    YMIR_BENCHMARK("Parsing VDJ",
// //                   parser.openAndParse(BENCH_DATA_FOLDER + input_beta_file,
// //                                       &cloneset_vdj,
// //                                       vdj_single_genes,
// //                                       NUCLEOTIDE,
// //                                       VDJ_RECOMB,
// //                                       AlignmentColumnOptions()
// //                                               .setV(AlignmentColumnOptions::USE_PROVIDED)
// //                                               .setD(AlignmentColumnOptions::OVERWRITE)
// //                                               .setJ(AlignmentColumnOptions::USE_PROVIDED),
// //                                       VDJAlignerParameters(3)))

//     //
//     // VJ MAAG
//     //
//     ProbabilisticAssemblingModel vj_single_model(BENCH_DATA_FOLDER + "../../models/hTRA", EMPTY);

//     //
//     // VDJ MAAG
//     //
// //    ProbabilisticAssemblingModel vdj_single_model(BENCH_DATA_FOLDER + "../../models/hTRB", EMPTY);

//     //
//     // Inference
//     //
//     vector<int> vec_sample = {10000, 25000, 50000, 100000, 150000};
//     vec_sample = { 100000 };
//     vector<int> vec_block = {500, 1000, 2000, 5000, 10000}; //, 2000, 5000, 10000};
// //    vec_block = {2000, 5000, 10000};
//     vec_block = { std::stoi(argv[2]) };
//     vector<double> vec_alpha = {.5, .6, .7, .8, .9};
//     vec_alpha = { std::stof(argv[3]) };
//     vector<double> vec_beta =  {.1, .5, 1, 3};
//     vec_beta = { std::stof(argv[4]) };
//     vector<double> vec_K =     {1, 2, 3};
//     vec_K = { std::stod(argv[5]) };
//     ErrorMode error_mode = COMPUTE_ERRORS;

// //    int niter, sample, block;
// //    double alpha;
// //    niter = 10;
// //    int sample = 10000;

// //    RUN_EM_INFERENCE(string("vj"), cloneset_vj, vj_single_model, niter, sample, error_mode)
// //    RUN_EM_INFERENCE(string("vdj"), cloneset_vdj, vdj_single_model, niter, sample, error_mode)
// //    for(auto val_sample: vec_sample) {
// //        RUN_EM_INFERENCE(string("vj"), cloneset_vj, vj_single_model, 40, val_sample, error_mode)
// //    }

// //    ModelParameterVector new_param_vec = vj_single_model.event_probabilities();
// //    new_param_vec.fill(1);
// //    new_param_vec.normaliseEventFamilies();
// //    vj_single_model.updateModelParameterVector(new_param_vec);
// //
// //    auto rep_nonc = cloneset_vj.noncoding().sample(2500);
// //    auto maag_rep = vj_single_model.buildGraphs(rep_nonc, SAVE_METADATA, error_mode, NUCLEOTIDE, true);
// //    vector<prob_t> prob_vec(maag_rep.size(), 0);
// //
// //    vector<bool> good_clonotypes(maag_rep.size(), true);
// //    for (size_t i = 0; i < maag_rep.size(); ++i) {
// //        if (rep_nonc[i].is_good()) {
// //            prob_vec[i] = maag_rep[i].fullProbability();
// //            if (std::isnan(prob_vec[i]) || prob_vec[i] == 0) {
// //                good_clonotypes[i] = false;
// //            }
// //        } else {
// //            good_clonotypes[i] = false;
// //        }
// //    }

//     for(auto val_sample: vec_sample) {
//         for(auto val_block: vec_block) {
//             for (auto val_alpha: vec_alpha) {
//                 for (auto val_beta: vec_beta) {
//                     for (auto val_K: vec_K) {
//                         RUN_SG_INFERENCE(string("vj"), cloneset_vj, vj_single_model, 40, val_block, val_alpha, val_beta, val_K, val_sample, error_mode)
//                     }
//                 }
//             }
//         }
//     }

}
<|endoftext|>


<commit_before><commit_msg>Update CloseIdleSockets to close out FLIP connections as well as HTTP connections.  This is used for benchmarking.<commit_after><|endoftext|>


<commit_before>/*
 * Copyright (c) 2014 Juniper Networks, Inc. All rights reserved.
 */

#include "loadbalancer_haproxy.h"

#include <cerrno>
#include <fstream>
#include <boost/assign/list_of.hpp>
#include "base/logging.h"
#include "agent.h"
#include "init/agent_param.h"

#include "loadbalancer_properties.h"

using namespace std;
using boost::assign::map_list_of;

LoadbalancerHaproxy::LoadbalancerHaproxy(Agent *agent)
        : protocol_default_("tcp"),
          balance_default_("roundrobin"), agent_(agent) {
    protocol_map_ = map_list_of
            ("TCP", "tcp")
            ("HTTP", "http")
            ("HTTPS", "tcp");
    balance_map_ = map_list_of
            ("ROUND_ROBIN", "roundrobin")
            ("LEAST_CONNECTIONS", "leastconn")
            ("SOURCE_IP", "source");
}

const string &LoadbalancerHaproxy::ProtocolMap(const string &proto) const {
    map<string, string>::const_iterator loc = protocol_map_.find(proto);
    if (loc == protocol_map_.end()) {
        return protocol_default_;
    }
    return loc->second;
}

const string &LoadbalancerHaproxy::BalanceMap(const string &proto) const {
    map<string, string>::const_iterator loc = balance_map_.find(proto);
    if (loc == balance_map_.end()) {
        return balance_default_;
    }
    return loc->second;
}

/*
 * global
 *     daemon
 *     user nobody
 *     group nogroup
 *     log /dev/log local0
 *     log /dev/log local1 notice
 *     stats socket <path> mode 0666 level user
 */
void LoadbalancerHaproxy::GenerateGlobal(
    ostream *out, const LoadbalancerProperties &props) const {

    *out << "global" << endl;
    *out << string(4, ' ') << "daemon" << endl;
    *out << string(4, ' ') << "user nobody" << endl;
    *out << string(4, ' ') << "group nogroup" << endl;
    *out << endl;
}

void LoadbalancerHaproxy::GenerateDefaults(
    ostream *out, const LoadbalancerProperties &props) const {

    *out << "defaults" << endl;
    *out << string(4, ' ') << "log global" << endl;
    *out << string(4, ' ') << "retries 3" << endl;
    *out << string(4, ' ') << "option redispatch" << endl;
    *out << string(4, ' ') << "timeout connect 5000" << endl;
    *out << string(4, ' ') << "timeout client 50000" << endl;
    *out << string(4, ' ') << "timeout server 50000" << endl;
    *out << endl;
}

void LoadbalancerHaproxy::GenerateListen(
    ostream *out, const LoadbalancerProperties &props) const {

    *out << "listen contrail-config-stats :5937" << endl;
    *out << string(4, ' ') << "mode http" << endl;
    *out << string(4, ' ') << "stats enable" << endl;
    *out << string(4, ' ') << "stats uri /" << endl;
    *out << string(4, ' ') << "stats auth haproxy:contrail123" << endl;
    *out << endl;
}

/*
 * frontend vip_id
 *     bind address:port
 *     mode [http|tcp]
 *     default_backend pool_id
 */
void LoadbalancerHaproxy::GenerateFrontend(
    ostream *out, const boost::uuids::uuid &pool_id,
    const LoadbalancerProperties &props) const {

    *out << "frontend " << props.vip_uuid() << endl;
    const autogen::VirtualIpType &vip = props.vip_properties();
    *out << string(4, ' ')
         << "bind " << vip.address << ":" << vip.protocol_port;
    if (vip.protocol_port ==  LB_HAPROXY_SSL_PORT) {
        *out << " ssl crt " <<
            agent_->params()->si_haproxy_ssl_cert_path();
    }
    *out << endl;

    *out << string(4, ' ')
         << "mode " << ProtocolMap(vip.protocol) << endl;
    *out << string(4, ' ')
         << "default_backend " << pool_id << endl;

    if (vip.connection_limit >= 0) {
        *out << string(4, ' ')
             << "maxconn " << vip.connection_limit << endl;
    }
    *out << endl;
}

/*
 * backend <pool_id>
 *     mode <protocol>
 *     balance <lb_method>
 *     server <id> <address>:<port> weight <weight>
 */
void LoadbalancerHaproxy::GenerateBackend(
    ostream *out, const boost::uuids::uuid &pool_id,
    const LoadbalancerProperties &props) const {
    const autogen::LoadbalancerPoolType &pool = props.pool_properties();
    *out << "backend " << pool_id << endl;
    *out << string(4, ' ')
         << "mode " << ProtocolMap(pool.protocol) << endl;
    *out << string(4, ' ')
         << "balance " << BalanceMap(pool.loadbalancer_method) << endl;

    int timeout = 0, max_retries = 0;
    if (props.healthmonitors().size()) {
        const autogen::LoadbalancerHealthmonitorType &hm =
            props.healthmonitors().begin()->second;
        timeout = hm.timeout * 1000; //In milliseconds
        max_retries = hm.max_retries;
        if (!hm.url_path.empty()) {
            *out << string(4, ' ')
                 << "option httpchk ";
            if (!hm.http_method.empty()) {
                *out << hm.http_method;
            }
            *out << " " << hm.url_path << endl;
        }
        if (!hm.expected_codes.empty()) {
            *out << string(4, ' ')
                 << "http-check expect status "
                 << hm.expected_codes << endl;
        }
    }

    for (LoadbalancerProperties::MemberMap::const_iterator iter =
                 props.members().begin();
         iter != props.members().end(); ++iter) {
        const autogen::LoadbalancerMemberType &member = iter->second;
        *out << string(4, ' ')
             << "server " << iter->first << " " << member.address
             << ":" << member.protocol_port
             << " weight " << member.weight;
        if (timeout) {
            *out << " check inter " << timeout << " rise 1 fall "
                 << max_retries;
        }
        *out << endl;
    }
}

void LoadbalancerHaproxy::GenerateConfig(
    const string &filename, const boost::uuids::uuid &pool_id,
    const LoadbalancerProperties &props) const {
    ofstream fs(filename.c_str());
    if (fs.fail()) {
        LOG(ERROR, "File create " << filename << ": " << strerror(errno));
    }

    GenerateGlobal(&fs, props);
    GenerateDefaults(&fs, props);
    GenerateListen(&fs, props);
    GenerateFrontend(&fs, pool_id, props);
    GenerateBackend(&fs, pool_id, props);
    fs.close();
}
<commit_msg>Bug:#1380771 Adding the load balancer session persistence parameters fro Service Instance's Virtual ip. The session persistense type and name are written to haproxy configuration file in the backend section<commit_after>/*
 * Copyright (c) 2014 Juniper Networks, Inc. All rights reserved.
 */

#include "loadbalancer_haproxy.h"

#include <cerrno>
#include <fstream>
#include <boost/assign/list_of.hpp>
#include "base/logging.h"
#include "agent.h"
#include "init/agent_param.h"

#include "loadbalancer_properties.h"

using namespace std;
using boost::assign::map_list_of;

LoadbalancerHaproxy::LoadbalancerHaproxy(Agent *agent)
        : protocol_default_("tcp"),
          balance_default_("roundrobin"), agent_(agent) {
    protocol_map_ = map_list_of
            ("TCP", "tcp")
            ("HTTP", "http")
            ("HTTPS", "tcp");
    balance_map_ = map_list_of
            ("ROUND_ROBIN", "roundrobin")
            ("LEAST_CONNECTIONS", "leastconn")
            ("SOURCE_IP", "source");
}

const string &LoadbalancerHaproxy::ProtocolMap(const string &proto) const {
    map<string, string>::const_iterator loc = protocol_map_.find(proto);
    if (loc == protocol_map_.end()) {
        return protocol_default_;
    }
    return loc->second;
}

const string &LoadbalancerHaproxy::BalanceMap(const string &proto) const {
    map<string, string>::const_iterator loc = balance_map_.find(proto);
    if (loc == balance_map_.end()) {
        return balance_default_;
    }
    return loc->second;
}

/*
 * global
 *     daemon
 *     user nobody
 *     group nogroup
 *     log /dev/log local0
 *     log /dev/log local1 notice
 *     stats socket <path> mode 0666 level user
 */
void LoadbalancerHaproxy::GenerateGlobal(
    ostream *out, const LoadbalancerProperties &props) const {

    *out << "global" << endl;
    *out << string(4, ' ') << "daemon" << endl;
    *out << string(4, ' ') << "user nobody" << endl;
    *out << string(4, ' ') << "group nogroup" << endl;
    *out << endl;
}

void LoadbalancerHaproxy::GenerateDefaults(
    ostream *out, const LoadbalancerProperties &props) const {

    *out << "defaults" << endl;
    *out << string(4, ' ') << "log global" << endl;
    *out << string(4, ' ') << "retries 3" << endl;
    *out << string(4, ' ') << "option redispatch" << endl;
    *out << string(4, ' ') << "timeout connect 5000" << endl;
    *out << string(4, ' ') << "timeout client 50000" << endl;
    *out << string(4, ' ') << "timeout server 50000" << endl;
    *out << endl;
}

void LoadbalancerHaproxy::GenerateListen(
    ostream *out, const LoadbalancerProperties &props) const {

    *out << "listen contrail-config-stats :5937" << endl;
    *out << string(4, ' ') << "mode http" << endl;
    *out << string(4, ' ') << "stats enable" << endl;
    *out << string(4, ' ') << "stats uri /" << endl;
    *out << string(4, ' ') << "stats auth haproxy:contrail123" << endl;
    *out << endl;
}

/*
 * frontend vip_id
 *     bind address:port
 *     mode [http|tcp]
 *     default_backend pool_id
 */
void LoadbalancerHaproxy::GenerateFrontend(
    ostream *out, const boost::uuids::uuid &pool_id,
    const LoadbalancerProperties &props) const {

    *out << "frontend " << props.vip_uuid() << endl;
    const autogen::VirtualIpType &vip = props.vip_properties();
    *out << string(4, ' ')
         << "bind " << vip.address << ":" << vip.protocol_port;
    if (vip.protocol_port ==  LB_HAPROXY_SSL_PORT) {
        *out << " ssl crt " <<
            agent_->params()->si_haproxy_ssl_cert_path();
    }
    *out << endl;

    *out << string(4, ' ')
         << "mode " << ProtocolMap(vip.protocol) << endl;
    *out << string(4, ' ')
         << "default_backend " << pool_id << endl;

    if (vip.connection_limit >= 0) {
        *out << string(4, ' ')
             << "maxconn " << vip.connection_limit << endl;
    }
    *out << endl;
}

/*
 * backend <pool_id>
 *     mode <protocol>
 *     balance <lb_method>
 *     server <id> <address>:<port> weight <weight>
 */
void LoadbalancerHaproxy::GenerateBackend(
    ostream *out, const boost::uuids::uuid &pool_id,
    const LoadbalancerProperties &props) const {
    const autogen::LoadbalancerPoolType &pool = props.pool_properties();
    *out << "backend " << pool_id << endl;
    *out << string(4, ' ')
         << "mode " << ProtocolMap(pool.protocol) << endl;
    *out << string(4, ' ')
         << "balance " << BalanceMap(pool.loadbalancer_method) << endl;

    int timeout = 0, max_retries = 0;
    if (props.healthmonitors().size()) {
        const autogen::LoadbalancerHealthmonitorType &hm =
            props.healthmonitors().begin()->second;
        timeout = hm.timeout * 1000; //In milliseconds
        max_retries = hm.max_retries;
        if (!hm.url_path.empty()) {
            *out << string(4, ' ')
                 << "option httpchk ";
            if (!hm.http_method.empty()) {
                *out << hm.http_method;
            }
            *out << " " << hm.url_path << endl;
        }
        if (!hm.expected_codes.empty()) {
            *out << string(4, ' ')
                 << "http-check expect status "
                 << hm.expected_codes << endl;
        }
    }
    const autogen::VirtualIpType &vip = props.vip_properties();
    if (vip.persistence_type == "HTTP_COOKIE") {
        *out << string(4, ' ') << "cookie SRV insert indirect nocache"
             << endl;
    }
    if (vip.persistence_type == "SOURCE_IP") {
        *out << string(4, ' ') << "stick-table type ip size 10k"
             << endl;
        *out << string(4, ' ') << "stick on src" << endl;
    }
    if (vip.persistence_type == "APP_COOKIE" &&
            !vip.persistence_cookie_name.empty()) {
        *out << string(4, ' ') << "appsession " <<
            vip.persistence_cookie_name << " len 56 timeout 3h" << endl;
    }

    for (LoadbalancerProperties::MemberMap::const_iterator iter =
                 props.members().begin();
         iter != props.members().end(); ++iter) {
        const autogen::LoadbalancerMemberType &member = iter->second;
        *out << string(4, ' ')
             << "server " << iter->first << " " << member.address
             << ":" << member.protocol_port
             << " weight " << member.weight;
        if (timeout) {
            *out << " check inter " << timeout << " rise 1 fall "
                 << max_retries;
        }
        *out << endl;
    }
}

void LoadbalancerHaproxy::GenerateConfig(
    const string &filename, const boost::uuids::uuid &pool_id,
    const LoadbalancerProperties &props) const {
    ofstream fs(filename.c_str());
    if (fs.fail()) {
        LOG(ERROR, "File create " << filename << ": " << strerror(errno));
    }

    GenerateGlobal(&fs, props);
    GenerateDefaults(&fs, props);
    GenerateListen(&fs, props);
    GenerateFrontend(&fs, pool_id, props);
    GenerateBackend(&fs, pool_id, props);
    fs.close();
}
<|endoftext|>


<commit_before>/**
 ******************************************************************************
 * Xenia : Xbox 360 Emulator Research Project                                 *
 ******************************************************************************
 * Copyright 2013 Ben Vanik. All rights reserved.                             *
 * Released under the BSD license - see LICENSE in the root for more details. *
 ******************************************************************************
 */

#include "xenia/hid/xinput/xinput_input_driver.h"

#include "xenia/hid/hid-private.h"

#include <Xinput.h>

namespace xe {
namespace hid {
namespace xinput {

XInputInputDriver::XInputInputDriver(InputSystem* input_system)
    : InputDriver(input_system) {
  XInputEnable(TRUE);
}

XInputInputDriver::~XInputInputDriver() { XInputEnable(FALSE); }

X_STATUS XInputInputDriver::Setup() { return X_STATUS_SUCCESS; }

X_RESULT XInputInputDriver::GetCapabilities(uint32_t user_index, uint32_t flags,
                                            X_INPUT_CAPABILITIES* out_caps) {
  XINPUT_CAPABILITIES native_caps;
  DWORD result = XInputGetCapabilities(user_index, flags, &native_caps);
  if (result) {
    return result;
  }

  out_caps->type = native_caps.Type;
  out_caps->sub_type = native_caps.SubType;
  out_caps->flags = native_caps.Flags;
  out_caps->gamepad.buttons = native_caps.Gamepad.wButtons;
  out_caps->gamepad.left_trigger = native_caps.Gamepad.bLeftTrigger;
  out_caps->gamepad.right_trigger = native_caps.Gamepad.bRightTrigger;
  out_caps->gamepad.thumb_lx = native_caps.Gamepad.sThumbLX;
  out_caps->gamepad.thumb_ly = native_caps.Gamepad.sThumbLY;
  out_caps->gamepad.thumb_rx = native_caps.Gamepad.sThumbRX;
  out_caps->gamepad.thumb_ry = native_caps.Gamepad.sThumbRY;
  out_caps->vibration.left_motor_speed = native_caps.Vibration.wLeftMotorSpeed;
  out_caps->vibration.right_motor_speed =
      native_caps.Vibration.wRightMotorSpeed;

  return result;
}

X_RESULT XInputInputDriver::GetState(uint32_t user_index,
                                     X_INPUT_STATE* out_state) {
  XINPUT_STATE native_state;
  DWORD result = XInputGetState(user_index, &native_state);
  if (result) {
    return result;
  }

  out_state->packet_number = native_state.dwPacketNumber;
  out_state->gamepad.buttons = native_state.Gamepad.wButtons;
  out_state->gamepad.left_trigger = native_state.Gamepad.bLeftTrigger;
  out_state->gamepad.right_trigger = native_state.Gamepad.bRightTrigger;
  out_state->gamepad.thumb_lx = native_state.Gamepad.sThumbLX;
  out_state->gamepad.thumb_ly = native_state.Gamepad.sThumbLY;
  out_state->gamepad.thumb_rx = native_state.Gamepad.sThumbRX;
  out_state->gamepad.thumb_ry = native_state.Gamepad.sThumbRY;

  return result;
}

X_RESULT XInputInputDriver::SetState(uint32_t user_index,
                                     X_INPUT_VIBRATION* vibration) {
  XINPUT_VIBRATION native_vibration;
  native_vibration.wLeftMotorSpeed = vibration->left_motor_speed;
  native_vibration.wRightMotorSpeed = vibration->right_motor_speed;
  DWORD result = XInputSetState(user_index, &native_vibration);
  return result;
}

X_RESULT XInputInputDriver::GetKeystroke(uint32_t user_index, uint32_t flags,
                                         X_INPUT_KEYSTROKE* out_keystroke) {
  // We may want to filter flags/user_index before sending to native.
  // flags is reserved on desktop.
  XINPUT_KEYSTROKE native_keystroke;
  DWORD result = XInputGetKeystroke(user_index, flags, &native_keystroke);
  if (result == ERROR_SUCCESS) {
    out_keystroke->virtual_key = native_keystroke.VirtualKey;
    out_keystroke->unicode = native_keystroke.Unicode;
    out_keystroke->flags = native_keystroke.Flags;
    out_keystroke->user_index = native_keystroke.UserIndex;
    out_keystroke->hid_code = native_keystroke.HidCode;
  }
  // X_ERROR_EMPTY if no new keys
  // X_ERROR_DEVICE_NOT_CONNECTED if no device
  // X_ERROR_SUCCESS if key
  return result;
}

}  // namespace xinput
}  // namespace hid
}  // namespace xe
<commit_msg>Fixed XInputGetKeystroke.<commit_after>/**
 ******************************************************************************
 * Xenia : Xbox 360 Emulator Research Project                                 *
 ******************************************************************************
 * Copyright 2013 Ben Vanik. All rights reserved.                             *
 * Released under the BSD license - see LICENSE in the root for more details. *
 ******************************************************************************
 */

#include "xenia/hid/xinput/xinput_input_driver.h"

#include "xenia/hid/hid-private.h"

#include <Xinput.h>

namespace xe {
namespace hid {
namespace xinput {

XInputInputDriver::XInputInputDriver(InputSystem* input_system)
    : InputDriver(input_system) {
  XInputEnable(TRUE);
}

XInputInputDriver::~XInputInputDriver() { XInputEnable(FALSE); }

X_STATUS XInputInputDriver::Setup() { return X_STATUS_SUCCESS; }

X_RESULT XInputInputDriver::GetCapabilities(uint32_t user_index, uint32_t flags,
                                            X_INPUT_CAPABILITIES* out_caps) {
  XINPUT_CAPABILITIES native_caps;
  DWORD result = XInputGetCapabilities(user_index, flags, &native_caps);
  if (result) {
    return result;
  }

  out_caps->type = native_caps.Type;
  out_caps->sub_type = native_caps.SubType;
  out_caps->flags = native_caps.Flags;
  out_caps->gamepad.buttons = native_caps.Gamepad.wButtons;
  out_caps->gamepad.left_trigger = native_caps.Gamepad.bLeftTrigger;
  out_caps->gamepad.right_trigger = native_caps.Gamepad.bRightTrigger;
  out_caps->gamepad.thumb_lx = native_caps.Gamepad.sThumbLX;
  out_caps->gamepad.thumb_ly = native_caps.Gamepad.sThumbLY;
  out_caps->gamepad.thumb_rx = native_caps.Gamepad.sThumbRX;
  out_caps->gamepad.thumb_ry = native_caps.Gamepad.sThumbRY;
  out_caps->vibration.left_motor_speed = native_caps.Vibration.wLeftMotorSpeed;
  out_caps->vibration.right_motor_speed =
      native_caps.Vibration.wRightMotorSpeed;

  return result;
}

X_RESULT XInputInputDriver::GetState(uint32_t user_index,
                                     X_INPUT_STATE* out_state) {
  XINPUT_STATE native_state;
  DWORD result = XInputGetState(user_index, &native_state);
  if (result) {
    return result;
  }

  out_state->packet_number = native_state.dwPacketNumber;
  out_state->gamepad.buttons = native_state.Gamepad.wButtons;
  out_state->gamepad.left_trigger = native_state.Gamepad.bLeftTrigger;
  out_state->gamepad.right_trigger = native_state.Gamepad.bRightTrigger;
  out_state->gamepad.thumb_lx = native_state.Gamepad.sThumbLX;
  out_state->gamepad.thumb_ly = native_state.Gamepad.sThumbLY;
  out_state->gamepad.thumb_rx = native_state.Gamepad.sThumbRX;
  out_state->gamepad.thumb_ry = native_state.Gamepad.sThumbRY;

  return result;
}

X_RESULT XInputInputDriver::SetState(uint32_t user_index,
                                     X_INPUT_VIBRATION* vibration) {
  XINPUT_VIBRATION native_vibration;
  native_vibration.wLeftMotorSpeed = vibration->left_motor_speed;
  native_vibration.wRightMotorSpeed = vibration->right_motor_speed;
  DWORD result = XInputSetState(user_index, &native_vibration);
  return result;
}

X_RESULT XInputInputDriver::GetKeystroke(uint32_t user_index, uint32_t flags,
                                         X_INPUT_KEYSTROKE* out_keystroke) {
  // We may want to filter flags/user_index before sending to native.
  // flags is reserved on desktop.
  XINPUT_KEYSTROKE native_keystroke;
  DWORD result = XInputGetKeystroke(user_index, flags, &native_keystroke);
  out_keystroke->virtual_key = native_keystroke.VirtualKey;
  out_keystroke->unicode = native_keystroke.Unicode;
  out_keystroke->flags = native_keystroke.Flags;
  out_keystroke->user_index = native_keystroke.UserIndex;
  out_keystroke->hid_code = native_keystroke.HidCode;
  // X_ERROR_EMPTY if no new keys
  // X_ERROR_DEVICE_NOT_CONNECTED if no device
  // X_ERROR_SUCCESS if key
  return result;
}

}  // namespace xinput
}  // namespace hid
}  // namespace xe
<|endoftext|>


<commit_before>#include <iostream>
#include <map>
#include <memory>
#include <string>
#include <vector>
#include <cctype>
namespace workspace {

void example_01() { // -> the "how to do it" section
    {
        auto i = 42;
        auto d = 42.5;
        auto s = "text";
        auto v = { 1, 2, 3 };
    }

    {
        auto b = new char[10]{0};
        auto s1 = std::string{"text"};
        auto v1 = std::vector<int>{ 1, 2, 3 };
        auto p = std::make_shared<int>(42);
    }

    {
        auto upper = [](char const c) { return std::toupper(c); };
    }

    {
        auto add = [](auto const a, auto const b) { return a + b; };
    }
}

void example_02() { // -> the "how it works" section
    {
        auto v = std::vector<int>{ 1, 2, 3 };
        auto size2 = v.size();
    }

    {
        std::map<int, std::string> m;
        for (std::map<int, std::string>::const_iterator it = m.cbegin();
            it != m.cend();
            ++it)
        { /* ... */ }

        for (auto it = m.cbegin(); it != m.cend(); ++it)
        { /* ... */ }
    }

    {
        class foo {
            int x_;
        public:
            foo(int const x = 0) : x_{x} {}
            int& get() { return x_; }
        };

        foo f(42);

        auto x = f.get();
        x = 100;
        std::cout << f.get() << '\n';

        auto& y = f.get();
        y = 100;
        std::cout << f.get() << '\n';
    }

    {
        using llong = long long;
        auto l2 = llong{42};
        auto l3 = 42LL;
    }

    {
        class foo {
            static auto func1(int const i) -> int { return 2 * i; }
            static auto func2(int const i) { return 2 * i; }
        };
    }

    {
        class foo {
            int x_;
        public:
            foo(int const x = 0) : x_{ x } {}
            int& get() { return x_; }

            static decltype(auto) proxy_get(foo& f) { return f.get(); }
        };

        auto f = foo{ 42 };
        decltype(auto) x = foo::proxy_get(f);
    }

    {
        using namespace std::string_literals;

        auto ladd = [] (auto const a, auto const b) { return a + b; };
        auto i = ladd(40, 2);
        auto s = ladd("forty"s, "two"s);
    }
}

void run() {
    std::cout << "how to do it =>" << std::endl; example_01(); std::cout << std::endl;
    std::cout << "how it works =>" << std::endl; example_02(); std::cout << std::endl;
}

} // workspace

int main() {
    workspace::run();

    return 0;
}
<commit_msg>[m_bancila-modern_cpp_progr_cookbook-2_ed][ch 01] slightly rewrite the 1-st example<commit_after>#include <initializer_list>
#include <memory>
#include <string>
#include <vector>
#include <cctype>
namespace example_01 { // -> the "how to do it..." section

template <typename F, typename T>
auto apply(F&& f, T value) {
    return f(value);
}

void run() {
    {
        auto i = 42;
        auto d = 42.5;
        auto s = "text";
        auto v = { 1, 2, 3 };
    }

    {
        auto b  = new char[10]{ 0 };
        auto s1 = std::string{"text"};
        auto v1 = std::vector<int>{ 1, 2, 3 };
        auto p  = std::make_shared<int>(42);
    }

    {
        auto upper = [](char const c) { return std::toupper(c); };
    }

    {
        auto add = [](auto const a, auto const b) { return a + b; };
    }

    {
        const auto func = [](const int value) { return value + 1; };
        apply(func, 10);
    }
}
} // example_01 -> the "how to do it..." section

#include <iostream>
#include <map>
#include <string>
#include <vector>
namespace example_02 { // -> the "how it works..." section

struct {
    template <typename T, typename U>
    auto operator()(T const a, U const b) const { return a + b; }
} lstruct;

void run() {
    {
        const auto v = std::vector<int>{ 1, 2, 3 };
        int size1 = v.size(); // possible loss of data
        auto size2 = v.size();
        // auto size3 = int{ v.size() }; // error
    }

    {
        std::map<int, std::string> m{};
        for (std::map<int, std::string>::const_iterator it = m.cbegin();
            it != m.cend();
            ++it)
        { /* ... */}

        for (auto it = m.cbegin(); it != m.cend(); ++it)
        { /* ... */ }
    }

    {
        class foo {
            int x_;
        public:
            foo(int const x = 0) : x_{ x } {}
            int& get() { return x_; }
        };
        foo f{42};
        auto x = f.get();
        x = 100;
        std::cout << f.get() << '\n';

        auto& y = f.get();
        y = 100;
        std::cout << f.get() << '\n';
    }

    {
        using llong = long long;
        auto l2 = llong{42};
        auto l3 = 42LL;
    }

    {
        class foo {
            static auto func1(int const i) -> int { return 2 * i; }
            static auto func2(int const i) { return 2 * i; }
        };
    }

    {
        class foo {
            int x_;
        public:
            foo(int const x = 0) : x_{x} {}
            int& get() { return x_; }

            static auto proxy_get(foo& f) { return f.get(); }
        };

        auto f = foo{42};
        // auto& x = foo::proxy_get(f); // error
    }

    {
        class foo {
            int x_;
        public:
            foo(int const x = 0) : x_{x} {}
            int& get() { return x_; }

            static decltype(auto) proxy_get(foo& f) { return f.get(); }
        };

        auto f = foo{42};
        decltype(auto) x = foo::proxy_get(f);
    }

    {
        using namespace std::string_literals;

        auto ladd = [](auto const a, auto const b) { return a + b; };
        auto i = ladd(40, 2);
        auto s = ladd("forty"s, "two"s);
    }

    {
        using namespace std::string_literals;

        auto i = lstruct(40, 2);
        auto s = lstruct("forty"s, "two"s);
    }
}
} // example_02 -> the "how it works..." section

#include <iostream>
int main() {
    std::cout << "example_01 =>" << std::endl; example_01::run(); std::cout << std::endl;
    std::cout << "example_02 =>" << std::endl; example_02::run(); std::cout << std::endl;

    return 0;
}
<|endoftext|>