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

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"

#ifndef _WRTSH_HXX
#include <wrtsh.hxx>
#endif
#ifndef _CRSSKIP_HXX
#include <crsskip.hxx>
#endif

/*
* private Methoden, die den Cursor ueber Suchen bewegen. Das
* Aufheben der Selektion muss auf der Ebene darueber erfolgen.
*/

/*
* Der Anfang eines Wortes ist das Folgen eines nicht-
* Trennzeichens auf Trennzeichen. Ferner das Folgen von
* nicht-Satztrennern auf Satztrenner. Der Absatzanfang ist
* ebenfalls Wortanfang.
*/

BOOL SwWrtShell::_SttWrd()
{
    if ( IsSttPara() )
        return 1;
        /*
            * temporaeren Cursor ohne Selektion erzeugen
            */
    Push();
    ClearMark();
    if( !GoStartWord() )
            // nicht gefunden --> an den Absatzanfang
        SwCrsrShell::MovePara( fnParaCurr, fnParaStart );
    ClearMark();
        // falls vorher Mark gesetzt war, zusammenfassen
    Combine();
    return 1;
}
/*
 * Das Ende eines Wortes ist das Folgen von Trennzeichen auf
 * nicht-Trennzeichen.  Unter dem Ende eines Wortes wird
 * ebenfalls die Folge von Worttrennzeichen auf Interpunktions-
 * zeichen verstanden. Das Absatzende ist ebenfalls Wortende.
 */

BOOL SwWrtShell::_EndWrd()
{
    if ( IsEndWrd() )
        return 1;
        // temporaeren Cursor ohne Selektion erzeugen
    Push();
    ClearMark();
    if( !GoEndWord() )
            // nicht gefunden --> an das Absatz Ende
        SwCrsrShell::MovePara(fnParaCurr, fnParaEnd);
    ClearMark();
        // falls vorher Mark gesetzt war, zusammenfassen
    Combine();
    return 1;
}

BOOL SwWrtShell::_NxtWrd()
{
    if( IsEndPara() )               // wenn schon am Ende, dann naechsten ???
    {
        if(!SwCrsrShell::Right(1,CRSR_SKIP_CHARS))  // Document - Ende ??
        {
            Pop( FALSE );
            return 0L;
        }
        return 1;
    }
    Push();
    ClearMark();
    if( !GoNextWord() )
            // nicht gefunden --> das AbsatzEnde ist Ende vom Wort
        SwCrsrShell::MovePara( fnParaCurr, fnParaEnd );
    ClearMark();
    Combine();
    return 1;
}

BOOL SwWrtShell::_PrvWrd()
{
    if(IsSttPara())
    {                               // wenn schon am Anfang, dann naechsten ???
        if(!SwCrsrShell::Left(1,CRSR_SKIP_CHARS))
        {                           // Document - Anfang ??
            Pop( FALSE );
            return 0;
        }
        return 1;
    }
    Push();
    ClearMark();
    if( !GoPrevWord() )
            // nicht gefunden --> an den Absatz Anfang
        SwCrsrShell::MovePara( fnParaCurr, fnParaStart );
    ClearMark();
    Combine();
    return 1;
}

BOOL SwWrtShell::_FwdSentence()
{
    Push();
    ClearMark();
    if(!SwCrsrShell::Right(1,CRSR_SKIP_CHARS))
    {
        Pop(FALSE);
        return 0;
    }
    if( !GoNextSentence() && !IsEndPara() )
        SwCrsrShell::MovePara(fnParaCurr, fnParaEnd);

    ClearMark();
    Combine();
    return 1;
}

BOOL SwWrtShell::_BwdSentence()
{
    Push();
    ClearMark();
    if(!SwCrsrShell::Left(1,CRSR_SKIP_CHARS))
    {
        Pop(FALSE);
        return 0;
    }
    if(IsSttPara())
    {
        Pop();
        return 1;
    }
    if( !GoPrevSentence()  && !IsSttPara() )
            // nicht gefunden --> an den Absatz Anfang
        SwCrsrShell::MovePara( fnParaCurr, fnParaStart );
    ClearMark();
    Combine();
    return 1;
}

BOOL SwWrtShell::_FwdPara()
{
    Push();
    ClearMark();
    if(!SwCrsrShell::Right(1,CRSR_SKIP_CHARS))
    {
        Pop(FALSE);
        return 0;
    }
    SwCrsrShell::Left(1,CRSR_SKIP_CHARS);
    BOOL bRet = SwCrsrShell::MovePara(fnParaNext, fnParaStart);

    ClearMark();
    Combine();
    return bRet;
}

BOOL SwWrtShell::_BwdPara()
{
    Push();
    ClearMark();
    if(!SwCrsrShell::Left(1,CRSR_SKIP_CHARS))
    {
        Pop(FALSE);
        return 0;
    }
    SwCrsrShell::Right(1,CRSR_SKIP_CHARS);
    if(!IsSttOfPara())
        SttPara();
    BOOL bRet = SwCrsrShell::MovePara(fnParaPrev, fnParaStart);

    ClearMark();
    Combine();
    return bRet;
}

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

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"

#include <wrtsh.hxx>
#include <crsskip.hxx>

/*
* private Methoden, die den Cursor ueber Suchen bewegen. Das
* Aufheben der Selektion muss auf der Ebene darueber erfolgen.
*/

/*
* Der Anfang eines Wortes ist das Folgen eines nicht-
* Trennzeichens auf Trennzeichen. Ferner das Folgen von
* nicht-Satztrennern auf Satztrenner. Der Absatzanfang ist
* ebenfalls Wortanfang.
*/

BOOL SwWrtShell::_SttWrd()
{
    if ( IsSttPara() )
        return 1;
        /*
            * temporaeren Cursor ohne Selektion erzeugen
            */
    Push();
    ClearMark();
    if( !GoStartWord() )
            // nicht gefunden --> an den Absatzanfang
        SwCrsrShell::MovePara( fnParaCurr, fnParaStart );
    ClearMark();
        // falls vorher Mark gesetzt war, zusammenfassen
    Combine();
    return 1;
}
/*
 * Das Ende eines Wortes ist das Folgen von Trennzeichen auf
 * nicht-Trennzeichen.  Unter dem Ende eines Wortes wird
 * ebenfalls die Folge von Worttrennzeichen auf Interpunktions-
 * zeichen verstanden. Das Absatzende ist ebenfalls Wortende.
 */

BOOL SwWrtShell::_EndWrd()
{
    if ( IsEndWrd() )
        return 1;
        // temporaeren Cursor ohne Selektion erzeugen
    Push();
    ClearMark();
    if( !GoEndWord() )
            // nicht gefunden --> an das Absatz Ende
        SwCrsrShell::MovePara(fnParaCurr, fnParaEnd);
    ClearMark();
        // falls vorher Mark gesetzt war, zusammenfassen
    Combine();
    return 1;
}

BOOL SwWrtShell::_NxtWrd()
{
    if( IsEndPara() )               // wenn schon am Ende, dann naechsten ???
    {
        if(!SwCrsrShell::Right(1,CRSR_SKIP_CHARS))  // Document - Ende ??
        {
            Pop( FALSE );
            return 0L;
        }
        return 1;
    }
    Push();
    ClearMark();
    if( !GoNextWord() )
            // nicht gefunden --> das AbsatzEnde ist Ende vom Wort
        SwCrsrShell::MovePara( fnParaCurr, fnParaEnd );
    ClearMark();
    Combine();
    return 1;
}

BOOL SwWrtShell::_PrvWrd()
{
    if(IsSttPara())
    {                               // wenn schon am Anfang, dann naechsten ???
        if(!SwCrsrShell::Left(1,CRSR_SKIP_CHARS))
        {                           // Document - Anfang ??
            Pop( FALSE );
            return 0;
        }
        return 1;
    }
    Push();
    ClearMark();
    if( !GoPrevWord() )
            // nicht gefunden --> an den Absatz Anfang
        SwCrsrShell::MovePara( fnParaCurr, fnParaStart );
    ClearMark();
    Combine();
    return 1;
}

BOOL SwWrtShell::_FwdSentence()
{
    Push();
    ClearMark();
    if(!SwCrsrShell::Right(1,CRSR_SKIP_CHARS))
    {
        Pop(FALSE);
        return 0;
    }
    if( !GoNextSentence() && !IsEndPara() )
        SwCrsrShell::MovePara(fnParaCurr, fnParaEnd);

    ClearMark();
    Combine();
    return 1;
}

BOOL SwWrtShell::_BwdSentence()
{
    Push();
    ClearMark();
    if(!SwCrsrShell::Left(1,CRSR_SKIP_CHARS))
    {
        Pop(FALSE);
        return 0;
    }
    if(IsSttPara())
    {
        Pop();
        return 1;
    }
    if( !GoPrevSentence()  && !IsSttPara() )
            // nicht gefunden --> an den Absatz Anfang
        SwCrsrShell::MovePara( fnParaCurr, fnParaStart );
    ClearMark();
    Combine();
    return 1;
}

BOOL SwWrtShell::_FwdPara()
{
    Push();
    ClearMark();
    if(!SwCrsrShell::Right(1,CRSR_SKIP_CHARS))
    {
        Pop(FALSE);
        return 0;
    }
    SwCrsrShell::Left(1,CRSR_SKIP_CHARS);
    BOOL bRet = SwCrsrShell::MovePara(fnParaNext, fnParaStart);

    ClearMark();
    Combine();
    return bRet;
}

BOOL SwWrtShell::_BwdPara()
{
    Push();
    ClearMark();
    if(!SwCrsrShell::Left(1,CRSR_SKIP_CHARS))
    {
        Pop(FALSE);
        return 0;
    }
    SwCrsrShell::Right(1,CRSR_SKIP_CHARS);
    if(!IsSttOfPara())
        SttPara();
    BOOL bRet = SwCrsrShell::MovePara(fnParaPrev, fnParaStart);

    ClearMark();
    Combine();
    return bRet;
}

<|endoftext|>


<commit_before>#include "options.h"

namespace nng {

    options::options() {
    }

    option_names::option_names() {
    }

    const std::string option_names::raw = NNG_OPT_RAW;
    const std::string option_names::linger = NNG_OPT_LINGER;
    const std::string option_names::receive_buffer = NNG_OPT_RECVBUF;
    const std::string option_names::send_buffer = NNG_OPT_SENDBUF;
    const std::string option_names::receive_file_descriptor = NNG_OPT_RECVFD;
    const std::string option_names::send_file_descriptor = NNG_OPT_SENDFD;
    const std::string option_names::receive_timeout_usec = NNG_OPT_RECVTIMEO;
    const std::string option_names::send_timeout_usec = NNG_OPT_SENDTIMEO;
    const std::string option_names::local_address = NNG_OPT_LOCADDR;
    const std::string option_names::remote_address = NNG_OPT_REMADDR;
    const std::string option_names::url = NNG_OPT_URL;
    const std::string option_names::max_ttl = NNG_OPT_MAXTTL;
    const std::string option_names::protocol = NNG_OPT_PROTOCOL;
    const std::string option_names::transport = NNG_OPT_TRANSPORT;
    const std::string option_names::receive_max_size = NNG_OPT_RECVMAXSZ;
    const std::string option_names::min_reconnect_time_usec = NNG_OPT_RECONNMINT;
    const std::string option_names::sub_subscribe = NNG_OPT_SUB_SUBSCRIBE;
    const std::string option_names::surveyor_survey_time_usec = NNG_OPT_SURVEYOR_SURVEYTIME;
}
<commit_msg>added symbol definition to the source code<commit_after>#include "options.h"

namespace nng {

    options::options() {
    }

    option_names::option_names() {
    }

    const std::string option_names::raw = NNG_OPT_RAW;
    const std::string option_names::linger = NNG_OPT_LINGER;
    const std::string option_names::receive_buffer = NNG_OPT_RECVBUF;
    const std::string option_names::send_buffer = NNG_OPT_SENDBUF;
    const std::string option_names::receive_file_descriptor = NNG_OPT_RECVFD;
    const std::string option_names::send_file_descriptor = NNG_OPT_SENDFD;
    const std::string option_names::receive_timeout_usec = NNG_OPT_RECVTIMEO;
    const std::string option_names::send_timeout_usec = NNG_OPT_SENDTIMEO;
    const std::string option_names::local_address = NNG_OPT_LOCADDR;
    const std::string option_names::remote_address = NNG_OPT_REMADDR;
    const std::string option_names::url = NNG_OPT_URL;
    const std::string option_names::max_ttl = NNG_OPT_MAXTTL;
    const std::string option_names::protocol = NNG_OPT_PROTOCOL;
    const std::string option_names::transport = NNG_OPT_TRANSPORT;
    const std::string option_names::receive_max_size = NNG_OPT_RECVMAXSZ;
    const std::string option_names::min_reconnect_time_usec = NNG_OPT_RECONNMINT;
    const std::string option_names::max_reconnect_time_usec = NNG_OPT_RECONNMAXT;
    const std::string option_names::sub_subscribe = NNG_OPT_SUB_SUBSCRIBE;
    const std::string option_names::surveyor_survey_time_usec = NNG_OPT_SURVEYOR_SURVEYTIME;
}
<|endoftext|>


<commit_before>/*********************************************************************
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2012, Willow Garage, Inc.
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * 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.
 *   * Neither the name of Willow Garage nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  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.
 *********************************************************************/

/* Author: Ioan Sucan, Robert Haschke */

#include "query_planners_service_capability.h"
#include <moveit/planning_pipeline/planning_pipeline.h>
#include <moveit/move_group/capability_names.h>

move_group::MoveGroupQueryPlannersService::MoveGroupQueryPlannersService():
  MoveGroupCapability("QueryPlannersService")
{
}

void move_group::MoveGroupQueryPlannersService::initialize()
{
  query_service_ = root_node_handle_.advertiseService(QUERY_PLANNERS_SERVICE_NAME, &MoveGroupQueryPlannersService::queryInterface, this);

  get_service_ = root_node_handle_.advertiseService(GET_PLANNER_PARAMS_SERVICE_NAME,
                                                    &MoveGroupQueryPlannersService::getParams, this);
  set_service_ = root_node_handle_.advertiseService(SET_PLANNER_PARAMS_SERVICE_NAME,
                                                    &MoveGroupQueryPlannersService::setParams, this);
}

bool move_group::MoveGroupQueryPlannersService::queryInterface(moveit_msgs::QueryPlannerInterfaces::Request &req, moveit_msgs::QueryPlannerInterfaces::Response &res)
{
  const planning_interface::PlannerManagerPtr &planner_interface = context_->planning_pipeline_->getPlannerManager();
  if (planner_interface)
  {
    std::vector<std::string> algs;
    planner_interface->getPlanningAlgorithms(algs);
    moveit_msgs::PlannerInterfaceDescription pi_desc;
    pi_desc.name = planner_interface->getDescription();
    planner_interface->getPlanningAlgorithms(pi_desc.planner_ids);
    res.planner_interfaces.push_back(pi_desc);
  }
  return true;
}

bool move_group::MoveGroupQueryPlannersService::getParams(moveit_msgs::GetPlannerParams::Request &req,
                                                          moveit_msgs::GetPlannerParams::Response &res)
{
  const planning_interface::PlannerManagerPtr &planner_interface = context_->planning_pipeline_->getPlannerManager();
  if (planner_interface)
  {
    std::map<std::string, std::string> config;

    const planning_interface::PlannerConfigurationMap&
        configs = planner_interface->getPlannerConfigurations();

    planning_interface::PlannerConfigurationMap::const_iterator
        it = configs.find(req.planner_config); // fetch default params first
    config.insert(it->second.config.begin(), it->second.config.end());

    if (!req.group.empty()) { // merge in group-specific params
      it = configs.find(req.group + "[" + req.planner_config + "]");
      config.insert(it->second.config.begin(), it->second.config.end());
    }

    for (std::map<std::string, std::string>::const_iterator
         it = config.begin(), end = config.end(); it != end; ++it) {
      res.params.keys.push_back(it->first);
      res.params.values.push_back(it->second);
    }
  }
  return true;
}

bool move_group::MoveGroupQueryPlannersService::setParams(moveit_msgs::SetPlannerParams::Request &req,
                                                          moveit_msgs::SetPlannerParams::Response &res)
{
  const planning_interface::PlannerManagerPtr &planner_interface = context_->planning_pipeline_->getPlannerManager();
  if (req.params.keys.size() != req.params.values.size())
    return false;

  if (planner_interface)
  {
    planning_interface::PlannerConfigurationMap
        configs = planner_interface->getPlannerConfigurations();
    std::string config_name = req.group.empty() ?
          req.planner_config : req.group + "[" + req.planner_config + "]";

    planning_interface::PlannerConfigurationSettings &config = configs[config_name];
    config.group = req.group;
    config.name = config_name;
    if (req.replace) config.config.clear();
    for (unsigned int i=0, end=req.params.keys.size(); i < end; ++i)
      config.config[req.params.keys[i]] = req.params.values[i];

    planner_interface->setPlannerConfigurations(configs);
  }
  return true;
}

#include <class_loader/class_loader.h>
CLASS_LOADER_REGISTER_CLASS(move_group::MoveGroupQueryPlannersService, move_group::MoveGroupCapability)
<commit_msg>added missing validity check<commit_after>/*********************************************************************
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2012, Willow Garage, Inc.
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * 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.
 *   * Neither the name of Willow Garage nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  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.
 *********************************************************************/

/* Author: Ioan Sucan, Robert Haschke */

#include "query_planners_service_capability.h"
#include <moveit/planning_pipeline/planning_pipeline.h>
#include <moveit/move_group/capability_names.h>

move_group::MoveGroupQueryPlannersService::MoveGroupQueryPlannersService():
  MoveGroupCapability("QueryPlannersService")
{
}

void move_group::MoveGroupQueryPlannersService::initialize()
{
  query_service_ = root_node_handle_.advertiseService(QUERY_PLANNERS_SERVICE_NAME, &MoveGroupQueryPlannersService::queryInterface, this);

  get_service_ = root_node_handle_.advertiseService(GET_PLANNER_PARAMS_SERVICE_NAME,
                                                    &MoveGroupQueryPlannersService::getParams, this);
  set_service_ = root_node_handle_.advertiseService(SET_PLANNER_PARAMS_SERVICE_NAME,
                                                    &MoveGroupQueryPlannersService::setParams, this);
}

bool move_group::MoveGroupQueryPlannersService::queryInterface(moveit_msgs::QueryPlannerInterfaces::Request &req, moveit_msgs::QueryPlannerInterfaces::Response &res)
{
  const planning_interface::PlannerManagerPtr &planner_interface = context_->planning_pipeline_->getPlannerManager();
  if (planner_interface)
  {
    std::vector<std::string> algs;
    planner_interface->getPlanningAlgorithms(algs);
    moveit_msgs::PlannerInterfaceDescription pi_desc;
    pi_desc.name = planner_interface->getDescription();
    planner_interface->getPlanningAlgorithms(pi_desc.planner_ids);
    res.planner_interfaces.push_back(pi_desc);
  }
  return true;
}

bool move_group::MoveGroupQueryPlannersService::getParams(moveit_msgs::GetPlannerParams::Request &req,
                                                          moveit_msgs::GetPlannerParams::Response &res)
{
  const planning_interface::PlannerManagerPtr &planner_interface = context_->planning_pipeline_->getPlannerManager();
  if (planner_interface)
  {
    std::map<std::string, std::string> config;

    const planning_interface::PlannerConfigurationMap&
        configs = planner_interface->getPlannerConfigurations();

    planning_interface::PlannerConfigurationMap::const_iterator
        it = configs.find(req.planner_config); // fetch default params first
    if (it != configs.end())
      config.insert(it->second.config.begin(), it->second.config.end());

    if (!req.group.empty()) { // merge in group-specific params
      it = configs.find(req.group + "[" + req.planner_config + "]");
      if (it != configs.end())
        config.insert(it->second.config.begin(), it->second.config.end());
    }

    for (std::map<std::string, std::string>::const_iterator
         it = config.begin(), end = config.end(); it != end; ++it) {
      res.params.keys.push_back(it->first);
      res.params.values.push_back(it->second);
    }
  }
  return true;
}

bool move_group::MoveGroupQueryPlannersService::setParams(moveit_msgs::SetPlannerParams::Request &req,
                                                          moveit_msgs::SetPlannerParams::Response &res)
{
  const planning_interface::PlannerManagerPtr &planner_interface = context_->planning_pipeline_->getPlannerManager();
  if (req.params.keys.size() != req.params.values.size())
    return false;

  if (planner_interface)
  {
    planning_interface::PlannerConfigurationMap
        configs = planner_interface->getPlannerConfigurations();
    std::string config_name = req.group.empty() ?
          req.planner_config : req.group + "[" + req.planner_config + "]";

    planning_interface::PlannerConfigurationSettings &config = configs[config_name];
    config.group = req.group;
    config.name = config_name;
    if (req.replace) config.config.clear();
    for (unsigned int i=0, end=req.params.keys.size(); i < end; ++i)
      config.config[req.params.keys[i]] = req.params.values[i];

    planner_interface->setPlannerConfigurations(configs);
  }
  return true;
}

#include <class_loader/class_loader.h>
CLASS_LOADER_REGISTER_CLASS(move_group::MoveGroupQueryPlannersService, move_group::MoveGroupCapability)
<|endoftext|>


<commit_before>#include <chrono>
#include <cstdint>

#include "envoy/config/endpoint/v3/endpoint_components.pb.h"

#include "source/common/common/base64.h"
#include "source/common/http/utility.h"
#include "source/common/protobuf/protobuf.h"
#include "source/extensions/filters/http/stateful_session/stateful_session.h"

#include "test/integration/http_integration.h"

#include "gtest/gtest.h"

namespace Envoy {
namespace Extensions {
namespace HttpFilters {
namespace StatefulSession {
namespace {

class StatefulSessionIntegrationTest : public Envoy::HttpIntegrationTest, public testing::Test {
public:
  StatefulSessionIntegrationTest()
      : HttpIntegrationTest(
            Http::CodecType::HTTP1,
            [](int i) { return Network::Utility::parseInternetAddress("127.0.0.1", 50000 + i); },
            Network::Address::IpVersion::v4) {
    // Create 4 different upstream server for stateful session test.
    setUpstreamCount(4);

    skipPortUsageValidation();

    // Update endpoints of default cluster `cluster_0` to 4 different fake upstreams.
    config_helper_.addConfigModifier([](envoy::config::bootstrap::v3::Bootstrap& bootstrap) {
      auto* cluster_0 = bootstrap.mutable_static_resources()->mutable_clusters()->Mutable(0);
      ASSERT(cluster_0->name() == "cluster_0");
      auto* endpoint = cluster_0->mutable_load_assignment()->mutable_endpoints()->Mutable(0);

      const std::string EndpointsYaml = R"EOF(
        lb_endpoints:
        - endpoint:
            address:
              socket_address:
                address: 127.0.0.1
                port_value: 50000
        - endpoint:
            address:
              socket_address:
                address: 127.0.0.1
                port_value: 50001
        - endpoint:
            address:
              socket_address:
                address: 127.0.0.1
                port_value: 50002
        - endpoint:
            address:
              socket_address:
                address: 127.0.0.1
                port_value: 50003
      )EOF";

      envoy::config::endpoint::v3::LocalityLbEndpoints new_lb_endpints;
      TestUtility::loadFromYaml(EndpointsYaml, new_lb_endpints);
      *endpoint = new_lb_endpints;
    });
  }

  // Initialize route filter and per route config.
  void initializeFilterAndRoute(const std::string& filter_yaml,
                                const std::string& per_route_config_yaml) {
    config_helper_.prependFilter(filter_yaml);

    // Create virtual host with domain `stateful.session.com` and default route to `cluster_0`
    auto virtual_host = config_helper_.createVirtualHost("stateful.session.com");

    // Update per route config of default route.
    if (!per_route_config_yaml.empty()) {
      auto* route = virtual_host.mutable_routes(0);
      ProtobufWkt::Any per_route_config;
      TestUtility::loadFromYaml(per_route_config_yaml, per_route_config);

      route->mutable_typed_per_filter_config()->insert(
          {"envoy.filters.http.stateful_session", per_route_config});
    }
    config_helper_.addVirtualHost(virtual_host);

    initialize();
  }
};

static const std::string STATEFUL_SESSION_FILTER =
    R"EOF(
name: envoy.filters.http.stateful_session
typed_config:
  "@type": type.googleapis.com/envoy.extensions.filters.http.stateful_session.v3.StatefulSession
  session_state:
    name: envoy.http.stateful_session.cookie
    typed_config:
      "@type": type.googleapis.com/envoy.extensions.http.stateful_session.cookie.v3.CookieBasedSessionState
      cookie:
        name: global-session-cookie
        path: /path
        ttl: 120s
)EOF";

static const std::string DISABLE_STATEFUL_SESSION =
    R"EOF(
"@type": type.googleapis.com/envoy.extensions.filters.http.stateful_session.v3.StatefulSessionPerRoute
disabled: true
)EOF";

static const std::string OVERRIDE_STATEFUL_SESSION =
    R"EOF(
"@type": type.googleapis.com/envoy.extensions.filters.http.stateful_session.v3.StatefulSessionPerRoute
stateful_session:
  session_state:
    name: envoy.http.stateful_session.cookie
    typed_config:
      "@type": type.googleapis.com/envoy.extensions.http.stateful_session.cookie.v3.CookieBasedSessionState
      cookie:
        name: route-session-cookie
        path: /path
        ttl: 120s
)EOF";

TEST_F(StatefulSessionIntegrationTest, NormalStatefulSession) {
  initializeFilterAndRoute(STATEFUL_SESSION_FILTER, "");

  codec_client_ = makeHttpConnection(lookupPort("http"));

  Http::TestRequestHeaderMapImpl request_headers{{":method", "GET"},
                                                 {":path", "/test"},
                                                 {":scheme", "http"},
                                                 {":authority", "stateful.session.com"}};

  auto response = codec_client_->makeRequestWithBody(request_headers, 0);

  auto upstream_index = waitForNextUpstreamRequest({0, 1, 2, 3});
  ASSERT(upstream_index.has_value());
  const std::string address_string = fmt::format("127.0.0.1:{}", upstream_index.value() + 50000);
  const std::string encoded_address = Envoy::Base64::encode(address_string.data(), 15);

  upstream_request_->encodeHeaders(default_response_headers_, true);

  ASSERT_TRUE(response->waitForEndStream());

  EXPECT_TRUE(upstream_request_->complete());
  EXPECT_TRUE(response->complete());

  // The selected upstream server address would be selected to the response headers.
  EXPECT_EQ(
      Envoy::Http::Utility::makeSetCookieValue("global-session-cookie", encoded_address, "/path",
                                               std::chrono::seconds(120), true),
      response->headers().get(Http::LowerCaseString("set-cookie"))[0]->value().getStringView());

  cleanupUpstreamAndDownstream();
}

TEST_F(StatefulSessionIntegrationTest, DownstreamRequestWithStatefulSessionCookie) {
  initializeFilterAndRoute(STATEFUL_SESSION_FILTER, "");

  {
    codec_client_ = makeHttpConnection(lookupPort("http"));
    Http::TestRequestHeaderMapImpl request_headers{
        {":method", "GET"},
        {":path", "/test"},
        {":scheme", "http"},
        {":authority", "stateful.session.com"},
        {"cookie", fmt::format("global-session-cookie=\"{}\"",
                               Envoy::Base64::encode("127.0.0.1:50001", 15))}};

    auto response = codec_client_->makeRequestWithBody(request_headers, 0);

    // `127.0.0.1:50001` should be selected and it's upstream index is 1.
    auto upstream_index = waitForNextUpstreamRequest({0, 1, 2, 3});
    EXPECT_EQ(upstream_index.value(), 1);

    upstream_request_->encodeHeaders(default_response_headers_, true);

    ASSERT_TRUE(response->waitForEndStream());

    EXPECT_TRUE(upstream_request_->complete());
    EXPECT_TRUE(response->complete());

    // No response header to be added.
    EXPECT_TRUE(response->headers().get(Http::LowerCaseString("set-cookie")).empty());

    cleanupUpstreamAndDownstream();
  }

  {
    codec_client_ = makeHttpConnection(lookupPort("http"));
    Http::TestRequestHeaderMapImpl request_headers{
        {":method", "GET"},
        {":path", "/test"},
        {":scheme", "http"},
        {":authority", "stateful.session.com"},
        {"cookie", fmt::format("global-session-cookie=\"{}\"",
                               Envoy::Base64::encode("127.0.0.1:50002", 15))}};

    auto response = codec_client_->makeRequestWithBody(request_headers, 0);

    // `127.0.0.1:50002` should be selected and it's upstream index is 2.
    auto upstream_index = waitForNextUpstreamRequest({0, 1, 2, 3});
    EXPECT_EQ(upstream_index.value(), 2);

    upstream_request_->encodeHeaders(default_response_headers_, true);

    ASSERT_TRUE(response->waitForEndStream());

    EXPECT_TRUE(upstream_request_->complete());
    EXPECT_TRUE(response->complete());

    // No response header to be added.
    EXPECT_TRUE(response->headers().get(Http::LowerCaseString("set-cookie")).empty());

    cleanupUpstreamAndDownstream();
  }

  // Test the case that stateful session cookie with unknown server address.
  {
    codec_client_ = makeHttpConnection(lookupPort("http"));
    Http::TestRequestHeaderMapImpl request_headers{
        {":method", "GET"},
        {":path", "/test"},
        {":scheme", "http"},
        {":authority", "stateful.session.com"},
        {"cookie", fmt::format("global-session-cookie=\"{}\"",
                               Envoy::Base64::encode("127.0.0.1:50005", 15))}};

    auto response = codec_client_->makeRequestWithBody(request_headers, 0);

    auto upstream_index = waitForNextUpstreamRequest({0, 1, 2, 3});
    ASSERT(upstream_index.has_value());
    const std::string address_string = fmt::format("127.0.0.1:{}", upstream_index.value() + 50000);
    const std::string encoded_address = Envoy::Base64::encode(address_string.data(), 15);

    upstream_request_->encodeHeaders(default_response_headers_, true);

    ASSERT_TRUE(response->waitForEndStream());

    EXPECT_TRUE(upstream_request_->complete());
    EXPECT_TRUE(response->complete());

    // The selected upstream server address would be selected to the response headers.
    EXPECT_EQ(
        Envoy::Http::Utility::makeSetCookieValue("global-session-cookie", encoded_address, "/path",
                                                 std::chrono::seconds(120), true),
        response->headers().get(Http::LowerCaseString("set-cookie"))[0]->value().getStringView());

    cleanupUpstreamAndDownstream();
  }
}

TEST_F(StatefulSessionIntegrationTest, StatefulSessionDisabledByRoute) {
  initializeFilterAndRoute(STATEFUL_SESSION_FILTER, DISABLE_STATEFUL_SESSION);

  uint64_t first_index = 0;
  uint64_t second_index = 0;

  {
    codec_client_ = makeHttpConnection(lookupPort("http"));
    Http::TestRequestHeaderMapImpl request_headers{
        {":method", "GET"},
        {":path", "/test"},
        {":scheme", "http"},
        {":authority", "stateful.session.com"},
        {"cookie", fmt::format("global-session-cookie=\"{}\"",
                               Envoy::Base64::encode("127.0.0.1:50001", 15))}};

    auto response = codec_client_->makeRequestWithBody(request_headers, 0);

    auto upstream_index = waitForNextUpstreamRequest({0, 1, 2, 3});
    ASSERT(upstream_index.has_value());
    first_index = upstream_index.value();

    upstream_request_->encodeHeaders(default_response_headers_, true);

    ASSERT_TRUE(response->waitForEndStream());

    EXPECT_TRUE(upstream_request_->complete());
    EXPECT_TRUE(response->complete());

    // No response header to be added.
    EXPECT_TRUE(response->headers().get(Http::LowerCaseString("set-cookie")).empty());

    cleanupUpstreamAndDownstream();
  }

  {
    codec_client_ = makeHttpConnection(lookupPort("http"));
    Http::TestRequestHeaderMapImpl request_headers{
        {":method", "GET"},
        {":path", "/test"},
        {":scheme", "http"},
        {":authority", "stateful.session.com"},
        {"cookie", fmt::format("global-session-cookie=\"{}\"",
                               Envoy::Base64::encode("127.0.0.1:50001", 15))}};

    auto response = codec_client_->makeRequestWithBody(request_headers, 0);

    auto upstream_index = waitForNextUpstreamRequest({0, 1, 2, 3});
    ASSERT(upstream_index.has_value());
    second_index = upstream_index.value();

    upstream_request_->encodeHeaders(default_response_headers_, true);

    ASSERT_TRUE(response->waitForEndStream());

    EXPECT_TRUE(upstream_request_->complete());
    EXPECT_TRUE(response->complete());

    // No response header to be added.
    EXPECT_TRUE(response->headers().get(Http::LowerCaseString("set-cookie")).empty());

    cleanupUpstreamAndDownstream();
  }

  // Choose different upstream servers by default.
  EXPECT_NE(first_index, second_index);
}

TEST_F(StatefulSessionIntegrationTest, StatefulSessionOverriddenByRoute) {
  initializeFilterAndRoute(STATEFUL_SESSION_FILTER, OVERRIDE_STATEFUL_SESSION);

  {
    codec_client_ = makeHttpConnection(lookupPort("http"));
    Http::TestRequestHeaderMapImpl request_headers{
        {":method", "GET"},
        {":path", "/test"},
        {":scheme", "http"},
        {":authority", "stateful.session.com"},
        {"cookie", fmt::format("global-session-cookie=\"{}\"",
                               Envoy::Base64::encode("127.0.0.1:50001", 15))}};

    auto response = codec_client_->makeRequestWithBody(request_headers, 0);

    auto upstream_index = waitForNextUpstreamRequest({0, 1, 2, 3});
    ASSERT(upstream_index.has_value());
    const std::string address_string = fmt::format("127.0.0.1:{}", upstream_index.value() + 50000);
    const std::string encoded_address = Envoy::Base64::encode(address_string.data(), 15);

    upstream_request_->encodeHeaders(default_response_headers_, true);

    ASSERT_TRUE(response->waitForEndStream());

    EXPECT_TRUE(upstream_request_->complete());
    EXPECT_TRUE(response->complete());

    EXPECT_EQ(
        Envoy::Http::Utility::makeSetCookieValue("route-session-cookie", encoded_address, "/path",
                                                 std::chrono::seconds(120), true),
        response->headers().get(Http::LowerCaseString("set-cookie"))[0]->value().getStringView());

    cleanupUpstreamAndDownstream();
  }

  {
    codec_client_ = makeHttpConnection(lookupPort("http"));
    Http::TestRequestHeaderMapImpl request_headers{
        {":method", "GET"},
        {":path", "/test"},
        {":scheme", "http"},
        {":authority", "stateful.session.com"},
        {"cookie",
         fmt::format("route-session-cookie=\"{}\"", Envoy::Base64::encode("127.0.0.1:50002", 15))}};

    auto response = codec_client_->makeRequestWithBody(request_headers, 0);

    // Stateful session is overridden and `127.0.0.1:50002` should be selected.
    auto upstream_index = waitForNextUpstreamRequest({0, 1, 2, 3});
    EXPECT_EQ(upstream_index.value(), 2);

    upstream_request_->encodeHeaders(default_response_headers_, true);

    ASSERT_TRUE(response->waitForEndStream());

    EXPECT_TRUE(upstream_request_->complete());
    EXPECT_TRUE(response->complete());

    // No response header to be added.
    EXPECT_TRUE(response->headers().get(Http::LowerCaseString("set-cookie")).empty());

    cleanupUpstreamAndDownstream();
  }
}

} // namespace
} // namespace StatefulSession
} // namespace HttpFilters
} // namespace Extensions
} // namespace Envoy
<commit_msg>fix stateful session test flakes (#19560)<commit_after>#include <chrono>
#include <cstdint>

#include "envoy/config/endpoint/v3/endpoint_components.pb.h"

#include "source/common/common/base64.h"
#include "source/common/http/utility.h"
#include "source/common/protobuf/protobuf.h"
#include "source/extensions/filters/http/stateful_session/stateful_session.h"

#include "test/integration/http_integration.h"

#include "gtest/gtest.h"

namespace Envoy {
namespace Extensions {
namespace HttpFilters {
namespace StatefulSession {
namespace {

class StatefulSessionIntegrationTest : public Envoy::HttpIntegrationTest, public testing::Test {
public:
  StatefulSessionIntegrationTest()
      : HttpIntegrationTest(Http::CodecType::HTTP1, Network::Address::IpVersion::v4) {
    // Create 4 different upstream server for stateful session test.
    setUpstreamCount(4);

    // Update endpoints of default cluster `cluster_0` to 4 different fake upstreams.
    config_helper_.addConfigModifier([](envoy::config::bootstrap::v3::Bootstrap& bootstrap) {
      auto* cluster_0 = bootstrap.mutable_static_resources()->mutable_clusters()->Mutable(0);
      ASSERT(cluster_0->name() == "cluster_0");
      auto* endpoint = cluster_0->mutable_load_assignment()->mutable_endpoints()->Mutable(0);

      const std::string EndpointsYaml = R"EOF(
        lb_endpoints:
        - endpoint:
            address:
              socket_address:
                address: 127.0.0.1
                port_value: 0
        - endpoint:
            address:
              socket_address:
                address: 127.0.0.1
                port_value: 0
        - endpoint:
            address:
              socket_address:
                address: 127.0.0.1
                port_value: 0
        - endpoint:
            address:
              socket_address:
                address: 127.0.0.1
                port_value: 0
      )EOF";

      envoy::config::endpoint::v3::LocalityLbEndpoints new_lb_endpints;
      TestUtility::loadFromYaml(EndpointsYaml, new_lb_endpints);
      *endpoint = new_lb_endpints;
    });
  }

  // Initialize route filter and per route config.
  void initializeFilterAndRoute(const std::string& filter_yaml,
                                const std::string& per_route_config_yaml) {
    config_helper_.prependFilter(filter_yaml);

    // Create virtual host with domain `stateful.session.com` and default route to `cluster_0`
    auto virtual_host = config_helper_.createVirtualHost("stateful.session.com");

    // Update per route config of default route.
    if (!per_route_config_yaml.empty()) {
      auto* route = virtual_host.mutable_routes(0);
      ProtobufWkt::Any per_route_config;
      TestUtility::loadFromYaml(per_route_config_yaml, per_route_config);

      route->mutable_typed_per_filter_config()->insert(
          {"envoy.filters.http.stateful_session", per_route_config});
    }
    config_helper_.addVirtualHost(virtual_host);

    initialize();
  }
};

static const std::string STATEFUL_SESSION_FILTER =
    R"EOF(
name: envoy.filters.http.stateful_session
typed_config:
  "@type": type.googleapis.com/envoy.extensions.filters.http.stateful_session.v3.StatefulSession
  session_state:
    name: envoy.http.stateful_session.cookie
    typed_config:
      "@type": type.googleapis.com/envoy.extensions.http.stateful_session.cookie.v3.CookieBasedSessionState
      cookie:
        name: global-session-cookie
        path: /path
        ttl: 120s
)EOF";

static const std::string DISABLE_STATEFUL_SESSION =
    R"EOF(
"@type": type.googleapis.com/envoy.extensions.filters.http.stateful_session.v3.StatefulSessionPerRoute
disabled: true
)EOF";

static const std::string OVERRIDE_STATEFUL_SESSION =
    R"EOF(
"@type": type.googleapis.com/envoy.extensions.filters.http.stateful_session.v3.StatefulSessionPerRoute
stateful_session:
  session_state:
    name: envoy.http.stateful_session.cookie
    typed_config:
      "@type": type.googleapis.com/envoy.extensions.http.stateful_session.cookie.v3.CookieBasedSessionState
      cookie:
        name: route-session-cookie
        path: /path
        ttl: 120s
)EOF";

TEST_F(StatefulSessionIntegrationTest, NormalStatefulSession) {
  initializeFilterAndRoute(STATEFUL_SESSION_FILTER, "");

  codec_client_ = makeHttpConnection(lookupPort("http"));

  Http::TestRequestHeaderMapImpl request_headers{{":method", "GET"},
                                                 {":path", "/test"},
                                                 {":scheme", "http"},
                                                 {":authority", "stateful.session.com"}};

  auto response = codec_client_->makeRequestWithBody(request_headers, 0);

  auto upstream_index = waitForNextUpstreamRequest({0, 1, 2, 3});
  ASSERT(upstream_index.has_value());

  envoy::config::endpoint::v3::LbEndpoint endpoint;
  setUpstreamAddress(upstream_index.value(), endpoint);
  const std::string address_string =
      fmt::format("127.0.0.1:{}", endpoint.endpoint().address().socket_address().port_value());
  const std::string encoded_address =
      Envoy::Base64::encode(address_string.data(), address_string.size());

  upstream_request_->encodeHeaders(default_response_headers_, true);

  ASSERT_TRUE(response->waitForEndStream());

  EXPECT_TRUE(upstream_request_->complete());
  EXPECT_TRUE(response->complete());

  // The selected upstream server address would be selected to the response headers.
  EXPECT_EQ(
      Envoy::Http::Utility::makeSetCookieValue("global-session-cookie", encoded_address, "/path",
                                               std::chrono::seconds(120), true),
      response->headers().get(Http::LowerCaseString("set-cookie"))[0]->value().getStringView());

  cleanupUpstreamAndDownstream();
}

TEST_F(StatefulSessionIntegrationTest, DownstreamRequestWithStatefulSessionCookie) {
  initializeFilterAndRoute(STATEFUL_SESSION_FILTER, "");

  {

    envoy::config::endpoint::v3::LbEndpoint endpoint;
    setUpstreamAddress(1, endpoint);
    const std::string address_string =
        fmt::format("127.0.0.1:{}", endpoint.endpoint().address().socket_address().port_value());
    const std::string encoded_address =
        Envoy::Base64::encode(address_string.data(), address_string.size());

    codec_client_ = makeHttpConnection(lookupPort("http"));
    Http::TestRequestHeaderMapImpl request_headers{
        {":method", "GET"},
        {":path", "/test"},
        {":scheme", "http"},
        {":authority", "stateful.session.com"},
        {"cookie", fmt::format("global-session-cookie=\"{}\"", encoded_address)}};

    auto response = codec_client_->makeRequestWithBody(request_headers, 0);

    // The upstream with index 1 should be selected.
    auto upstream_index = waitForNextUpstreamRequest({0, 1, 2, 3});
    EXPECT_EQ(upstream_index.value(), 1);

    upstream_request_->encodeHeaders(default_response_headers_, true);

    ASSERT_TRUE(response->waitForEndStream());

    EXPECT_TRUE(upstream_request_->complete());
    EXPECT_TRUE(response->complete());

    // No response header to be added.
    EXPECT_TRUE(response->headers().get(Http::LowerCaseString("set-cookie")).empty());

    cleanupUpstreamAndDownstream();
  }

  {
    envoy::config::endpoint::v3::LbEndpoint endpoint;
    setUpstreamAddress(2, endpoint);
    const std::string address_string =
        fmt::format("127.0.0.1:{}", endpoint.endpoint().address().socket_address().port_value());
    const std::string encoded_address =
        Envoy::Base64::encode(address_string.data(), address_string.size());

    codec_client_ = makeHttpConnection(lookupPort("http"));
    Http::TestRequestHeaderMapImpl request_headers{
        {":method", "GET"},
        {":path", "/test"},
        {":scheme", "http"},
        {":authority", "stateful.session.com"},
        {"cookie", fmt::format("global-session-cookie=\"{}\"", encoded_address)}};

    auto response = codec_client_->makeRequestWithBody(request_headers, 0);

    // The upstream with index 2 should be selected.
    auto upstream_index = waitForNextUpstreamRequest({0, 1, 2, 3});
    EXPECT_EQ(upstream_index.value(), 2);

    upstream_request_->encodeHeaders(default_response_headers_, true);

    ASSERT_TRUE(response->waitForEndStream());

    EXPECT_TRUE(upstream_request_->complete());
    EXPECT_TRUE(response->complete());

    // No response header to be added.
    EXPECT_TRUE(response->headers().get(Http::LowerCaseString("set-cookie")).empty());

    cleanupUpstreamAndDownstream();
  }

  // Test the case that stateful session cookie with unknown server address.
  {
    codec_client_ = makeHttpConnection(lookupPort("http"));
    Http::TestRequestHeaderMapImpl request_headers{
        {":method", "GET"},
        {":path", "/test"},
        {":scheme", "http"},
        {":authority", "stateful.session.com"},
        {"cookie", fmt::format("global-session-cookie=\"{}\"",
                               Envoy::Base64::encode("127.0.0.7:50000", 15))}};

    auto response = codec_client_->makeRequestWithBody(request_headers, 0);

    auto upstream_index = waitForNextUpstreamRequest({0, 1, 2, 3});
    ASSERT(upstream_index.has_value());

    envoy::config::endpoint::v3::LbEndpoint endpoint;
    setUpstreamAddress(upstream_index.value(), endpoint);
    const std::string address_string =
        fmt::format("127.0.0.1:{}", endpoint.endpoint().address().socket_address().port_value());
    const std::string encoded_address =
        Envoy::Base64::encode(address_string.data(), address_string.size());

    upstream_request_->encodeHeaders(default_response_headers_, true);

    ASSERT_TRUE(response->waitForEndStream());

    EXPECT_TRUE(upstream_request_->complete());
    EXPECT_TRUE(response->complete());

    // The selected upstream server address would be selected to the response headers.
    EXPECT_EQ(
        Envoy::Http::Utility::makeSetCookieValue("global-session-cookie", encoded_address, "/path",
                                                 std::chrono::seconds(120), true),
        response->headers().get(Http::LowerCaseString("set-cookie"))[0]->value().getStringView());

    cleanupUpstreamAndDownstream();
  }
}

TEST_F(StatefulSessionIntegrationTest, StatefulSessionDisabledByRoute) {
  initializeFilterAndRoute(STATEFUL_SESSION_FILTER, DISABLE_STATEFUL_SESSION);

  uint64_t first_index = 0;
  uint64_t second_index = 0;

  envoy::config::endpoint::v3::LbEndpoint endpoint;
  setUpstreamAddress(1, endpoint);
  const std::string address_string =
      fmt::format("127.0.0.1:{}", endpoint.endpoint().address().socket_address().port_value());
  const std::string encoded_address =
      Envoy::Base64::encode(address_string.data(), address_string.size());

  {
    codec_client_ = makeHttpConnection(lookupPort("http"));
    Http::TestRequestHeaderMapImpl request_headers{
        {":method", "GET"},
        {":path", "/test"},
        {":scheme", "http"},
        {":authority", "stateful.session.com"},
        {"cookie", fmt::format("global-session-cookie=\"{}\"", encoded_address)}};

    auto response = codec_client_->makeRequestWithBody(request_headers, 0);

    auto upstream_index = waitForNextUpstreamRequest({0, 1, 2, 3});
    ASSERT(upstream_index.has_value());
    first_index = upstream_index.value();

    upstream_request_->encodeHeaders(default_response_headers_, true);

    ASSERT_TRUE(response->waitForEndStream());

    EXPECT_TRUE(upstream_request_->complete());
    EXPECT_TRUE(response->complete());

    // No response header to be added.
    EXPECT_TRUE(response->headers().get(Http::LowerCaseString("set-cookie")).empty());

    cleanupUpstreamAndDownstream();
  }

  {
    codec_client_ = makeHttpConnection(lookupPort("http"));
    Http::TestRequestHeaderMapImpl request_headers{
        {":method", "GET"},
        {":path", "/test"},
        {":scheme", "http"},
        {":authority", "stateful.session.com"},
        {"cookie", fmt::format("global-session-cookie=\"{}\"", encoded_address)}};

    auto response = codec_client_->makeRequestWithBody(request_headers, 0);

    auto upstream_index = waitForNextUpstreamRequest({0, 1, 2, 3});
    ASSERT(upstream_index.has_value());
    second_index = upstream_index.value();

    upstream_request_->encodeHeaders(default_response_headers_, true);

    ASSERT_TRUE(response->waitForEndStream());

    EXPECT_TRUE(upstream_request_->complete());
    EXPECT_TRUE(response->complete());

    // No response header to be added.
    EXPECT_TRUE(response->headers().get(Http::LowerCaseString("set-cookie")).empty());

    cleanupUpstreamAndDownstream();
  }

  // Choose different upstream servers by default.
  EXPECT_NE(first_index, second_index);
}

TEST_F(StatefulSessionIntegrationTest, StatefulSessionOverriddenByRoute) {
  initializeFilterAndRoute(STATEFUL_SESSION_FILTER, OVERRIDE_STATEFUL_SESSION);

  {
    envoy::config::endpoint::v3::LbEndpoint endpoint;
    setUpstreamAddress(1, endpoint);
    const std::string address_string =
        fmt::format("127.0.0.1:{}", endpoint.endpoint().address().socket_address().port_value());
    const std::string encoded_address =
        Envoy::Base64::encode(address_string.data(), address_string.size());

    codec_client_ = makeHttpConnection(lookupPort("http"));
    Http::TestRequestHeaderMapImpl request_headers{
        {":method", "GET"},
        {":path", "/test"},
        {":scheme", "http"},
        {":authority", "stateful.session.com"},
        {"cookie", fmt::format("global-session-cookie=\"{}\"", encoded_address)}};

    auto response = codec_client_->makeRequestWithBody(request_headers, 0);

    auto upstream_index = waitForNextUpstreamRequest({0, 1, 2, 3});
    ASSERT(upstream_index.has_value());

    envoy::config::endpoint::v3::LbEndpoint route_endpoint;
    setUpstreamAddress(upstream_index.value(), route_endpoint);
    const std::string route_address_string = fmt::format(
        "127.0.0.1:{}", route_endpoint.endpoint().address().socket_address().port_value());
    const std::string route_encoded_address =
        Envoy::Base64::encode(route_address_string.data(), route_address_string.size());

    upstream_request_->encodeHeaders(default_response_headers_, true);

    ASSERT_TRUE(response->waitForEndStream());

    EXPECT_TRUE(upstream_request_->complete());
    EXPECT_TRUE(response->complete());

    EXPECT_EQ(
        Envoy::Http::Utility::makeSetCookieValue("route-session-cookie", route_encoded_address,
                                                 "/path", std::chrono::seconds(120), true),
        response->headers().get(Http::LowerCaseString("set-cookie"))[0]->value().getStringView());

    cleanupUpstreamAndDownstream();
  }

  {
    envoy::config::endpoint::v3::LbEndpoint endpoint;
    setUpstreamAddress(2, endpoint);
    const std::string address_string =
        fmt::format("127.0.0.1:{}", endpoint.endpoint().address().socket_address().port_value());
    const std::string encoded_address =
        Envoy::Base64::encode(address_string.data(), address_string.size());

    codec_client_ = makeHttpConnection(lookupPort("http"));
    Http::TestRequestHeaderMapImpl request_headers{
        {":method", "GET"},
        {":path", "/test"},
        {":scheme", "http"},
        {":authority", "stateful.session.com"},
        {"cookie", fmt::format("route-session-cookie=\"{}\"", encoded_address)}};

    auto response = codec_client_->makeRequestWithBody(request_headers, 0);

    // Stateful session is overridden and the upstream with index 2 should be selected..
    auto upstream_index = waitForNextUpstreamRequest({0, 1, 2, 3});
    EXPECT_EQ(upstream_index.value(), 2);

    upstream_request_->encodeHeaders(default_response_headers_, true);

    ASSERT_TRUE(response->waitForEndStream());

    EXPECT_TRUE(upstream_request_->complete());
    EXPECT_TRUE(response->complete());

    // No response header to be added.
    EXPECT_TRUE(response->headers().get(Http::LowerCaseString("set-cookie")).empty());

    cleanupUpstreamAndDownstream();
  }
}

} // namespace
} // namespace StatefulSession
} // namespace HttpFilters
} // namespace Extensions
} // namespace Envoy
<|endoftext|>


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

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_dbaccess.hxx"

#ifndef DBA_COREDATAACESS_COMPONENTDEFINITION_HXX
#include "ComponentDefinition.hxx"
#endif
#ifndef _DBASHARED_APITOOLS_HXX_
#include "apitools.hxx"
#endif
#ifndef DBACCESS_SHARED_DBASTRINGS_HRC
#include "dbastrings.hrc"
#endif

#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _COMPHELPER_SEQUENCE_HXX_
#include <comphelper/sequence.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_
#include <com/sun/star/beans/PropertyAttribute.hpp>
#endif
#ifndef _COMPHELPER_PROPERTY_HXX_
#include <comphelper/property.hxx>
#endif
#ifndef _DBACORE_DEFINITIONCOLUMN_HXX_
#include "definitioncolumn.hxx"
#endif

using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::lang;

using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::container;
using namespace ::osl;
using namespace ::comphelper;
using namespace ::cppu;

extern "C" void SAL_CALL createRegistryInfo_OComponentDefinition()
{
    static ::dbaccess::OMultiInstanceAutoRegistration< ::dbaccess::OComponentDefinition > aAutoRegistration;
}

//........................................................................
namespace dbaccess
{
//........................................................................
DBG_NAME(OComponentDefinition_Impl)
OComponentDefinition_Impl::OComponentDefinition_Impl()
{
    DBG_CTOR(OComponentDefinition_Impl,NULL);
}
// -----------------------------------------------------------------------------
OComponentDefinition_Impl::~OComponentDefinition_Impl()
{
    DBG_DTOR(OComponentDefinition_Impl,NULL);
}
//==========================================================================
//= OComponentDefinition
//==========================================================================
//--------------------------------------------------------------------------
DBG_NAME(OComponentDefinition)
//--------------------------------------------------------------------------
void OComponentDefinition::registerProperties()
{
    OComponentDefinition_Impl& rDefinition( getDefinition() );
    ODataSettings::registerPropertiesFor( &rDefinition );

    registerProperty(PROPERTY_NAME, PROPERTY_ID_NAME, PropertyAttribute::BOUND | PropertyAttribute::READONLY|PropertyAttribute::CONSTRAINED,
                    &rDefinition.m_aProps.aTitle, ::getCppuType(&rDefinition.m_aProps.aTitle));

    if ( m_bTable )
    {
        registerProperty(PROPERTY_SCHEMANAME, PROPERTY_ID_SCHEMANAME, PropertyAttribute::BOUND,
                        &rDefinition.m_sSchemaName, ::getCppuType(&rDefinition.m_sSchemaName));

        registerProperty(PROPERTY_CATALOGNAME, PROPERTY_ID_CATALOGNAME, PropertyAttribute::BOUND,
                        &rDefinition.m_sCatalogName, ::getCppuType(&rDefinition.m_sCatalogName));
    }
}

//--------------------------------------------------------------------------
OComponentDefinition::OComponentDefinition(const Reference< XMultiServiceFactory >& _xORB
                                           ,const Reference< XInterface >&  _xParentContainer
                                           ,const TContentPtr& _pImpl
                                           ,sal_Bool _bTable)
    :OContentHelper(_xORB,_xParentContainer,_pImpl)
    ,ODataSettings(m_aBHelper,!_bTable)
    ,m_bTable(_bTable)
{
    DBG_CTOR(OComponentDefinition, NULL);
    registerProperties();
}
//--------------------------------------------------------------------------
OComponentDefinition::~OComponentDefinition()
{
    DBG_DTOR(OComponentDefinition, NULL);
}

//--------------------------------------------------------------------------
OComponentDefinition::OComponentDefinition( const Reference< XInterface >& _rxContainer
                                       ,const ::rtl::OUString& _rElementName
                                       ,const Reference< XMultiServiceFactory >& _xORB
                                       ,const TContentPtr& _pImpl
                                       ,sal_Bool _bTable)
    :OContentHelper(_xORB,_rxContainer,_pImpl)
    ,ODataSettings(m_aBHelper,!_bTable)
    ,m_bTable(_bTable)
{
    DBG_CTOR(OComponentDefinition, NULL);
    registerProperties();

    m_pImpl->m_aProps.aTitle = _rElementName;
    DBG_ASSERT(m_pImpl->m_aProps.aTitle.getLength() != 0, "OComponentDefinition::OComponentDefinition : invalid name !");
}

//--------------------------------------------------------------------------
IMPLEMENT_IMPLEMENTATION_ID(OComponentDefinition);
IMPLEMENT_GETTYPES3(OComponentDefinition,ODataSettings,OContentHelper,OComponentDefinition_BASE);
IMPLEMENT_FORWARD_XINTERFACE3( OComponentDefinition,OContentHelper,ODataSettings,OComponentDefinition_BASE)
//--------------------------------------------------------------------------
::rtl::OUString OComponentDefinition::getImplementationName_Static(  ) throw(RuntimeException)
{
    return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.comp.dba.OComponentDefinition"));
}

//--------------------------------------------------------------------------
::rtl::OUString SAL_CALL OComponentDefinition::getImplementationName(  ) throw(RuntimeException)
{
    return getImplementationName_Static();
}

//--------------------------------------------------------------------------
Sequence< ::rtl::OUString > OComponentDefinition::getSupportedServiceNames_Static(  ) throw(RuntimeException)
{
    Sequence< ::rtl::OUString > aServices(2);
    aServices.getArray()[0] = SERVICE_SDB_TABLEDEFINITION;
    aServices.getArray()[1] = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.ucb.Content"));

    return aServices;
}

//--------------------------------------------------------------------------
Sequence< ::rtl::OUString > SAL_CALL OComponentDefinition::getSupportedServiceNames(  ) throw(RuntimeException)
{
    return getSupportedServiceNames_Static();
}
//------------------------------------------------------------------------------
Reference< XInterface > OComponentDefinition::Create(const Reference< XMultiServiceFactory >& _rxFactory)
{
    return *(new OComponentDefinition(_rxFactory,NULL,TContentPtr(new OComponentDefinition_Impl)));
}
// -----------------------------------------------------------------------------
void SAL_CALL OComponentDefinition::disposing()
{
    OContentHelper::disposing();
    if ( m_pColumns.get() )
        m_pColumns->disposing();
}
// -----------------------------------------------------------------------------
IPropertyArrayHelper& OComponentDefinition::getInfoHelper()
{
    return *getArrayHelper();
}
//--------------------------------------------------------------------------
IPropertyArrayHelper* OComponentDefinition::createArrayHelper( ) const
{
    Sequence< Property > aProps;
    describeProperties(aProps);
    return new OPropertyArrayHelper(aProps);
}
//--------------------------------------------------------------------------
Reference< XPropertySetInfo > SAL_CALL OComponentDefinition::getPropertySetInfo(  ) throw(RuntimeException)
{
    Reference<XPropertySetInfo> xInfo( createPropertySetInfo( getInfoHelper() ) );
    return xInfo;
}
// -----------------------------------------------------------------------------
Reference< XNameAccess> OComponentDefinition::getColumns() throw (RuntimeException)
{
    ::osl::MutexGuard aGuard(m_aMutex);
    ::connectivity::checkDisposed(OContentHelper::rBHelper.bDisposed);

    if ( !m_pColumns.get() )
    {
        ::std::vector< ::rtl::OUString> aNames;

        const OComponentDefinition_Impl& rDefinition( getDefinition() );
        aNames.reserve( rDefinition.size() );

        OComponentDefinition_Impl::const_iterator aIter = rDefinition.begin();
        OComponentDefinition_Impl::const_iterator aEnd = rDefinition.end();
        for ( ; aIter != aEnd; ++aIter )
            aNames.push_back( aIter->first );

        m_pColumns.reset( new OColumns( *this, m_aMutex, sal_True, aNames, this, NULL, sal_True, sal_False, sal_False ) );
        m_pColumns->setParent( *this );
    }
    return m_pColumns.get();
}
// -----------------------------------------------------------------------------
OColumn* OComponentDefinition::createColumn(const ::rtl::OUString& _rName) const
{
    const OComponentDefinition_Impl& rDefinition( getDefinition() );
    OComponentDefinition_Impl::const_iterator aFind = rDefinition.find( _rName );
    if ( aFind != rDefinition.end() )
        return new OTableColumnWrapper( aFind->second, aFind->second, sal_True );
    return new OTableColumn( _rName );
}
// -----------------------------------------------------------------------------
Reference< ::com::sun::star::beans::XPropertySet > OComponentDefinition::createColumnDescriptor()
{
    return new OTableColumnDescriptor();
}
// -----------------------------------------------------------------------------
void OComponentDefinition::setFastPropertyValue_NoBroadcast(sal_Int32 nHandle,const Any& rValue) throw (Exception)
{
    ODataSettings::setFastPropertyValue_NoBroadcast(nHandle,rValue);
    notifyDataSourceModified();
}
// -----------------------------------------------------------------------------
void OComponentDefinition::columnDropped(const ::rtl::OUString& _sName)
{
    getDefinition().erase( _sName );
    notifyDataSourceModified();
}
// -----------------------------------------------------------------------------
void OComponentDefinition::columnAppended( const Reference< XPropertySet >& _rxSourceDescriptor )
{
    ::rtl::OUString sName;
    _rxSourceDescriptor->getPropertyValue( PROPERTY_NAME ) >>= sName;

    Reference<XPropertySet> xColDesc = new OTableColumnDescriptor();
    ::comphelper::copyProperties( _rxSourceDescriptor, xColDesc );
    getDefinition().insert( sName, xColDesc );

    // formerly, here was a setParent at the xColDesc. The parent used was an adapter (ChildHelper_Impl)
    // which held another XChild weak, and forwarded all getParent requests to this other XChild.
    // m_pColumns was used for this. This was nonsense, since m_pColumns dies when our instance dies,
    // but xColDesc will live longer than this. So effectively, the setParent call was pretty useless.
    //
    // The intention for this parenting was that the column descriptor is able to find the data source,
    // by traveling up the parent hierachy until there's an XDataSource. This didn't work (which
    // for instance causes #i65023#). We need another way to properly ensure this.

    notifyDataSourceModified();
}

//........................................................................
}   // namespace dbaccess
//........................................................................

<commit_msg>INTEGRATION: CWS dba24a (1.12.56); FILE MERGED 2007/08/02 10:49:09 oj 1.12.56.1: #i65023# modify dswhen column width changed<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ComponentDefinition.cxx,v $
 *
 *  $Revision: 1.13 $
 *
 *  last change: $Author: hr $ $Date: 2007-09-26 14:39:27 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_dbaccess.hxx"

#ifndef DBA_COREDATAACESS_COMPONENTDEFINITION_HXX
#include "ComponentDefinition.hxx"
#endif
#ifndef _DBASHARED_APITOOLS_HXX_
#include "apitools.hxx"
#endif
#ifndef DBACCESS_SHARED_DBASTRINGS_HRC
#include "dbastrings.hrc"
#endif

#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _COMPHELPER_SEQUENCE_HXX_
#include <comphelper/sequence.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_
#include <com/sun/star/beans/PropertyAttribute.hpp>
#endif
#ifndef _COMPHELPER_PROPERTY_HXX_
#include <comphelper/property.hxx>
#endif
#ifndef _DBACORE_DEFINITIONCOLUMN_HXX_
#include "definitioncolumn.hxx"
#endif
#include <cppuhelper/implbase1.hxx>

using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::lang;

using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::container;
using namespace ::osl;
using namespace ::comphelper;
using namespace ::cppu;

extern "C" void SAL_CALL createRegistryInfo_OComponentDefinition()
{
    static ::dbaccess::OMultiInstanceAutoRegistration< ::dbaccess::OComponentDefinition > aAutoRegistration;
}

//........................................................................
namespace dbaccess
{
//........................................................................
/// helper class for column property change events which holds the OComponentDefinition weak
typedef ::cppu::WeakImplHelper1 < XPropertyChangeListener > TColumnPropertyListener_BASE;
class OColumnPropertyListener : public TColumnPropertyListener_BASE
{
    OComponentDefinition* m_pComponent;

    OColumnPropertyListener(const OColumnPropertyListener&);
    void operator =(const OColumnPropertyListener&);
protected:
    virtual ~OColumnPropertyListener(){}
public:
    OColumnPropertyListener(OComponentDefinition* _pComponent) : m_pComponent(_pComponent){}
    // XPropertyChangeListener
    virtual void SAL_CALL propertyChange( const PropertyChangeEvent& /*_rEvent*/ ) throw (RuntimeException)
    {
        m_pComponent->notifyDataSourceModified();
    }
    // XEventListener
    virtual void SAL_CALL disposing( const EventObject& /*_rSource*/ ) throw (RuntimeException)
    {
    }
};
DBG_NAME(OComponentDefinition_Impl)
OComponentDefinition_Impl::OComponentDefinition_Impl()
{
    DBG_CTOR(OComponentDefinition_Impl,NULL);
}
// -----------------------------------------------------------------------------
OComponentDefinition_Impl::~OComponentDefinition_Impl()
{
    DBG_DTOR(OComponentDefinition_Impl,NULL);
}
//==========================================================================
//= OComponentDefinition
//==========================================================================
//--------------------------------------------------------------------------
DBG_NAME(OComponentDefinition)
//--------------------------------------------------------------------------
void OComponentDefinition::registerProperties()
{
    m_xColumnPropertyListener = new OColumnPropertyListener(this);
    OComponentDefinition_Impl& rDefinition( getDefinition() );
    ODataSettings::registerPropertiesFor( &rDefinition );

    registerProperty(PROPERTY_NAME, PROPERTY_ID_NAME, PropertyAttribute::BOUND | PropertyAttribute::READONLY|PropertyAttribute::CONSTRAINED,
                    &rDefinition.m_aProps.aTitle, ::getCppuType(&rDefinition.m_aProps.aTitle));

    if ( m_bTable )
    {
        registerProperty(PROPERTY_SCHEMANAME, PROPERTY_ID_SCHEMANAME, PropertyAttribute::BOUND,
                        &rDefinition.m_sSchemaName, ::getCppuType(&rDefinition.m_sSchemaName));

        registerProperty(PROPERTY_CATALOGNAME, PROPERTY_ID_CATALOGNAME, PropertyAttribute::BOUND,
                        &rDefinition.m_sCatalogName, ::getCppuType(&rDefinition.m_sCatalogName));
    }
}

//--------------------------------------------------------------------------
OComponentDefinition::OComponentDefinition(const Reference< XMultiServiceFactory >& _xORB
                                           ,const Reference< XInterface >&  _xParentContainer
                                           ,const TContentPtr& _pImpl
                                           ,sal_Bool _bTable)
    :OContentHelper(_xORB,_xParentContainer,_pImpl)
    ,ODataSettings(m_aBHelper,!_bTable)
    ,m_bTable(_bTable)
{
    DBG_CTOR(OComponentDefinition, NULL);
    registerProperties();
}
//--------------------------------------------------------------------------
OComponentDefinition::~OComponentDefinition()
{
    DBG_DTOR(OComponentDefinition, NULL);
}

//--------------------------------------------------------------------------
OComponentDefinition::OComponentDefinition( const Reference< XInterface >& _rxContainer
                                       ,const ::rtl::OUString& _rElementName
                                       ,const Reference< XMultiServiceFactory >& _xORB
                                       ,const TContentPtr& _pImpl
                                       ,sal_Bool _bTable)
    :OContentHelper(_xORB,_rxContainer,_pImpl)
    ,ODataSettings(m_aBHelper,!_bTable)
    ,m_bTable(_bTable)
{
    DBG_CTOR(OComponentDefinition, NULL);
    registerProperties();

    m_pImpl->m_aProps.aTitle = _rElementName;
    DBG_ASSERT(m_pImpl->m_aProps.aTitle.getLength() != 0, "OComponentDefinition::OComponentDefinition : invalid name !");
}

//--------------------------------------------------------------------------
IMPLEMENT_IMPLEMENTATION_ID(OComponentDefinition);
IMPLEMENT_GETTYPES3(OComponentDefinition,ODataSettings,OContentHelper,OComponentDefinition_BASE);
IMPLEMENT_FORWARD_XINTERFACE3( OComponentDefinition,OContentHelper,ODataSettings,OComponentDefinition_BASE)
//--------------------------------------------------------------------------
::rtl::OUString OComponentDefinition::getImplementationName_Static(  ) throw(RuntimeException)
{
    return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.comp.dba.OComponentDefinition"));
}

//--------------------------------------------------------------------------
::rtl::OUString SAL_CALL OComponentDefinition::getImplementationName(  ) throw(RuntimeException)
{
    return getImplementationName_Static();
}

//--------------------------------------------------------------------------
Sequence< ::rtl::OUString > OComponentDefinition::getSupportedServiceNames_Static(  ) throw(RuntimeException)
{
    Sequence< ::rtl::OUString > aServices(2);
    aServices.getArray()[0] = SERVICE_SDB_TABLEDEFINITION;
    aServices.getArray()[1] = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.ucb.Content"));

    return aServices;
}

//--------------------------------------------------------------------------
Sequence< ::rtl::OUString > SAL_CALL OComponentDefinition::getSupportedServiceNames(  ) throw(RuntimeException)
{
    return getSupportedServiceNames_Static();
}
//------------------------------------------------------------------------------
Reference< XInterface > OComponentDefinition::Create(const Reference< XMultiServiceFactory >& _rxFactory)
{
    return *(new OComponentDefinition(_rxFactory,NULL,TContentPtr(new OComponentDefinition_Impl)));
}
// -----------------------------------------------------------------------------
void SAL_CALL OComponentDefinition::disposing()
{
    OContentHelper::disposing();
    m_xColumnPropertyListener.clear();
    if ( m_pColumns.get() )
        m_pColumns->disposing();
}
// -----------------------------------------------------------------------------
IPropertyArrayHelper& OComponentDefinition::getInfoHelper()
{
    return *getArrayHelper();
}
//--------------------------------------------------------------------------
IPropertyArrayHelper* OComponentDefinition::createArrayHelper( ) const
{
    Sequence< Property > aProps;
    describeProperties(aProps);
    return new OPropertyArrayHelper(aProps);
}
//--------------------------------------------------------------------------
Reference< XPropertySetInfo > SAL_CALL OComponentDefinition::getPropertySetInfo(  ) throw(RuntimeException)
{
    Reference<XPropertySetInfo> xInfo( createPropertySetInfo( getInfoHelper() ) );
    return xInfo;
}
// -----------------------------------------------------------------------------
Reference< XNameAccess> OComponentDefinition::getColumns() throw (RuntimeException)
{
    ::osl::MutexGuard aGuard(m_aMutex);
    ::connectivity::checkDisposed(OContentHelper::rBHelper.bDisposed);

    if ( !m_pColumns.get() )
    {
        ::std::vector< ::rtl::OUString> aNames;

        const OComponentDefinition_Impl& rDefinition( getDefinition() );
        aNames.reserve( rDefinition.size() );

        OComponentDefinition_Impl::const_iterator aIter = rDefinition.begin();
        OComponentDefinition_Impl::const_iterator aEnd = rDefinition.end();
        for ( ; aIter != aEnd; ++aIter )
            aNames.push_back( aIter->first );

        m_pColumns.reset( new OColumns( *this, m_aMutex, sal_True, aNames, this, NULL, sal_True, sal_False, sal_False ) );
        m_pColumns->setParent( *this );
    }
    return m_pColumns.get();
}
// -----------------------------------------------------------------------------
OColumn* OComponentDefinition::createColumn(const ::rtl::OUString& _rName) const
{
    const OComponentDefinition_Impl& rDefinition( getDefinition() );
    OComponentDefinition_Impl::const_iterator aFind = rDefinition.find( _rName );
    if ( aFind != rDefinition.end() )
    {
        aFind->second->addPropertyChangeListener(::rtl::OUString(),m_xColumnPropertyListener);
        return new OTableColumnWrapper( aFind->second, aFind->second, sal_True );
    }
    return new OTableColumn( _rName );
}
// -----------------------------------------------------------------------------
Reference< XPropertySet > OComponentDefinition::createColumnDescriptor()
{
    return new OTableColumnDescriptor();
}
// -----------------------------------------------------------------------------
void OComponentDefinition::setFastPropertyValue_NoBroadcast(sal_Int32 nHandle,const Any& rValue) throw (Exception)
{
    ODataSettings::setFastPropertyValue_NoBroadcast(nHandle,rValue);
    notifyDataSourceModified();
}
// -----------------------------------------------------------------------------
void OComponentDefinition::columnDropped(const ::rtl::OUString& _sName)
{
    getDefinition().erase( _sName );
    notifyDataSourceModified();
}
// -----------------------------------------------------------------------------
void OComponentDefinition::columnAppended( const Reference< XPropertySet >& _rxSourceDescriptor )
{
    ::rtl::OUString sName;
    _rxSourceDescriptor->getPropertyValue( PROPERTY_NAME ) >>= sName;

    Reference<XPropertySet> xColDesc = new OTableColumnDescriptor();
    ::comphelper::copyProperties( _rxSourceDescriptor, xColDesc );
    getDefinition().insert( sName, xColDesc );

    // formerly, here was a setParent at the xColDesc. The parent used was an adapter (ChildHelper_Impl)
    // which held another XChild weak, and forwarded all getParent requests to this other XChild.
    // m_pColumns was used for this. This was nonsense, since m_pColumns dies when our instance dies,
    // but xColDesc will live longer than this. So effectively, the setParent call was pretty useless.
    //
    // The intention for this parenting was that the column descriptor is able to find the data source,
    // by traveling up the parent hierachy until there's an XDataSource. This didn't work (which
    // for instance causes #i65023#). We need another way to properly ensure this.

    notifyDataSourceModified();
}

//........................................................................
}   // namespace dbaccess
//........................................................................

<|endoftext|>


<commit_before>#include <netinet/ip6.h>
#include <arpa/inet.h>
#include "PacketPayload.h"
#include "PcapDumper.h"
#include "TransportLayerProcessorFactory.h"
#include "IPv6Processor.h"

void IPv6Processor::process(const u_char *header, const struct pcap_pkthdr *pkthdr, const u_char *packet,
                            const vector<NetData> &tcpNetData, const vector<NetData> &udpNetData, const vector<NetData> &tcp6NetData,
                            const vector<NetData> &udp6NetData) {

    const struct ip6_hdr* ip6Header = reinterpret_cast<const struct ip6_hdr*>(header);

    char srcIp6Buffer[INET6_ADDRSTRLEN];
    char dstIp6Buffer[INET6_ADDRSTRLEN];

    string srcIp6 = inet_ntop(AF_INET6, &ip6Header->ip6_src, srcIp6Buffer, INET6_ADDRSTRLEN);
    string dstIp6 = inet_ntop(AF_INET6, &ip6Header->ip6_dst, dstIp6Buffer, INET6_ADDRSTRLEN);

    auto protocol = ip6Header->ip6_ctlun.ip6_un1.ip6_un1_nxt;
    auto processor = TransportLayerProcessorFactory().getProcessor(protocol);
    if (processor != nullptr) {
        auto srcPort = processor->getSourcePort(header + sizeof(struct ip6_hdr));
        auto dstPort = processor->getDestinationPort(header + sizeof(struct ip6_hdr));

        vector<NetData> ip6NetDataTemp;

        if (protocol == IPPROTO_TCP) {
            ip6NetDataTemp = move(tcp6NetData);
        } else if (protocol == IPPROTO_UDP) {
            ip6NetDataTemp = move(udp6NetData);
        }

        for (auto data: ip6NetDataTemp) {
            struct in6_addr localIp6Addr;

            char localIp6Buffer[INET6_ADDRSTRLEN];

            sscanf(data.localIp.c_str(), "%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx",
                   &localIp6Addr.s6_addr[3], &localIp6Addr.s6_addr[2], &localIp6Addr.s6_addr[1], &localIp6Addr.s6_addr[0],
                   &localIp6Addr.s6_addr[7], &localIp6Addr.s6_addr[6], &localIp6Addr.s6_addr[5], &localIp6Addr.s6_addr[4],
                   &localIp6Addr.s6_addr[11], &localIp6Addr.s6_addr[10], &localIp6Addr.s6_addr[9], &localIp6Addr.s6_addr[8],
                   &localIp6Addr.s6_addr[15], &localIp6Addr.s6_addr[14], &localIp6Addr.s6_addr[13], &localIp6Addr.s6_addr[12]);

            string localIp6 = inet_ntop(AF_INET6, &localIp6Addr, localIp6Buffer, INET6_ADDRSTRLEN);
            uint32_t localPort = static_cast<uint32_t >(stoul(data.localPort, nullptr, 16));

            if (srcIp6 == localIp6 && srcPort == localPort) {
                PacketPayload::getInstance().addUploadedBytes(pkthdr->caplen);
                PcapDumper::getInstance().writePcapToFile(pkthdr, packet);
                break;
            }

            if (dstIp6 == localIp6 && dstPort == localPort) {
                PacketPayload::getInstance().addDownloadedBytes(pkthdr->caplen);
                PcapDumper::getInstance().writePcapToFile(pkthdr, packet);
                break;
            }
        }
    }
}
<commit_msg>Include ip header to ipv6 processor<commit_after>#include <netinet/ip.h>
#include <netinet/ip6.h>
#include <arpa/inet.h>
#include "PacketPayload.h"
#include "PcapDumper.h"
#include "TransportLayerProcessorFactory.h"
#include "IPv6Processor.h"

void IPv6Processor::process(const u_char *header, const struct pcap_pkthdr *pkthdr, const u_char *packet,
                            const vector<NetData> &tcpNetData, const vector<NetData> &udpNetData, const vector<NetData> &tcp6NetData,
                            const vector<NetData> &udp6NetData) {

    const struct ip6_hdr* ip6Header = reinterpret_cast<const struct ip6_hdr*>(header);

    char srcIp6Buffer[INET6_ADDRSTRLEN];
    char dstIp6Buffer[INET6_ADDRSTRLEN];

    string srcIp6 = inet_ntop(AF_INET6, &ip6Header->ip6_src, srcIp6Buffer, INET6_ADDRSTRLEN);
    string dstIp6 = inet_ntop(AF_INET6, &ip6Header->ip6_dst, dstIp6Buffer, INET6_ADDRSTRLEN);

    auto protocol = ip6Header->ip6_ctlun.ip6_un1.ip6_un1_nxt;
    auto processor = TransportLayerProcessorFactory().getProcessor(protocol);
    if (processor != nullptr) {
        auto srcPort = processor->getSourcePort(header + sizeof(struct ip6_hdr));
        auto dstPort = processor->getDestinationPort(header + sizeof(struct ip6_hdr));

        vector<NetData> ip6NetDataTemp;

        if (protocol == IPPROTO_TCP) {
            ip6NetDataTemp = move(tcp6NetData);
        } else if (protocol == IPPROTO_UDP) {
            ip6NetDataTemp = move(udp6NetData);
        }

        for (auto data: ip6NetDataTemp) {
            struct in6_addr localIp6Addr;

            char localIp6Buffer[INET6_ADDRSTRLEN];

            sscanf(data.localIp.c_str(), "%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx",
                   &localIp6Addr.s6_addr[3], &localIp6Addr.s6_addr[2], &localIp6Addr.s6_addr[1], &localIp6Addr.s6_addr[0],
                   &localIp6Addr.s6_addr[7], &localIp6Addr.s6_addr[6], &localIp6Addr.s6_addr[5], &localIp6Addr.s6_addr[4],
                   &localIp6Addr.s6_addr[11], &localIp6Addr.s6_addr[10], &localIp6Addr.s6_addr[9], &localIp6Addr.s6_addr[8],
                   &localIp6Addr.s6_addr[15], &localIp6Addr.s6_addr[14], &localIp6Addr.s6_addr[13], &localIp6Addr.s6_addr[12]);

            string localIp6 = inet_ntop(AF_INET6, &localIp6Addr, localIp6Buffer, INET6_ADDRSTRLEN);
            uint32_t localPort = static_cast<uint32_t >(stoul(data.localPort, nullptr, 16));

            if (srcIp6 == localIp6 && srcPort == localPort) {
                PacketPayload::getInstance().addUploadedBytes(pkthdr->caplen);
                PcapDumper::getInstance().writePcapToFile(pkthdr, packet);
                break;
            }

            if (dstIp6 == localIp6 && dstPort == localPort) {
                PacketPayload::getInstance().addDownloadedBytes(pkthdr->caplen);
                PcapDumper::getInstance().writePcapToFile(pkthdr, packet);
                break;
            }
        }
    }
}
<|endoftext|>


<commit_before>//http://www.spoj.com/problems/EDIST/
//longes common subsequence
<commit_msg>Adding<commit_after>//http://www.spoj.com/problems/EDIST/
//longes common subsequence
#include <stdio.h>
using namespace std;
int lcs(int a,int b){

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

	return 0;
}<|endoftext|>


<commit_before>#include "generateur/ParseCmdLine.hh"
#include <string>
using namespace std;

variables_map ParseCmdLine::parse(int argc_p, char** argv_p){
    options_description desc_l("Options autorisees");
    desc_l.add_options()
        ("help", "genere ce message")
        ("strategy,s", value<string>(), "Specifie la strategy de generation a adopter");

    variables_map result_l;
    store(parse_command_line(argc_p, argv_p, desc_l), result_l);
    notify(result_l);

    if ( result_l.count("help") ){
        cout << desc_l << endl;
    }

    return result_l;
}
<commit_msg>Ajout d'une gestion des erreurs autours de la lecture de la ligne de cmd<commit_after>#include "generateur/ParseCmdLine.hh"
#include <string>
using namespace std;

variables_map ParseCmdLine::parse(int argc_p, char** argv_p){
    variables_map result_l;
    options_description desc_l("Options autorisees");
    desc_l.add_options()
        ("help", "genere ce message")
        ("strategy,s", value<string>(), "Specifie la strategy de generation a adopter");

    try {
        store(parse_command_line(argc_p, argv_p, desc_l), result_l);
        notify(result_l);

        if ( result_l.count("help") ){
            cout << desc_l << endl;
        }
    }catch(exception& err_l) {
        cerr << "Erreur de lecture de la ligne de commande : " << err_l.what() << endl;
        cerr << desc_l << endl;
    }

    return result_l;
}
<|endoftext|>


<commit_before>#pragma once

#include <string>
#include <list>

typedef std::pair<std::string, std::string> keilo_instance;
typedef std::list<keilo_instance> keilo_record;

typedef struct {
	SOCKET sock;
	SOCKADDR_IN addr;
} client;<commit_msg>winsock<commit_after>#pragma once

#include <string>
#include <list>
#include <winsock2.h>

#pragma comment(lib, "ws2_32.lib")

typedef std::pair<std::string, std::string> keilo_instance;
typedef std::list<keilo_instance> keilo_record;

typedef struct {
	SOCKET sock;
	SOCKADDR_IN addr;
} client;<|endoftext|>


<commit_before>using namespace std;

string encrypt (string plaintext, string key)
{
  return "TODO";
}
<commit_msg>Removed unused namespace import.<commit_after>string encrypt (string plaintext, string key)
{
  return "TODO";
}
<|endoftext|>