<commit_before>/** Copyright (C) 2016, 2017 European Spallation Source ERIC */

#include <cinttypes>
#include <common/FBSerializer.h>
#include <common/Trace.h>
#include <common/DataSave.h>
#include <libs/include/gccintel.h>

#define TIMESIZE 4
#define PIXELSIZE 4

//#undef TRC_LEVEL
//#define TRC_LEVEL TRC_L_DEB

static_assert(FLATBUFFERS_LITTLEENDIAN,
              "Flatbuffers only tested on little endian systems");

FBSerializer::FBSerializer(size_t maxarraylength, Producer &prod)
    : builder(maxarraylength * 8 + 256), maxlen(maxarraylength),
      producer(prod) {

  auto sourceName = builder.CreateString("c_spec_data");
  std::uint64_t sequenceNr = 1; // Placeholder, must not be 0
  std::uint64_t pulseTime = 1;  // Placeholder, must not be 0
  auto timeoff = builder.CreateUninitializedVector(maxlen, TIMESIZE, &timeptr);
  auto pixeloff =
      builder.CreateUninitializedVector(maxlen, PIXELSIZE, &pixelptr);

  auto evMsgHeader = CreateEventMessage(builder, sourceName, sequenceNr,
                                        pulseTime, timeoff, pixeloff);
  FinishEventMessageBuffer(builder, evMsgHeader);

  //Use reinterpret_cast
  fbBufferPointer = reinterpret_cast<char*>(builder.GetBufferPointer());
  fbSize = builder.GetSize();
  assert(fbSize > 0);
  assert(fbBufferPointer != nullptr);

  eventMsg = const_cast<EventMessage *>(GetEventMessage(fbBufferPointer));
  timeLenPtr =
      reinterpret_cast<flatbuffers::uoffset_t *>(
          const_cast<std::uint8_t *>(eventMsg->time_of_flight()->Data())) -
      1;
  pixelLenPtr =
      reinterpret_cast<flatbuffers::uoffset_t *>(
          const_cast<std::uint8_t *>(eventMsg->detector_id()->Data())) -
      1;
}

FBSerializer::~FBSerializer() {}

int FBSerializer::serialize(uint64_t time, uint64_t seqno, size_t entries,
                            char **buffer) {
  if (entries > maxlen) {
    *buffer = 0;
    return 0;
  }
  eventMsg->mutate_pulse_time(time);
  eventMsg->mutate_message_id(seqno);
  *timeLenPtr = entries;
  *pixelLenPtr = entries;

  *buffer = fbBufferPointer;
  return fbSize;
}

int FBSerializer::produce() {
  int txlen = 0;
  if (events != 0) {
    // Debug
    // for (unsigned int i = 0; i < events; i++) {
    //   printf("(%d, %d) ", i, ((uint32_t *)pixelptr)[i]);
    // }
    // printf("\n");

    XTRACE(OUTPUT, DEB, "produce %zu events \n", events);
    char *txbuffer;
    txlen = serialize((uint64_t)0x01, seqno++, events, &txbuffer);
    assert(txlen > 0);
    XTRACE(OUTPUT, DEB, "Flatbuffer tx length %d\n", txlen);
    producer.produce(txbuffer, txlen);

#if 0
      DataSave eventfb("eventfb", txbuffer, txlen);
      sleep(3);
      exit(1);
#endif
    events = 0;
  }
  return txlen;
}

int FBSerializer::addevent(uint32_t time, uint32_t pixel) {
  XTRACE(OUTPUT, DEB, "Add event: %d %u\n", time, pixel);
  ((uint32_t *)timeptr)[events] = time;
  ((uint32_t *)pixelptr)[events] = pixel;
  events++;

  /** Produce when enough data has been accumulated */
  if (events >= maxlen) {
    return produce();
  }
  return 0;
}
<commit_msg>Removed useless comment.<commit_after>/** Copyright (C) 2016, 2017 European Spallation Source ERIC */

#include <cinttypes>
#include <common/FBSerializer.h>
#include <common/Trace.h>
#include <common/DataSave.h>
#include <libs/include/gccintel.h>

#define TIMESIZE 4
#define PIXELSIZE 4

//#undef TRC_LEVEL
//#define TRC_LEVEL TRC_L_DEB

static_assert(FLATBUFFERS_LITTLEENDIAN,
              "Flatbuffers only tested on little endian systems");

FBSerializer::FBSerializer(size_t maxarraylength, Producer &prod)
    : builder(maxarraylength * 8 + 256), maxlen(maxarraylength),
      producer(prod) {

  auto sourceName = builder.CreateString("c_spec_data");
  std::uint64_t sequenceNr = 1; // Placeholder, must not be 0
  std::uint64_t pulseTime = 1;  // Placeholder, must not be 0
  auto timeoff = builder.CreateUninitializedVector(maxlen, TIMESIZE, &timeptr);
  auto pixeloff =
      builder.CreateUninitializedVector(maxlen, PIXELSIZE, &pixelptr);

  auto evMsgHeader = CreateEventMessage(builder, sourceName, sequenceNr,
                                        pulseTime, timeoff, pixeloff);
  FinishEventMessageBuffer(builder, evMsgHeader);

  fbBufferPointer = reinterpret_cast<char*>(builder.GetBufferPointer());
  fbSize = builder.GetSize();
  assert(fbSize > 0);
  assert(fbBufferPointer != nullptr);

  eventMsg = const_cast<EventMessage *>(GetEventMessage(fbBufferPointer));
  timeLenPtr =
      reinterpret_cast<flatbuffers::uoffset_t *>(
          const_cast<std::uint8_t *>(eventMsg->time_of_flight()->Data())) -
      1;
  pixelLenPtr =
      reinterpret_cast<flatbuffers::uoffset_t *>(
          const_cast<std::uint8_t *>(eventMsg->detector_id()->Data())) -
      1;
}

FBSerializer::~FBSerializer() {}

int FBSerializer::serialize(uint64_t time, uint64_t seqno, size_t entries,
                            char **buffer) {
  if (entries > maxlen) {
    *buffer = 0;
    return 0;
  }
  eventMsg->mutate_pulse_time(time);
  eventMsg->mutate_message_id(seqno);
  *timeLenPtr = entries;
  *pixelLenPtr = entries;

  *buffer = fbBufferPointer;
  return fbSize;
}

int FBSerializer::produce() {
  int txlen = 0;
  if (events != 0) {
    // Debug
    // for (unsigned int i = 0; i < events; i++) {
    //   printf("(%d, %d) ", i, ((uint32_t *)pixelptr)[i]);
    // }
    // printf("\n");

    XTRACE(OUTPUT, DEB, "produce %zu events \n", events);
    char *txbuffer;
    txlen = serialize((uint64_t)0x01, seqno++, events, &txbuffer);
    assert(txlen > 0);
    XTRACE(OUTPUT, DEB, "Flatbuffer tx length %d\n", txlen);
    producer.produce(txbuffer, txlen);

#if 0
      DataSave eventfb("eventfb", txbuffer, txlen);
      sleep(3);
      exit(1);
#endif
    events = 0;
  }
  return txlen;
}

int FBSerializer::addevent(uint32_t time, uint32_t pixel) {
  XTRACE(OUTPUT, DEB, "Add event: %d %u\n", time, pixel);
  ((uint32_t *)timeptr)[events] = time;
  ((uint32_t *)pixelptr)[events] = pixel;
  events++;

  /** Produce when enough data has been accumulated */
  if (events >= maxlen) {
    return produce();
  }
  return 0;
}
<|endoftext|>


<commit_before>/*
 * ArcScript Scripts for Arcemu MMORPG Server
 * Copyright (C) 2008-2009 Arcemu Team
 * Copyright (C) 2007 Moon++ <http://www.moonplusplus.com/>
 *
 * 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 3 of the License, or
 * 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, see <http://www.gnu.org/licenses/>.
 */

#include "LUAEngine.h"

namespace lua_engine
{
	void bindItemMethods(luabridge::module &  m)
	{
#define BIND(name) .method(#name, &ItemInterface::name)
#define BINDE(name, functor) .method(name, functor)
		m	.class_<ItemInterface>("ItemInterface")
			.method( &ItemInterface::GetOwner, "GetOwner", "getOwner", "getowner", NULL)
			.method( &ItemInterface::IsBagSlot, "IsBagSlot", "isBagSlot", "isbagslot", NULL)
			.method( (Item *(ItemInterface::*)(int8,int16) )&ItemInterface::GetInventoryItem, "GetInventoryItem", "getInventoryItem", "getinventoryitem", NULL)
			.method (&ItemInterface::GetInventorySlotById, "GetInventorySlotByID", "getInventorySlotByID", "getinventoryslotbyid", NULL)
			.method( (Item*(ItemInterface::*)(uint32, int8, int16) )&ItemInterface::SafeAddItem, "SafeAddItem" "addItem", "additem", NULL)
			.method( &ItemInterface::SafeFullRemoveItemFromSlot, "RemoveItemFromSlot", "removeItemFromSlot", "removeitemfromslot", NULL)
			.method( &ItemInterface::AddItemToFreeSlot, "AddItemToFreeSlot", "addItemToFreeSlot", "additemtofreeslot", NULL)
			.method( &ItemInterface::AddItemToFreeBankSlot, "AddItemToFreeBankSlot", "addItemToFreeBankSlot", "additemtofreebankslot", NULL)
			.method( &ItemInterface::GetItemCount, "GetItemCount", "getItemCount", "getitemcount", NULL)
			.method( &ItemInterface::RemoveItemAmt, "RemoveItemAmnt", "removeItemAmount", "removeitemamount", NULL)
			.method( &ItemInterface::RemoveAllConjured, "removeAllConjured", "removeallconjured", NULL)
			.method( &ItemInterface::BuyItem, "BuyItem", "buyItem", "buyitem", NULL)
			.method( &ItemInterface::FindFreeBackPackSlot, "FindFreeBackPackSlot", "findFreeBackPackSlot", "findfreebackpackslot", NULL)
			.method( &ItemInterface::FindFreeBackPackSlotMax, "FindFreeBackPackSlotMax", "findFreeBackPackSlotMax", "findfreebackpackslotmax", NULL)
			//BIND(FindAmmoBag)
			.method( &ItemInterface::FindFreeKeyringSlot, "findFreeKeyringSlot", "FindFreeKeyRingSlot", "findfreekeyringslot", NULL)
			.method( &ItemInterface::IsEquipped, "isEquipped", "IsEquipped", "isequipped", NULL)
			.method( &ItemInterface::CanReceiveItem, "CanReceiveItem", "canReceiveItem", "canreceiveitem", NULL)
			.method( &ItemInterface::CanAffordItem, "CanAffordItem", "canAffordItem", "canafforditem", NULL);
#undef BIND
#undef BINDE
#define BIND(name) .method(#name, &Item::name)
#define BINDE(name, functor) .method(name, functor)
		m	.subclass<Item, Object>("Item")
			.method (&Item::GetProto, "GetProto", "getProto", "getproto", NULL)
			.method(&Item::GetOwner, "getOwner", "GetOwner", "getowner", NULL)
			.method(&Item::SetOwner, "SetOwner", "setOwner", "setowner", NULL)
			.method(&Item::SetStackCount, "SetStackCount", "setStackCount", "setstackcount", NULL)
			.method(&Item::GetStackCount, "getStackCount", "GetStackCount", "getstackcount", NULL)
			.method(&Item::ModStackCount, "ModStackCount", "modStackCount", "modstackcount", NULL)
			.method(&Item::GetDuration, "GetDuration", "getDuration", "getduration", NULL)
			.method(&Item::SetDuration, "SetDuration", "setDuration", "setduration", NULL)
			.method(&Item::GetCharges, "GetCharges", "getCharges", "getcharges", NULL)
			.method(&Item::SetCharges, "SetCharges", "setCharges", "setcharges", NULL)
			.method(&Item::ModCharges, "ModCharges", "modCharges", "modcharges", NULL)
			.method(&Item::SoulBind, "SoulBind", "soulBind", "soulbind", NULL)
			.method(&Item::IsSoulbound, "IsSoulbound", "IsSoulBound", "isSoulBound", "issoulbound", NULL)
			.method(&Item::AccountBind, "AccountBind", "accountBind", "accountbind", NULL)
			.method(&Item::IsAccountbound, "IsAccountbound", "IsAccountBound", "isAccountBound", "isaccountbound", NULL)
			.method(&Item::MakeConjured, "MakeConjured", "makeConjured", "makeconjured", NULL)
			.method(&Item::IsConjured, "IsConjured", "isConjured", "isconjured", NULL)
			.method(&Item::Lock, "Lock", "lock", NULL)
			.method(&Item::UnLock, "UnLock", "unlock", "Unlock", NULL)
			.method(&Item::Wrap, "Wrap", "wrap", NULL)
			.method(&Item::UnWrap, "UnWrap", "Unwrap", "unwrap", NULL)
			.method(&Item::ClearFlags, "ClearFlags", "clearFlags", "clearflags", NULL)

			.method( &Item::GetItemRandomPropertyId, "GetItemRandomPropertyID", "getItemRandomPropertyID", "getitemrandompropertyid", NULL)
			.method( &Item::GetItemRandomSuffixFactor, "GetItemRandomSuffixFactor", "getItemRandomSuffixFactor", "getitemrandomsuffixfactor", NULL)
			.method( &Item::SetItemRandomPropertyId, "SetItemRandomPropertyId", "setItemRandomPropertyId", "setitemrandompropertyid", NULL)
			.method( &Item::SetItemRandomSuffixFactor, "SetItemRandomSuffixFactor", "setItemRandomSuffixFactor", "setitemrandomsuffixfactor", NULL)
			.method( &Item::SetRandomSuffix, "SetRandomSuffix", "setRandomSuffix", "setrandomsuffix", NULL)
			.method( &Item::SetDurability, "SetDurability", "setDurability", "setdurability", NULL)
			.method( &Item::SetDurabilityMax, "SetDurabilityMax", "setDurabilityMax", "setdurabilitymax", NULL)
			.method( &Item::GetDurability, "GetDurability", "getDurability", "getdurability", NULL)
			.method( &Item::GetDurabilityMax, "GetDurabilityMax", "getDurabilityMax", "getdurabilitymax", NULL)
			.method( &Item::SetDurabilityToMax, "SetDurabilityToMax", "setDurabilityToMax", "setdurabilitytomax", NULL)
			.method( &Item::GetEnchantmentId, "GetEnchantmentID", "getEnchantmentID", "getenchantmentid", NULL)
			.method( &Item::SetEnchantmentId, "SetEnchantmentID", "setEnchantmentID", "setenchantmentid", NULL)
			.method( &Item::GetEnchantmentDuration, "GetEnchantmentDuration", "getEnchantmentDuration", "getenchantmentduration", NULL)
			.method( &Item::SetEnchantmentDuration, "SetEnchantmentDuration", "setEnchantmentDuration", "setenchantmentduration", NULL)
			.method( &Item::GetEnchantmentCharges, "GetEnchantmentCharges", "getEnchantmentCharges", "getenchantmentcharges", NULL)
			.method( &Item::SetEnchantmentCharges, "SetEnchantmentCharges", "setEnchantmentCharges", "setenchantmentcharges", NULL)

			.method( &Item::IsContainer, "IsContainer", "isContainer", "iscontainer", NULL)
			.method( &Item::GetChargesLeft, "GetChargesLeft", "getChargesLeft", "getchargesleft", NULL)

			.method( &Item::AddEnchantment, "AddEnchantment", "addEnchantment", "addenchantment", NULL)
			.method( &Item::RemoveEnchantment, "RemoveEnchantment", "removeEnchantment", "removeenchantment", NULL)
			.method( &Item::HasEnchantment, "HasEnchantment", "hasEnchantment", "hasenchantment", NULL)
			.method( &Item::HasEnchantmentOnSlot, "HasEnchantmentOnSlot", "hasEnchantmentOnSlot", "hasenchantmentonslot", NULL)
			.method( &Item::ModifyEnchantmentTime, "ModifyEnchantmentTime", "modifyEnchantmentTime", "modifyenchantmenttime", NULL)
			.method( &Item::RemoveAllEnchantments, "RemoveAllEnchantments", "removeAllEnchantments", "removeallenchantments", NULL)
			.method( &Item::IsAmmoBag, "IsAmmoBag", "isAmmoBag", "isammobag", NULL)
			.method( &Item::RemoveFromWorld, "RemoveFromWorld", "removeFromWorld", "removefromworld", NULL)
			.method( &Item::HasEnchantments, "HasEnchantments", "hasEnchantments", "hasenchantments", NULL)
			.method( &Item::SaveToDB, "SaveToDB", "saveToDB", "savetodb",  NULL);
#undef BIND
#undef BINDE

#define BIND(name) .property_ro(#name, &ItemPrototype::name)
		m	.class_<ItemPrototype>("ItemPrototype")
			BIND(ItemId)
			BIND(Name1)
			BIND(DisplayInfoID)
			BIND(Flags)
			BIND(Faction)
			BIND(BuyPrice)
			BIND(SellPrice)
			BIND(ItemLevel)
			BIND(RequiredLevel)
			BIND(RequiredSkill)
			BIND(RequiredFaction)
			BIND(RequiredFactionStanding)
			BIND(Unique)
			BIND(MaxCount)
			BIND(Delay)
			BIND(RandomPropId)
			BIND(RandomSuffixId)
			BIND(TotemCategory)
			BIND(QuestId)
			BIND(Description);
#undef BIND
	}
}<commit_msg>FIXED: SafeAddItem method name was mangled due to a typo.<commit_after>/*
 * ArcScript Scripts for Arcemu MMORPG Server
 * Copyright (C) 2008-2009 Arcemu Team
 * Copyright (C) 2007 Moon++ <http://www.moonplusplus.com/>
 *
 * 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 3 of the License, or
 * 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, see <http://www.gnu.org/licenses/>.
 */

#include "LUAEngine.h"

namespace lua_engine
{
	void bindItemMethods(luabridge::module &  m)
	{
#define BIND(name) .method(#name, &ItemInterface::name)
#define BINDE(name, functor) .method(name, functor)
		m	.class_<ItemInterface>("ItemInterface")
			.method( &ItemInterface::GetOwner, "GetOwner", "getOwner", "getowner", NULL)
			.method( &ItemInterface::IsBagSlot, "IsBagSlot", "isBagSlot", "isbagslot", NULL)
			.method( (Item *(ItemInterface::*)(int8,int16) )&ItemInterface::GetInventoryItem, "GetInventoryItem", "getInventoryItem", "getinventoryitem", NULL)
			.method (&ItemInterface::GetInventorySlotById, "GetInventorySlotByID", "getInventorySlotByID", "getinventoryslotbyid", NULL)
			.method( (Item*(ItemInterface::*)(uint32, int8, int16) )&ItemInterface::SafeAddItem, "SafeAddItem","addItem", "additem", NULL)
			.method( &ItemInterface::SafeFullRemoveItemFromSlot, "RemoveItemFromSlot", "removeItemFromSlot", "removeitemfromslot", NULL)
			.method( &ItemInterface::AddItemToFreeSlot, "AddItemToFreeSlot", "addItemToFreeSlot", "additemtofreeslot", NULL)
			.method( &ItemInterface::AddItemToFreeBankSlot, "AddItemToFreeBankSlot", "addItemToFreeBankSlot", "additemtofreebankslot", NULL)
			.method( &ItemInterface::GetItemCount, "GetItemCount", "getItemCount", "getitemcount", NULL)
			.method( &ItemInterface::RemoveItemAmt, "RemoveItemAmnt", "removeItemAmount", "removeitemamount", NULL)
			.method( &ItemInterface::RemoveAllConjured, "removeAllConjured", "removeallconjured", NULL)
			.method( &ItemInterface::BuyItem, "BuyItem", "buyItem", "buyitem", NULL)
			.method( &ItemInterface::FindFreeBackPackSlot, "FindFreeBackPackSlot", "findFreeBackPackSlot", "findfreebackpackslot", NULL)
			.method( &ItemInterface::FindFreeBackPackSlotMax, "FindFreeBackPackSlotMax", "findFreeBackPackSlotMax", "findfreebackpackslotmax", NULL)
			//BIND(FindAmmoBag)
			.method( &ItemInterface::FindFreeKeyringSlot, "findFreeKeyringSlot", "FindFreeKeyRingSlot", "findfreekeyringslot", NULL)
			.method( &ItemInterface::IsEquipped, "isEquipped", "IsEquipped", "isequipped", NULL)
			.method( &ItemInterface::CanReceiveItem, "CanReceiveItem", "canReceiveItem", "canreceiveitem", NULL)
			.method( &ItemInterface::CanAffordItem, "CanAffordItem", "canAffordItem", "canafforditem", NULL);
#undef BIND
#undef BINDE
#define BIND(name) .method(#name, &Item::name)
#define BINDE(name, functor) .method(name, functor)
		m	.subclass<Item, Object>("Item")
			.method (&Item::GetProto, "GetProto", "getProto", "getproto", NULL)
			.method(&Item::GetOwner, "getOwner", "GetOwner", "getowner", NULL)
			.method(&Item::SetOwner, "SetOwner", "setOwner", "setowner", NULL)
			.method(&Item::SetStackCount, "SetStackCount", "setStackCount", "setstackcount", NULL)
			.method(&Item::GetStackCount, "getStackCount", "GetStackCount", "getstackcount", NULL)
			.method(&Item::ModStackCount, "ModStackCount", "modStackCount", "modstackcount", NULL)
			.method(&Item::GetDuration, "GetDuration", "getDuration", "getduration", NULL)
			.method(&Item::SetDuration, "SetDuration", "setDuration", "setduration", NULL)
			.method(&Item::GetCharges, "GetCharges", "getCharges", "getcharges", NULL)
			.method(&Item::SetCharges, "SetCharges", "setCharges", "setcharges", NULL)
			.method(&Item::ModCharges, "ModCharges", "modCharges", "modcharges", NULL)
			.method(&Item::SoulBind, "SoulBind", "soulBind", "soulbind", NULL)
			.method(&Item::IsSoulbound, "IsSoulbound", "IsSoulBound", "isSoulBound", "issoulbound", NULL)
			.method(&Item::AccountBind, "AccountBind", "accountBind", "accountbind", NULL)
			.method(&Item::IsAccountbound, "IsAccountbound", "IsAccountBound", "isAccountBound", "isaccountbound", NULL)
			.method(&Item::MakeConjured, "MakeConjured", "makeConjured", "makeconjured", NULL)
			.method(&Item::IsConjured, "IsConjured", "isConjured", "isconjured", NULL)
			.method(&Item::Lock, "Lock", "lock", NULL)
			.method(&Item::UnLock, "UnLock", "unlock", "Unlock", NULL)
			.method(&Item::Wrap, "Wrap", "wrap", NULL)
			.method(&Item::UnWrap, "UnWrap", "Unwrap", "unwrap", NULL)
			.method(&Item::ClearFlags, "ClearFlags", "clearFlags", "clearflags", NULL)

			.method( &Item::GetItemRandomPropertyId, "GetItemRandomPropertyID", "getItemRandomPropertyID", "getitemrandompropertyid", NULL)
			.method( &Item::GetItemRandomSuffixFactor, "GetItemRandomSuffixFactor", "getItemRandomSuffixFactor", "getitemrandomsuffixfactor", NULL)
			.method( &Item::SetItemRandomPropertyId, "SetItemRandomPropertyId", "setItemRandomPropertyId", "setitemrandompropertyid", NULL)
			.method( &Item::SetItemRandomSuffixFactor, "SetItemRandomSuffixFactor", "setItemRandomSuffixFactor", "setitemrandomsuffixfactor", NULL)
			.method( &Item::SetRandomSuffix, "SetRandomSuffix", "setRandomSuffix", "setrandomsuffix", NULL)
			.method( &Item::SetDurability, "SetDurability", "setDurability", "setdurability", NULL)
			.method( &Item::SetDurabilityMax, "SetDurabilityMax", "setDurabilityMax", "setdurabilitymax", NULL)
			.method( &Item::GetDurability, "GetDurability", "getDurability", "getdurability", NULL)
			.method( &Item::GetDurabilityMax, "GetDurabilityMax", "getDurabilityMax", "getdurabilitymax", NULL)
			.method( &Item::SetDurabilityToMax, "SetDurabilityToMax", "setDurabilityToMax", "setdurabilitytomax", NULL)
			.method( &Item::GetEnchantmentId, "GetEnchantmentID", "getEnchantmentID", "getenchantmentid", NULL)
			.method( &Item::SetEnchantmentId, "SetEnchantmentID", "setEnchantmentID", "setenchantmentid", NULL)
			.method( &Item::GetEnchantmentDuration, "GetEnchantmentDuration", "getEnchantmentDuration", "getenchantmentduration", NULL)
			.method( &Item::SetEnchantmentDuration, "SetEnchantmentDuration", "setEnchantmentDuration", "setenchantmentduration", NULL)
			.method( &Item::GetEnchantmentCharges, "GetEnchantmentCharges", "getEnchantmentCharges", "getenchantmentcharges", NULL)
			.method( &Item::SetEnchantmentCharges, "SetEnchantmentCharges", "setEnchantmentCharges", "setenchantmentcharges", NULL)

			.method( &Item::IsContainer, "IsContainer", "isContainer", "iscontainer", NULL)
			.method( &Item::GetChargesLeft, "GetChargesLeft", "getChargesLeft", "getchargesleft", NULL)

			.method( &Item::AddEnchantment, "AddEnchantment", "addEnchantment", "addenchantment", NULL)
			.method( &Item::RemoveEnchantment, "RemoveEnchantment", "removeEnchantment", "removeenchantment", NULL)
			.method( &Item::HasEnchantment, "HasEnchantment", "hasEnchantment", "hasenchantment", NULL)
			.method( &Item::HasEnchantmentOnSlot, "HasEnchantmentOnSlot", "hasEnchantmentOnSlot", "hasenchantmentonslot", NULL)
			.method( &Item::ModifyEnchantmentTime, "ModifyEnchantmentTime", "modifyEnchantmentTime", "modifyenchantmenttime", NULL)
			.method( &Item::RemoveAllEnchantments, "RemoveAllEnchantments", "removeAllEnchantments", "removeallenchantments", NULL)
			.method( &Item::IsAmmoBag, "IsAmmoBag", "isAmmoBag", "isammobag", NULL)
			.method( &Item::RemoveFromWorld, "RemoveFromWorld", "removeFromWorld", "removefromworld", NULL)
			.method( &Item::HasEnchantments, "HasEnchantments", "hasEnchantments", "hasenchantments", NULL)
			.method( &Item::SaveToDB, "SaveToDB", "saveToDB", "savetodb",  NULL);
#undef BIND
#undef BINDE

#define BIND(name) .property_ro(#name, &ItemPrototype::name)
		m	.class_<ItemPrototype>("ItemPrototype")
			BIND(ItemId)
			BIND(Name1)
			BIND(DisplayInfoID)
			BIND(Flags)
			BIND(Faction)
			BIND(BuyPrice)
			BIND(SellPrice)
			BIND(ItemLevel)
			BIND(RequiredLevel)
			BIND(RequiredSkill)
			BIND(RequiredFaction)
			BIND(RequiredFactionStanding)
			BIND(Unique)
			BIND(MaxCount)
			BIND(Delay)
			BIND(RandomPropId)
			BIND(RandomSuffixId)
			BIND(TotemCategory)
			BIND(QuestId)
			BIND(Description);
#undef BIND
	}
}<|endoftext|>


<commit_before>#define weaver_debug_
#include "common/stl_serialization.h"
#include "node_prog/node_prog_type.h"
#include "node_prog/deep_nodes_inference.h"
#include <math.h>
# include <algorithm>
// #include <iostream>
using node_prog::search_type;
using node_prog::deep_node_infer_params;
using node_prog::deep_node_infer_state;
using node_prog::cache_response;

uint64_t deep_node_infer_params :: size() const
{
		uint64_t toRet = message::size(network_description)
				+ message::size(network_input)
				+ message::size(rank)
				+ message::size(layerType)
				+ message::size(layerOp)
				+ message::size(activationFn);
		return toRet;
}

void deep_node_infer_params :: pack(e::packer& packer) const
{
		message::pack_buffer(packer, network_description);
		message::pack_buffer(packer, network_input);
		message::pack_buffer(packer, rank);
		message::pack_buffer(packer, layerType);
		message::pack_buffer(packer, layerOp);
		message::pack_buffer(packer, activationFn);
}

void deep_node_infer_params :: unpack(e::unpacker& unpacker)
{
		message::unpack_buffer(unpacker, network_description);
		message::unpack_buffer(unpacker, network_input);
		message::unpack_buffer(unpacker, rank);
		message::unpack_buffer(unpacker, layerType);
		message::unpack_buffer(unpacker, layerOp);
		message::unpack_buffer(unpacker, activationFn);
}

deep_node_infer_state :: deep_node_infer_state()
		: visited(false)
		, in_count(0)

{ }

uint64_t
deep_node_infer_state:: size() const
{
		return message::size(visited)
				 + message::size(in_count)
				 + message::size(recorded_output);
}

void
deep_node_infer_state :: pack(e::packer &packer) const
{
		message::pack_buffer(packer, visited);
		message::pack_buffer(packer, in_count);
		message::pack_buffer(packer, recorded_output);
}

void
deep_node_infer_state :: unpack(e::unpacker &unpacker)
{
		message::unpack_buffer(unpacker, visited);
		message::unpack_buffer(unpacker, in_count);
		message::unpack_buffer(unpacker, recorded_output);
}

double
getEdgePropVal(node_prog::edge &e, std::string propertyName)
{
		node_prog::prop_list plist = e.get_properties();
		for (std::vector<std::shared_ptr<node_prog::property>> pvec: plist)
		{
			if (pvec.front()->key==propertyName)
			{
				double i_dec = std::stod (pvec.front()->value);
				return i_dec;
			}
		}
}

std::string
getEdgePropValStr(node_prog::edge &e, std::string propertyName)
{
		node_prog::prop_list plist = e.get_properties();
		for (std::vector<std::shared_ptr<node_prog::property>> pvec: plist)
		{
			if (pvec.front()->key==propertyName)
			{
				return pvec.front()->value;
			}
		}
}

uint32_t
nodeIncount(node_prog::node &n)
{
		uint32_t count=0;
		for (node_prog::edge &e: n.get_edges())
			{
					std::string str1="edgeDirection";
					std::string str2="B";
					std::pair<std::string, std::string> p=std::make_pair(str1,str2);
					if (e.has_property(p))
					{
							count=count+1;
					}
			}
			return count;
}

double sigmoid(double x)
{
		 double exp_value;
		 double return_value;
		 /*** Exponential calculation ***/
		 exp_value = exp((double) -x);
		 /*** Final sigmoid value ***/
		 return_value = 1 / (1 + exp_value);
		 return return_value;
}

double identityFn(double x)
{
		 return x;
}

std::pair<search_type, std::vector<std::pair<db::remote_node, deep_node_infer_params>>>
node_prog :: deep_node_inference_program(
		node &n,
		db::remote_node &rn,
		deep_node_infer_params &params,
		std::function<deep_node_infer_state&()> state_getter,
		std::function<void(std::shared_ptr<node_prog::Cache_Value_Base>,
				std::shared_ptr<std::vector<db::remote_node>>, cache_key_t)>&,
		cache_response<Cache_Value_Base>*)
{
		std::vector<std::pair<db::remote_node, deep_node_infer_params>> next;
		deep_node_infer_state &state = state_getter();

		std::cout << n.get_handle()<<std::endl;
		if (n.get_handle()==params.network_description.first)
		{
			// Start node of the network
				state.visited=true;
				std::vector<double> network_input(params.network_input);
				int counter=0;
				for (auto i = network_input.begin(); i != network_input.end(); ++i)
						{
						std::cout << *i << ' ';
						counter=counter+1;
						}
						std::cout << counter<<std::endl;

				params.network_input.clear();
				params.network_input.push_back(0.0);
				for (edge &e: n.get_edges())
				{
						uint32_t rank=(int)getEdgePropVal(e,"rank");
						double weight=getEdgePropVal(e,"weight");
						params.network_input.at(0)=weight*network_input.at(rank);
						params.rank=-1;
						params.layerType="init";
						params.layerOp="";
						next.emplace_back(std::make_pair(e.get_neighbor(), params));
				}
		}
		else if (n.get_handle()==params.network_description.second)
		{
			// last node of the network
			if (!state.visited)
			{
				state.visited=true;
				state.in_count=nodeIncount(n);
				state.recorded_output.assign (state.in_count,0.0);
			}
			state.recorded_output.at(params.rank)=params.network_input.at(0);
			state.in_count=state.in_count-1;
			if (state.in_count==0)
			{
				params.network_input=state.recorded_output;
				next.emplace_back(std::make_pair(db::coordinator, params));
			}
		}
		else
		{
			// any general node of the network
			if (!state.visited)
				{
					state.visited=true;
					state.in_count=nodeIncount(n);
					if (params.layerType!="pool")
						state.recorded_output.assign (1,0.0);
				}

				if (params.layerType=="pool")
					state.recorded_output.push_back(params.network_input.at(0));
				else
					state.recorded_output.at(0)=state.recorded_output.at(0)+params.network_input.at(0);

				state.in_count=state.in_count-1;
				if (state.in_count==0)
				{
					if (params.layerType=="pool")
					{
							double maxVal=*(std::max_element(state.recorded_output.begin(), state.recorded_output.end()));
							std::cout << maxVal<<std::endl;
							state.recorded_output.assign (1,0.0);
							state.recorded_output.at(0)=maxVal;
							params.network_input= state.recorded_output;

					}
					else
					{
						if (params.rank!=-1)
						{
							// first layer nodes , apply identity function to the input
							if (params.activationFn=="sigmoid")
							{
								state.recorded_output.at(0)=sigmoid(state.recorded_output.at(0));
							}
							else if (params.activationFn=="identity")
							{
								state.recorded_output.at(0)=identityFn(state.recorded_output.at(0));
							}

						}
					}

					for (edge &e: n.get_edges())
					{
						std::string str1="edgeDirection";
						std::string str2="F";
						std::pair<std::string, std::string> p=std::make_pair(str1,str2);

						if (e.has_property(p))
						{
							 double weight=getEdgePropVal(e,"weight");
							 params.network_input.at(0)=weight*state.recorded_output.at(0);
							 uint32_t rank=(int)getEdgePropVal(e,"rank");
							 std::string layerType=getEdgePropValStr(e,"layerType");
							 std::string layerOp=getEdgePropValStr(e,"layerOp");
							 params.rank=rank;
							 params.layerType=layerType;
							 params.layerOp=layerOp;
							 next.emplace_back(std::make_pair(e.get_neighbor(), params));
						}
					}
				}
		}
		return std::make_pair(search_type::BREADTH_FIRST, next);
}
<commit_msg>deepNdes<commit_after>#define weaver_debug_
#include "common/stl_serialization.h"
#include "node_prog/node_prog_type.h"
#include "node_prog/deep_nodes_inference.h"
#include <math.h>
# include <algorithm>
// #include <iostream>
using node_prog::search_type;
using node_prog::deep_node_infer_params;
using node_prog::deep_node_infer_state;
using node_prog::cache_response;

uint64_t deep_node_infer_params :: size() const
{
		uint64_t toRet = message::size(network_description)
				+ message::size(network_input)
				+ message::size(rank)
				+ message::size(layerType)
				+ message::size(layerOp)
				+ message::size(activationFn);
		return toRet;
}

void deep_node_infer_params :: pack(e::packer& packer) const
{
		message::pack_buffer(packer, network_description);
		message::pack_buffer(packer, network_input);
		message::pack_buffer(packer, rank);
		message::pack_buffer(packer, layerType);
		message::pack_buffer(packer, layerOp);
		message::pack_buffer(packer, activationFn);
}

void deep_node_infer_params :: unpack(e::unpacker& unpacker)
{
		message::unpack_buffer(unpacker, network_description);
		message::unpack_buffer(unpacker, network_input);
		message::unpack_buffer(unpacker, rank);
		message::unpack_buffer(unpacker, layerType);
		message::unpack_buffer(unpacker, layerOp);
		message::unpack_buffer(unpacker, activationFn);
}

deep_node_infer_state :: deep_node_infer_state()
		: visited(false)
		, in_count(0)

{ }

uint64_t
deep_node_infer_state:: size() const
{
		return message::size(visited)
				 + message::size(in_count)
				 + message::size(recorded_output);
}

void
deep_node_infer_state :: pack(e::packer &packer) const
{
		message::pack_buffer(packer, visited);
		message::pack_buffer(packer, in_count);
		message::pack_buffer(packer, recorded_output);
}

void
deep_node_infer_state :: unpack(e::unpacker &unpacker)
{
		message::unpack_buffer(unpacker, visited);
		message::unpack_buffer(unpacker, in_count);
		message::unpack_buffer(unpacker, recorded_output);
}

double
getEdgePropVal(node_prog::edge &e, std::string propertyName)
{
		node_prog::prop_list plist = e.get_properties();
		for (std::vector<std::shared_ptr<node_prog::property>> pvec: plist)
		{
			if (pvec.front()->key==propertyName)
			{
				double i_dec = std::stod (pvec.front()->value);
				return i_dec;
			}
		}
}

double
getNodePropVal(node_prog::node &n, std::string propertyName)
{
		node_prog::prop_list plist = n.get_properties();
		for (std::vector<std::shared_ptr<node_prog::property>> pvec: plist)
		{
			if (pvec.front()->key==propertyName)
			{
				double i_dec = std::stod (pvec.front()->value);
				return i_dec;
			}
		}
}

std::string
getEdgePropValStr(node_prog::edge &e, std::string propertyName)
{
		node_prog::prop_list plist = e.get_properties();
		for (std::vector<std::shared_ptr<node_prog::property>> pvec: plist)
		{
			if (pvec.front()->key==propertyName)
			{
				return pvec.front()->value;
			}
		}
}

uint32_t
nodeIncount(node_prog::node &n)
{
		uint32_t count=0;
		for (node_prog::edge &e: n.get_edges())
			{
					std::string str1="edgeDirection";
					std::string str2="B";
					std::pair<std::string, std::string> p=std::make_pair(str1,str2);
					if (e.has_property(p))
					{
							count=count+1;
					}
			}
			return count;
}

double sigmoid(double x)
{
		 double exp_value;
		 double return_value;
		 /*** Exponential calculation ***/
		 exp_value = exp((double) -x);
		 /*** Final sigmoid value ***/
		 return_value = 1 / (1 + exp_value);
		 return return_value;
}

double identityFn(double x)
{
		 return x;
}

std::pair<search_type, std::vector<std::pair<db::remote_node, deep_node_infer_params>>>
node_prog :: deep_node_inference_program(
		node &n,
		db::remote_node &rn,
		deep_node_infer_params &params,
		std::function<deep_node_infer_state&()> state_getter,
		std::function<void(std::shared_ptr<node_prog::Cache_Value_Base>,
				std::shared_ptr<std::vector<db::remote_node>>, cache_key_t)>&,
		cache_response<Cache_Value_Base>*)
{
		std::vector<std::pair<db::remote_node, deep_node_infer_params>> next;
		deep_node_infer_state &state = state_getter();

		std::cout << n.get_handle()<<std::endl;
		if (n.get_handle()==params.network_description.first)
		{
			// Start node of the network
				state.visited=true;
				std::vector<double> network_input(params.network_input);
				int counter=0;
				for (auto i = network_input.begin(); i != network_input.end(); ++i)
						{
						std::cout << *i << ' ';
						counter=counter+1;
						}
						std::cout << counter<<std::endl;

				params.network_input.clear();
				params.network_input.push_back(0.0);
				for (edge &e: n.get_edges())
				{
						uint32_t rank=(int)getEdgePropVal(e,"rank");
						double weight=getEdgePropVal(e,"weight");
						params.network_input.at(0)=weight*network_input.at(rank);
						params.rank=-1;
						params.layerType="init";
						params.layerOp="";
						next.emplace_back(std::make_pair(e.get_neighbor(), params));
				}
		}
		else if (n.get_handle()==params.network_description.second)
		{
			// last node of the network
			if (!state.visited)
			{
				state.visited=true;
				state.in_count=nodeIncount(n);
				state.recorded_output.assign (state.in_count,0.0);
			}
			state.recorded_output.at(params.rank)=params.network_input.at(0);
			state.in_count=state.in_count-1;
			if (state.in_count==0)
			{
				params.network_input=state.recorded_output;
				next.emplace_back(std::make_pair(db::coordinator, params));
			}
		}
		else
		{
			// any general node of the network
			if (!state.visited)
				{
					state.visited=true;
					state.in_count=nodeIncount(n);
					if (params.layerType!="pool")
					{
						double bias=getNodePropVal(n,"bias");
						state.recorded_output.assign (1,bias);
					}

				}

				if (params.layerType=="pool")
					state.recorded_output.push_back(params.network_input.at(0));
				else
					state.recorded_output.at(0)=state.recorded_output.at(0)+params.network_input.at(0);

				state.in_count=state.in_count-1;
				if (state.in_count==0)
				{
					if (params.layerType=="pool")
					{
							double maxVal=*(std::max_element(state.recorded_output.begin(), state.recorded_output.end()));
							std::cout << maxVal<<std::endl;
							state.recorded_output.assign (1,0.0);
							state.recorded_output.at(0)=maxVal;
							params.network_input= state.recorded_output;

					}
					else
					{
						if (params.rank!=-1)
						{
							// first layer nodes , apply identity function to the input
							if (params.activationFn=="sigmoid")
							{
								state.recorded_output.at(0)=sigmoid(state.recorded_output.at(0));
							}
							else if (params.activationFn=="identity")
							{
								state.recorded_output.at(0)=identityFn(state.recorded_output.at(0));
							}

						}
					}

					for (edge &e: n.get_edges())
					{
						std::string str1="edgeDirection";
						std::string str2="F";
						std::pair<std::string, std::string> p=std::make_pair(str1,str2);

						if (e.has_property(p))
						{
							 double weight=getEdgePropVal(e,"weight");
							 params.network_input.at(0)=weight*state.recorded_output.at(0);
							 uint32_t rank=(int)getEdgePropVal(e,"rank");
							 std::string layerType=getEdgePropValStr(e,"layerType");
							 std::string layerOp=getEdgePropValStr(e,"layerOp");
							 params.rank=rank;
							 params.layerType=layerType;
							 params.layerOp=layerOp;
							 next.emplace_back(std::make_pair(e.get_neighbor(), params));
						}
					}
				}
		}
		return std::make_pair(search_type::BREADTH_FIRST, next);
}
<|endoftext|>


<commit_before>#include "PositionModule.hpp"

#include <assert.h>
#include <sys/stat.h>
#include <errno.h>
#include <stdlib.h>
#include <string>
#include <algorithm>
#include <iostream>

#include <ros/console.h>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/calib3d/calib3d.hpp>

#include "sensor_msgs/Image.h"
#include "api_application/Ping.h"
#include "api_application/Announce.h"

#include "../matlab/Vector.h"

// Use this to test if images are saved properly, when you only have one camera.
//#define SINGLE_CAMERA_CALIBRATION

PositionModule::PositionModule(IPositionReceiver* receiver) :
	pictureCache(50), // Assume we never have 50 or more modules running on the network.
	pictureTimes(50)
{
	assert(receiver != 0);
	this->receiver = receiver;

	ROS_DEBUG("Initializing PositionModule");

	_isInitialized = true;
	isCalibrating = false;
	isRunning = false;

	ros::NodeHandle n;

	this->pictureSendingActivationPublisher = n.advertise<camera_application::PictureSendingActivation>("PictureSendingActivation", 4);
	this->pingPublisher = n.advertise<api_application::Ping>("Ping", 4);

	this->pictureSubscriber = n.subscribe("Picture", 128, &PositionModule::pictureCallback, this);
	this->systemSubscriber = n.subscribe("System", 4, &PositionModule::systemCallback, this);
	this->rawPositionSubscriber = n.subscribe("RawPosition", 1024, &PositionModule::rawPositionCallback, this);

	this->startCalibrationService = n.advertiseService("StartCalibration", &PositionModule::startCalibrationCallback, this);
	this->takeCalibrationPictureService = n.advertiseService("TakeCalibrationPicture", &PositionModule::takeCalibrationPictureCallback, this);
	this->calculateCalibrationService = n.advertiseService("CalculateCalibration", &PositionModule::calculateCalibrationCallback, this);

	// Advertise myself to API
	ros::ServiceClient announceClient = n.serviceClient<api_application::Announce>("announce");

	api_application::Announce announce;
	announce.request.type = 3; // 3 means position module

	if (announceClient.call(announce))
	{
		rosId = announce.response.id;

		if (rosId == ~0 /* -1 */)
		{
			ROS_ERROR("Error! Got id -1");
			_isInitialized = false;
		}
		else
		{
			ROS_INFO("Position module successfully announced. Got id %d", rosId);
		}
	}
	else
	{
		ROS_ERROR("Error! Could not announce myself to API!");
		_isInitialized = false;
	}

	msg = new KitrokopterMessages(rosId);

	if (_isInitialized)
	{
		ROS_DEBUG("PositionModule initialized");
	} else {
		ROS_ERROR("Could not initialize PositionModule!");
	}
}

PositionModule::~PositionModule()
{
	msg->~KitrokopterMessages();

	// TODO: Free picture cache.

	ROS_DEBUG("PositionModule destroyed");
}

// Service
bool PositionModule::startCalibrationCallback(control_application::StartCalibration::Request &req, control_application::StartCalibration::Response &res)
{
	res.ok = !isCalibrating;

	if (!isCalibrating)
	{
		ROS_INFO("Starting multi camera calibration process");

		setPictureSendingActivated(true);
		calibrationPictureCount = 0;
		boardSize = cv::Size(req.chessboardWidth, req.chessboardHeight);
		realSize = cv::Size(req.chessboardRealWidth, req.chessboardRealHeight);
	}

	isCalibrating = true;
	return true;
}

// Service
bool PositionModule::takeCalibrationPictureCallback(control_application::TakeCalibrationPicture::Request &req, control_application::TakeCalibrationPicture::Response &res)
{
	ROS_DEBUG("Taking calibration picture. Have %ld cameras.", camNoToNetId.size());

	pictureCacheMutex.lock();

	// Build net id -> cam no map.
	if (camNoToNetId.size() != netIdToCamNo.size()) {
		// If already built, there are already images on the disk with wrong ids, so return an error.
		if (netIdToCamNo.size() != 0) {
			ROS_ERROR("Got new cameras after taking first calibration picture!");
			return false;
		}

		std::sort(camNoToNetId.begin(), camNoToNetId.end());
		netIdToCamNo.clear();

		for (int i = 0; i < camNoToNetId.size(); i++) {
			netIdToCamNo[camNoToNetId[i]] = i;
		}

		ROS_INFO("Got %ld cameras", netIdToCamNo.size());
	}

	int id = 0;
	std::map<int, cv::Mat*> goodPictures;

	for (std::vector<cv::Mat*>::iterator it = pictureCache.begin(); it != pictureCache.end(); it++, id++)
	{
		if (*it != 0)
		{
			std::vector<cv::Point2f> corners;
			bool foundAllCorners = cv::findChessboardCorners(**it, boardSize, corners, CV_CALIB_CB_ADAPTIVE_THRESH | CV_CALIB_CB_FILTER_QUADS | CV_CALIB_CB_FAST_CHECK | CV_CALIB_CB_NORMALIZE_IMAGE);

			if (!foundAllCorners)
			{
				ROS_INFO("Took bad picture (id %d)", id);
				delete *it;
				*it = 0;
				continue;
			}
			else
			{
				ROS_INFO("Took good picture (id %d)", id);
				goodPictures[id] = *it;

				// Remove image from image cache.
				*it = 0;
			}
		}
	}

	pictureCacheMutex.unlock();

	#ifdef SINGLE_CAMERA_CALIBRATION
	if (goodPictures.size() >= 1) {
	#else
	if (goodPictures.size() >= 2) {
	#endif
		// Create directory for images.
		int error = mkdir("/tmp/calibrationImages", 0777);

		if (error != 0 && errno != EEXIST)
		{
			ROS_ERROR("Could not create directory for calibration images (/tmp/calibrationImages): %d", errno);

			// Delete images.
			for (std::map<int, cv::Mat*>::iterator it = goodPictures.begin(); it != goodPictures.end(); it++) {
				delete it->second;
			}

			return false;
		}

		error = mkdir("/tmp/calibrationResult", 0777);

		if (error != 0 && errno != EEXIST)
		{
			ROS_ERROR("Could not create directory for calibration images (/tmp/calibrationResult): %d", errno);

			// Delete images.
			for (std::map<int, cv::Mat*>::iterator it = goodPictures.begin(); it != goodPictures.end(); it++) {
				delete it->second;
			}

			return false;
		}

		for (std::map<int, cv::Mat*>::iterator it = goodPictures.begin(); it != goodPictures.end(); it++) {
			std::stringstream ss;
			ss << "/tmp/calibrationImages/cam" << netIdToCamNo[it->first] << "_image" << calibrationPictureCount << ".png";

			// Save picture on disk for amcctoolbox.
			std::cout << "Saving picture: " << cv::imwrite(ss.str(), *(it->second)) << std::endl;

			sensor_msgs::Image img;
			img.width = 640;
			img.height = 480;
			img.step = 3 * 640;
			img.data.reserve(img.step * img.height);

			for (int i = 0; i < 640 * 480 * 3; i++)
			{
				img.data[i] = it->second->data[i];
			}

			res.images.push_back(img);
			res.ids.push_back(it->first);

			delete it->second;
		}

		calibrationPictureCount++;
	}

	return true;
}

// Service
bool PositionModule::calculateCalibrationCallback(control_application::CalculateCalibration::Request &req, control_application::CalculateCalibration::Response &res)
{
	if (!isCalibrating) {
		ROS_ERROR("Cannot calculate calibration! Start calibration first!");
		return false;
	}

	if (netIdToCamNo.size() < 2) {
		ROS_ERROR("Have not enough images for calibration (Have %ld)!", netIdToCamNo.size());
	}

	ROS_INFO("Calculating multi camera calibration. This could take up to 2 hours");
	ChessboardData data(boardSize.width, boardSize.height, realSize.width, realSize.height);

	pictureCacheMutex.lock();
	int camNumber = camNoToNetId.size();
	pictureCacheMutex.unlock();

	// Delete old calibration results.
	system("rm -rf /tmp/calibrationResult/*");
	bool ok = tracker.calibrate(&data, camNoToNetId.size());

	if (ok) {
		ROS_INFO("Finished multi camera calibration");

		// TODO make not uncommented
		system("rm -rf /tmp/calibrationImages/*");
	} else {
		ROS_ERROR("Calibration failed!");
	}

	isCalibrating = false;

	return ok;
}

// Topic
void PositionModule::pictureCallback(const camera_application::Picture &msg)
{
	assert(msg.ID < 50);

	pictureCacheMutex.lock();

	bool idKnown = false;

	// Insert camera id, if not already there.
	for (int i = 0; i < camNoToNetId.size(); i++) {
		if (camNoToNetId[i] == msg.ID) {
			idKnown = true;
			break;
		}
	}

	if (!idKnown) {
		camNoToNetId.push_back(msg.ID);
	}

	if (isCalibrating)
	{
		// Will crash here, if more than 49 modules are used.
		if (pictureCache[msg.ID] != 0)
		{
			delete pictureCache[msg.ID];
			pictureCache[msg.ID] = 0;

		}

		cv::Mat* image = new cv::Mat(cv::Size(640, 480), CV_8UC3);

		for (int i = 0; i < 640 * 480 * 3; i++)
		{
			image->data[i] = msg.image[i];
		}

		pictureCache[msg.ID] = image;
		pictureTimes[msg.ID] = msg.timestamp;
	}

	pictureCacheMutex.unlock();
}

// Topic
void PositionModule::systemCallback(const api_application::System &msg)
{
	isRunning = msg.command == 1;

	if (isRunning) {
		ROS_INFO("Tracking started");
	} else {
		ROS_INFO("Tracking stopped");
	}

	if (!isRunning) {
		ros::shutdown();
	}
}

// Topic
void PositionModule::rawPositionCallback(const camera_application::RawPosition &msg)
{
 	// TODO: Calculate position in our coordinate system.
	// TODO: Is this coordinate change correct for amcctoolbox?
	Vector cameraVector(msg.xPosition, msg.yPosition, 1);
	ROS_DEBUG("msg.ID: %d netIdToCamNo[msg.ID]: %d msg.quadcopterId: %d", msg.ID, netIdToCamNo[msg.ID], msg.quadcopterId);
	Vector result = tracker.updatePosition(cameraVector, netIdToCamNo[msg.ID], msg.quadcopterId);

	std::vector<Vector> positions;
	std::vector<int> ids;
	std::vector<int> updates;
	positions.push_back(result);
	ids.push_back(msg.quadcopterId);
	updates.push_back(1);

	if (result.isValid()) {
		receiver->updatePositions(positions, ids, updates);
	} else {
		ROS_DEBUG("Not enough information to get position of quadcopter %d", msg.quadcopterId);
	}
}

void PositionModule::setPictureSendingActivated(bool activated)
{
	camera_application::PictureSendingActivation msg;
	msg.ID = 0;
	msg.active = activated;

	pictureSendingActivationPublisher.publish(msg);
}

void PositionModule::sendPing()
{
	api_application::Ping msg;
	msg.ID = rosId;
	pingPublisher.publish(msg);
}

bool PositionModule::isInitialized()
{
	return _isInitialized;
}<commit_msg>Save all images, if enough good images are found<commit_after>#include "PositionModule.hpp"

#include <assert.h>
#include <sys/stat.h>
#include <errno.h>
#include <stdlib.h>
#include <string>
#include <algorithm>
#include <iostream>

#include <ros/console.h>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/calib3d/calib3d.hpp>

#include "sensor_msgs/Image.h"
#include "api_application/Ping.h"
#include "api_application/Announce.h"

#include "../matlab/Vector.h"

// Use this to test if images are saved properly, when you only have one camera.
//#define SINGLE_CAMERA_CALIBRATION

PositionModule::PositionModule(IPositionReceiver* receiver) :
	pictureCache(50), // Assume we never have 50 or more modules running on the network.
	pictureTimes(50)
{
	assert(receiver != 0);
	this->receiver = receiver;

	ROS_DEBUG("Initializing PositionModule");

	_isInitialized = true;
	isCalibrating = false;
	isRunning = false;

	ros::NodeHandle n;

	this->pictureSendingActivationPublisher = n.advertise<camera_application::PictureSendingActivation>("PictureSendingActivation", 4);
	this->pingPublisher = n.advertise<api_application::Ping>("Ping", 4);

	this->pictureSubscriber = n.subscribe("Picture", 128, &PositionModule::pictureCallback, this);
	this->systemSubscriber = n.subscribe("System", 4, &PositionModule::systemCallback, this);
	this->rawPositionSubscriber = n.subscribe("RawPosition", 1024, &PositionModule::rawPositionCallback, this);

	this->startCalibrationService = n.advertiseService("StartCalibration", &PositionModule::startCalibrationCallback, this);
	this->takeCalibrationPictureService = n.advertiseService("TakeCalibrationPicture", &PositionModule::takeCalibrationPictureCallback, this);
	this->calculateCalibrationService = n.advertiseService("CalculateCalibration", &PositionModule::calculateCalibrationCallback, this);

	// Advertise myself to API
	ros::ServiceClient announceClient = n.serviceClient<api_application::Announce>("announce");

	api_application::Announce announce;
	announce.request.type = 3; // 3 means position module

	if (announceClient.call(announce))
	{
		rosId = announce.response.id;

		if (rosId == ~0 /* -1 */)
		{
			ROS_ERROR("Error! Got id -1");
			_isInitialized = false;
		}
		else
		{
			ROS_INFO("Position module successfully announced. Got id %d", rosId);
		}
	}
	else
	{
		ROS_ERROR("Error! Could not announce myself to API!");
		_isInitialized = false;
	}

	msg = new KitrokopterMessages(rosId);

	if (_isInitialized)
	{
		ROS_DEBUG("PositionModule initialized");
	} else {
		ROS_ERROR("Could not initialize PositionModule!");
	}
}

PositionModule::~PositionModule()
{
	msg->~KitrokopterMessages();

	// TODO: Free picture cache.

	ROS_DEBUG("PositionModule destroyed");
}

// Service
bool PositionModule::startCalibrationCallback(control_application::StartCalibration::Request &req, control_application::StartCalibration::Response &res)
{
	res.ok = !isCalibrating;

	if (!isCalibrating)
	{
		ROS_INFO("Starting multi camera calibration process");

		setPictureSendingActivated(true);
		calibrationPictureCount = 0;
		boardSize = cv::Size(req.chessboardWidth, req.chessboardHeight);
		realSize = cv::Size(req.chessboardRealWidth, req.chessboardRealHeight);
	}

	isCalibrating = true;
	return true;
}

// Service
bool PositionModule::takeCalibrationPictureCallback(control_application::TakeCalibrationPicture::Request &req, control_application::TakeCalibrationPicture::Response &res)
{
	ROS_DEBUG("Taking calibration picture. Have %ld cameras.", camNoToNetId.size());

	pictureCacheMutex.lock();

	// Build net id -> cam no map.
	if (camNoToNetId.size() != netIdToCamNo.size()) {
		// If already built, there are already images on the disk with wrong ids, so return an error.
		if (netIdToCamNo.size() != 0) {
			ROS_ERROR("Got new cameras after taking first calibration picture!");
			return false;
		}

		std::sort(camNoToNetId.begin(), camNoToNetId.end());
		netIdToCamNo.clear();

		for (int i = 0; i < camNoToNetId.size(); i++) {
			netIdToCamNo[camNoToNetId[i]] = i;
		}

		ROS_INFO("Got %ld cameras", netIdToCamNo.size());
	}

	int id = 0;
	std::map<int, cv::Mat*> pictureMap;
	int goodPictures = 0;

	for (std::vector<cv::Mat*>::iterator it = pictureCache.begin(); it != pictureCache.end(); it++, id++)
	{
		if (*it != 0)
		{
			std::vector<cv::Point2f> corners;
			bool foundAllCorners = cv::findChessboardCorners(**it, boardSize, corners, CV_CALIB_CB_ADAPTIVE_THRESH | CV_CALIB_CB_FILTER_QUADS | CV_CALIB_CB_FAST_CHECK | CV_CALIB_CB_NORMALIZE_IMAGE);

			if (!foundAllCorners)
			{
				ROS_INFO("Took bad picture (id %d)", id);
				goodPictures++;
			}
			else
			{
				ROS_INFO("Took good picture (id %d)", id);
			}

			pictureMap[id] = *it;

			// Remove image from image cache.
			*it = 0;
		}
	}

	pictureCacheMutex.unlock();

	#ifdef SINGLE_CAMERA_CALIBRATION
	if (goodPictures >= 1) {
	#else
	if (goodPictures >= 2) {
	#endif
		// Create directory for images.
		int error = mkdir("/tmp/calibrationImages", 0777);

		if (error != 0 && errno != EEXIST)
		{
			ROS_ERROR("Could not create directory for calibration images (/tmp/calibrationImages): %d", errno);

			// Delete images.
			for (std::map<int, cv::Mat*>::iterator it = pictureMap.begin(); it != pictureMap.end(); it++) {
				delete it->second;
			}

			return false;
		}

		error = mkdir("/tmp/calibrationResult", 0777);

		if (error != 0 && errno != EEXIST)
		{
			ROS_ERROR("Could not create directory for calibration images (/tmp/calibrationResult): %d", errno);

			// Delete images.
			for (std::map<int, cv::Mat*>::iterator it = pictureMap.begin(); it != pictureMap.end(); it++) {
				delete it->second;
			}

			return false;
		}

		for (std::map<int, cv::Mat*>::iterator it = pictureMap.begin(); it != pictureMap.end(); it++) {
			std::stringstream ss;
			ss << "/tmp/calibrationImages/cam" << netIdToCamNo[it->first] << "_image" << calibrationPictureCount << ".png";

			// Save picture on disk for amcctoolbox.
			std::cout << "Saving picture: " << cv::imwrite(ss.str(), *(it->second)) << std::endl;

			sensor_msgs::Image img;
			img.width = 640;
			img.height = 480;
			img.step = 3 * 640;
			img.data.reserve(img.step * img.height);

			for (int i = 0; i < 640 * 480 * 3; i++)
			{
				img.data[i] = it->second->data[i];
			}

			res.images.push_back(img);
			res.ids.push_back(it->first);

			delete it->second;
		}

		calibrationPictureCount++;
	}

	return true;
}

// Service
bool PositionModule::calculateCalibrationCallback(control_application::CalculateCalibration::Request &req, control_application::CalculateCalibration::Response &res)
{
	if (!isCalibrating) {
		ROS_ERROR("Cannot calculate calibration! Start calibration first!");
		return false;
	}

	if (netIdToCamNo.size() < 2) {
		ROS_ERROR("Have not enough images for calibration (Have %ld)!", netIdToCamNo.size());
	}

	ROS_INFO("Calculating multi camera calibration. This could take up to 2 hours");
	ChessboardData data(boardSize.width, boardSize.height, realSize.width, realSize.height);

	pictureCacheMutex.lock();
	int camNumber = camNoToNetId.size();
	pictureCacheMutex.unlock();

	// Delete old calibration results.
	system("rm -rf /tmp/calibrationResult/*");
	bool ok = tracker.calibrate(&data, camNoToNetId.size());

	if (ok) {
		ROS_INFO("Finished multi camera calibration");

		// TODO make not uncommented
		system("rm -rf /tmp/calibrationImages/*");
	} else {
		ROS_ERROR("Calibration failed!");
	}

	isCalibrating = false;

	return ok;
}

// Topic
void PositionModule::pictureCallback(const camera_application::Picture &msg)
{
	assert(msg.ID < 50);

	pictureCacheMutex.lock();

	bool idKnown = false;

	// Insert camera id, if not already there.
	for (int i = 0; i < camNoToNetId.size(); i++) {
		if (camNoToNetId[i] == msg.ID) {
			idKnown = true;
			break;
		}
	}

	if (!idKnown) {
		camNoToNetId.push_back(msg.ID);
	}

	if (isCalibrating)
	{
		// Will crash here, if more than 49 modules are used.
		if (pictureCache[msg.ID] != 0)
		{
			delete pictureCache[msg.ID];
			pictureCache[msg.ID] = 0;

		}

		cv::Mat* image = new cv::Mat(cv::Size(640, 480), CV_8UC3);

		for (int i = 0; i < 640 * 480 * 3; i++)
		{
			image->data[i] = msg.image[i];
		}

		pictureCache[msg.ID] = image;
		pictureTimes[msg.ID] = msg.timestamp;
	}

	pictureCacheMutex.unlock();
}

// Topic
void PositionModule::systemCallback(const api_application::System &msg)
{
	isRunning = msg.command == 1;

	if (isRunning) {
		ROS_INFO("Tracking started");
	} else {
		ROS_INFO("Tracking stopped");
	}

	if (!isRunning) {
		ros::shutdown();
	}
}

// Topic
void PositionModule::rawPositionCallback(const camera_application::RawPosition &msg)
{
 	// TODO: Calculate position in our coordinate system.
	// TODO: Is this coordinate change correct for amcctoolbox?
	Vector cameraVector(msg.xPosition, msg.yPosition, 1);
	ROS_DEBUG("msg.ID: %d netIdToCamNo[msg.ID]: %d msg.quadcopterId: %d", msg.ID, netIdToCamNo[msg.ID], msg.quadcopterId);
	Vector result = tracker.updatePosition(cameraVector, netIdToCamNo[msg.ID], msg.quadcopterId);

	std::vector<Vector> positions;
	std::vector<int> ids;
	std::vector<int> updates;
	positions.push_back(result);
	ids.push_back(msg.quadcopterId);
	updates.push_back(1);

	if (result.isValid()) {
		receiver->updatePositions(positions, ids, updates);
	} else {
		ROS_DEBUG("Not enough information to get position of quadcopter %d", msg.quadcopterId);
	}
}

void PositionModule::setPictureSendingActivated(bool activated)
{
	camera_application::PictureSendingActivation msg;
	msg.ID = 0;
	msg.active = activated;

	pictureSendingActivationPublisher.publish(msg);
}

void PositionModule::sendPing()
{
	api_application::Ping msg;
	msg.ID = rosId;
	pingPublisher.publish(msg);
}

bool PositionModule::isInitialized()
{
	return _isInitialized;
}<|endoftext|>


<commit_before>#include "TrackingWorker.hpp"

//#include <boost/chrono/duration.hpp>
#include <ros/console.h>
#include "../matlab/profiling.hpp"

TrackingWorker::TrackingWorker(IPositionReceiver *receiver)
{
	assert(receiver != 0);

	this->receiver = receiver;
	stop = false;

	thread = new boost::thread(boost::bind(&TrackingWorker::run, this));
}

TrackingWorker::~TrackingWorker()
{
	stop = true;
	thread->join();
}

void TrackingWorker::run()
{
	ROS_INFO("Started tracking thread");

	bool receivedFirstPosition = false;

	while (!stop) {
		CameraData data = dequeue();

		if (data.valid) {
			// ROS_DEBUG("Got valid data");
			receivedFirstPosition = true;

			long int startTime = getNanoTime();
			Vector position = tracker.updatePosition(data.cameraVector, data.camNo, data.quadcopterId);
			double duration = getNanoTime() - startTime;
			duration /= 1e6;

			std::vector<Vector> positions;
			std::vector<int> ids;
			std::vector<int> updates;
			positions.push_back(position);
			ids.push_back(data.quadcopterId);
			updates.push_back(1);

			if (position.isValid()) {
				receiver->updatePositions(positions, ids, updates);
			} else {
				// ROS_DEBUG("Not enough information to get position of quadcopter %d", data.quadcopterId);
			}

			ROS_DEBUG("Updating position of quadcopter %d took %.3f ms", data.quadcopterId, duration);
		} else if (receivedFirstPosition) {
			ROS_WARN("Position update buffer is empty!");
		}
	}

	ROS_INFO("Stopped tracking thread");
}

void TrackingWorker::updatePosition(Vector cameraVector, int camNo, int quadcopterId)
{
	CameraData data;
	data.cameraVector = cameraVector;
	data.camNo = camNo;
	data.quadcopterId = quadcopterId;
	data.valid = true;

	updatePosition(data);
}

void TrackingWorker::updatePosition(CameraData data)
{
	// ROS_DEBUG("updatePosition: called");

	enqueue(data);

	// ROS_DEBUG("updatePosition: Inserted CameraData for camera %d and quadcopter %d", data.camNo, data.quadcopterId);
}

void TrackingWorker::enqueue(CameraData data)
{
	// ROS_DEBUG("enqueue: Inserting CameraData");

	{
		boost::mutex::scoped_lock lock(positionsMutex);
		// ROS_DEBUG("enqueue: Got positions lock");
		positions.push(data);

		if (positions.size() > 25) {
			ROS_WARN("Position update buffer is running full (%ld entries). Seems like the position updating can't keep up! Dropping 15 entries.", positions.size());

			for (int i = 0; i < 15; i++) {
				positions.pop();
			}
		}
	}

	// ROS_DEBUG("enqueue: Released positions lock");
	// ROS_DEBUG("enqueue: Notifying about new CameraData");

	positionsEmpty.notify_one();

	// ROS_DEBUG("enqueue: Finished insertion process");
}

CameraData TrackingWorker::dequeue()
{
	// ROS_DEBUG("dequeue: Getting positions lock");

	{
		boost::mutex::scoped_lock lock(positionsMutex);

		// ROS_DEBUG("dequeue: Got positions lock");

		/*if (!dataAvailable()) {
			positionsEmpty.timed_wait(lock, boost::get_system_time() + boost::posix_time::milliseconds(100));
		}*/

		if (dataAvailable()) {
			CameraData data = positions.front();
			positions.pop();

			// ROS_DEBUG("dequeue: Released positions lock");
			return data;
		} else {
			CameraData data;
			data.valid = false;

			// ROS_DEBUG("dequeue: Released positions lock");
			return data;
		}
	}
}

bool TrackingWorker::dataAvailable()
{
	return positions.size() > 0;
}

bool TrackingWorker::calibrate(ChessboardData *chessboard, int camNo)
{
	return tracker.calibrate(chessboard, camNo);
}

Vector TrackingWorker::getCameraPosition(int camNo)
{
	return tracker.getPosition(camNo);
}
<commit_msg>Removed libboost quickfixes<commit_after>#include "TrackingWorker.hpp"

#include <boost/chrono/duration.hpp>
#include <ros/console.h>
#include "../matlab/profiling.hpp"

TrackingWorker::TrackingWorker(IPositionReceiver *receiver)
{
	assert(receiver != 0);

	this->receiver = receiver;
	stop = false;

	thread = new boost::thread(boost::bind(&TrackingWorker::run, this));
}

TrackingWorker::~TrackingWorker()
{
	stop = true;
	thread->join();
}

void TrackingWorker::run()
{
	ROS_INFO("Started tracking thread");

	bool receivedFirstPosition = false;

	while (!stop) {
		CameraData data = dequeue();

		if (data.valid) {
			// ROS_DEBUG("Got valid data");
			receivedFirstPosition = true;

			long int startTime = getNanoTime();
			Vector position = tracker.updatePosition(data.cameraVector, data.camNo, data.quadcopterId);
			double duration = getNanoTime() - startTime;
			duration /= 1e6;

			std::vector<Vector> positions;
			std::vector<int> ids;
			std::vector<int> updates;
			positions.push_back(position);
			ids.push_back(data.quadcopterId);
			updates.push_back(1);

			if (position.isValid()) {
				receiver->updatePositions(positions, ids, updates);
			} else {
				// ROS_DEBUG("Not enough information to get position of quadcopter %d", data.quadcopterId);
			}

			ROS_DEBUG("Updating position of quadcopter %d took %.3f ms", data.quadcopterId, duration);
		} else if (receivedFirstPosition) {
			ROS_WARN("Position update buffer is empty!");
		}
	}

	ROS_INFO("Stopped tracking thread");
}

void TrackingWorker::updatePosition(Vector cameraVector, int camNo, int quadcopterId)
{
	CameraData data;
	data.cameraVector = cameraVector;
	data.camNo = camNo;
	data.quadcopterId = quadcopterId;
	data.valid = true;

	updatePosition(data);
}

void TrackingWorker::updatePosition(CameraData data)
{
	// ROS_DEBUG("updatePosition: called");

	enqueue(data);

	// ROS_DEBUG("updatePosition: Inserted CameraData for camera %d and quadcopter %d", data.camNo, data.quadcopterId);
}

void TrackingWorker::enqueue(CameraData data)
{
	// ROS_DEBUG("enqueue: Inserting CameraData");

	{
		boost::mutex::scoped_lock lock(positionsMutex);
		// ROS_DEBUG("enqueue: Got positions lock");
		positions.push(data);

		if (positions.size() > 25) {
			ROS_WARN("Position update buffer is running full (%ld entries). Seems like the position updating can't keep up! Dropping 15 entries.", positions.size());

			for (int i = 0; i < 15; i++) {
				positions.pop();
			}
		}
	}

	// ROS_DEBUG("enqueue: Released positions lock");
	// ROS_DEBUG("enqueue: Notifying about new CameraData");

	positionsEmpty.notify_one();

	// ROS_DEBUG("enqueue: Finished insertion process");
}

CameraData TrackingWorker::dequeue()
{
	// ROS_DEBUG("dequeue: Getting positions lock");

	{
		boost::mutex::scoped_lock lock(positionsMutex);

		// ROS_DEBUG("dequeue: Got positions lock");

		if (!dataAvailable()) {
			positionsEmpty.timed_wait(lock, boost::get_system_time() + boost::posix_time::milliseconds(100));
		}

		if (dataAvailable()) {
			CameraData data = positions.front();
			positions.pop();

			// ROS_DEBUG("dequeue: Released positions lock");
			return data;
		} else {
			CameraData data;
			data.valid = false;

			// ROS_DEBUG("dequeue: Released positions lock");
			return data;
		}
	}
}

bool TrackingWorker::dataAvailable()
{
	return positions.size() > 0;
}

bool TrackingWorker::calibrate(ChessboardData *chessboard, int camNo)
{
	return tracker.calibrate(chessboard, camNo);
}

Vector TrackingWorker::getCameraPosition(int camNo)
{
	return tracker.getPosition(camNo);
}
<|endoftext|>


<commit_before>#include <gtest/gtest.h>
#include <boost/asio.hpp>

#include "../../../src/http/client/client_connection.h"
#include "../../../src/http/client/client_traits.h"
#include "../../../src/protocol/handler_http1.h"
#include "../../../src/http/client/request.h"
#include "../../../src/http/client/response.h"
#include "../../mocks/mock_connector.h"

using client_connection_t = server::handler_http1<http::client_traits>;

http::http_request make_dumb_request() {
	static http::http_request preamble;
	preamble.protocol(http::proto_version::HTTP11);
	preamble.urihost("localhost");
	preamble.hostname("localhost:1443");
	preamble.path("/prova");
	return preamble;
}

std::string get_expected(http::http_request &req, const std::string &body){
	if(body.size())req.content_len(body.size());
	std::string ret = std::string(req.serialize());
	if(body.size()) ret += body;
	return ret;
}

TEST(client_connection_test, send_request)
{
    boost::asio::io_service io;

	auto tested_object = std::make_shared<client_connection_t>(http::proto_version::HTTP11);
	//now register a mock connector; than go on.

	std::string body{"ciao"};
	http::http_request preamble = make_dumb_request();
	std::string received_data{};
	std::string expected_request = get_expected(preamble, body);

	MockConnector::wcb write_callback = [&](dstring d){
		received_data.append(std::string(d));
	};
    auto mock = std::make_shared<MockConnector>(io, write_callback);
	mock->handler(tested_object);

	auto user_handlers = tested_object->get_user_handlers();
	auto req = user_handlers.second;

	req->headers(std::move(preamble));
	req->body("ciao");
	req->end();
	mock->io_service().run();
	ASSERT_EQ(expected_request, received_data);
}

TEST(client_connection, request_sent_event)
{
    boost::asio::io_service io;

	auto tested_object = std::make_shared<client_connection_t>(http::proto_version::HTTP11);
	bool called;
	tested_object->on_request_sent([&called](auto conn){
		called = true;
	});

	http::http_request preamble = make_dumb_request();
	MockConnector::wcb write_callback = [](dstring d){};
    auto mock = std::make_shared<MockConnector>(io, write_callback);
	mock->handler(tested_object);
	auto user_handlers = tested_object->get_user_handlers();
	auto req = user_handlers.second;
	req->headers(std::move(preamble));
	req->end();
	mock->io_service().run();
	ASSERT_TRUE(called);
}

TEST(client_connection, read_before_write_failure)
{
    boost::asio::io_service io;

	auto tested_object = std::make_shared<client_connection_t>(http::proto_version::HTTP11);
	bool called;
	tested_object->on_error([&called](auto conn, const http::connection_error &ec){
		ASSERT_EQ(ec.errc(), http::error_code::invalid_read);
		called = true;
		conn->close();
	});
	MockConnector::wcb write_callback = [](dstring){};
    auto mock = std::make_shared<MockConnector>(io, write_callback);
	mock->handler(tested_object);
	std::string unexpected_response = "HTTP/1.1 200 OK\r\n"
		"connection: keep-alive\r\n"
		"content-length: 33\r\n"
		"content-type: text/plain\r\n"
		"date: Tue, 17 May 2016 14:53:09 GMT\r\n"
		"\r\n"
		"Ave client, dummy node says hello";
	mock->read(unexpected_response);
	mock->io_service().run();
	ASSERT_TRUE(called);
}

TEST(client_connection, pingpong)
{
    boost::asio::io_service io;

	auto tested_object = std::make_shared<client_connection_t>(http::proto_version::HTTP11);
	//now register a mock connector; than go on.

	std::string body{"ciao"};
	http::http_request preamble = make_dumb_request();
	std::string received_data{};
	std::string expected_request = get_expected(preamble, body);

	MockConnector::wcb write_callback;
    auto mock = std::make_shared<MockConnector>(io, write_callback);
	bool finished_request{false};
	int  response_events{0};
	write_callback = [&, mock](dstring d)
		{
			received_data.append(std::string(d));
			if(received_data == expected_request && !finished_request)
			{
				std::string expected_response = "HTTP/1.1 200 OK\r\n"
						"connection: keep-alive\r\n"
						"content-length: 33\r\n"
						"content-type: text/plain\r\n"
						"date: Tue, 17 May 2016 14:53:09 GMT\r\n"
						"\r\n"
						"Ave client, dummy node says hello";
				finished_request = true;
				mock->read(expected_response);
			}
		};
	mock->handler(tested_object);

	auto user_handlers = tested_object->get_user_handlers();
	auto req = user_handlers.second;
	auto res = user_handlers.first;

	res->on_headers([&](auto response){
		ASSERT_EQ(response->preamble().status_code(), 200);
		++response_events;
	});

    res->on_body([&](auto r, std::unique_ptr<char[]> body, size_t s){
		std::string rcvd{body.get(), s};
		ASSERT_EQ(rcvd, "Ave client, dummy node says hello");
		++response_events;
	});

	res->on_finished([&](auto response){
		++response_events;
	});

	req->headers(std::move(preamble));
	req->body("ciao");
	req->end();
	mock->io_service().run();
	ASSERT_EQ(expected_request, received_data);
	ASSERT_TRUE(finished_request && response_events == 3);
}
<commit_msg>fixed leaks in test<commit_after>#include <gtest/gtest.h>
#include <boost/asio.hpp>

#include "../../../src/http/client/client_connection.h"
#include "../../../src/http/client/client_traits.h"
#include "../../../src/protocol/handler_http1.h"
#include "../../../src/http/client/request.h"
#include "../../../src/http/client/response.h"
#include "../../mocks/mock_connector.h"

using client_connection_t = server::handler_http1<http::client_traits>;

http::http_request make_dumb_request() {
	static http::http_request preamble;
	preamble.protocol(http::proto_version::HTTP11);
	preamble.urihost("localhost");
	preamble.hostname("localhost:1443");
	preamble.path("/prova");
	return preamble;
}

std::string get_expected(http::http_request &req, const std::string &body){
	if(body.size())req.content_len(body.size());
	std::string ret = std::string(req.serialize());
	if(body.size()) ret += body;
	return ret;
}

TEST(client_connection, send_request)
{
    boost::asio::io_service io;
	auto tested_object = std::make_shared<client_connection_t>(http::proto_version::HTTP11);
	//now register a mock connector; than go on.

	std::string body{"ciao"};
	http::http_request preamble = make_dumb_request();
	std::string received_data{};
	std::string expected_request = get_expected(preamble, body);

	MockConnector::wcb write_callback = [&](dstring d){
		received_data.append(std::string(d));
	};
    auto mock = std::make_shared<MockConnector>(io, write_callback);
	mock->handler(tested_object);

	auto user_handlers = tested_object->get_user_handlers();
	auto &req = user_handlers.second;
	auto &res = user_handlers.first;
	req->headers(std::move(preamble));
	req->body("ciao");
	req->end();
	res->abort();
	res->get_connection()->close();
	mock->io_service().run();
	ASSERT_EQ(expected_request, received_data);
}

TEST(client_connection, request_sent_event)
{
    boost::asio::io_service io;

	auto tested_object = std::make_shared<client_connection_t>(http::proto_version::HTTP11);
	bool called;
	http::http_request preamble = make_dumb_request();
	MockConnector::wcb write_callback = [](dstring d){};
    auto mock = std::make_shared<MockConnector>(io, write_callback);
	mock->handler(tested_object);
	auto user_handlers = tested_object->get_user_handlers();
	auto &req = user_handlers.second;
	auto &res = user_handlers.first;
	tested_object->on_request_sent([&called, &res](auto conn){
		called = true;
		res->abort();
	});
	req->headers(std::move(preamble));
	req->end();
	res->get_connection()->close();
	mock->io_service().run();
	ASSERT_TRUE(called);
}

TEST(client_connection, read_before_write_failure)
{
    boost::asio::io_service io;
	auto tested_object = std::make_shared<client_connection_t>(http::proto_version::HTTP11);
	MockConnector::wcb write_callback = [](dstring){};
	auto mock = std::make_shared<MockConnector>(io, write_callback);
	bool called;
	tested_object->on_error([&called, &mock](auto conn, const http::connection_error &ec){
		ASSERT_EQ(ec.errc(), http::error_code::invalid_read);
		called = true;
		conn->close();
		mock = nullptr;
	});

	mock->handler(tested_object);
	std::string unexpected_response = "HTTP/1.1 200 OK\r\n"
		"connection: keep-alive\r\n"
		"content-length: 33\r\n"
		"content-type: text/plain\r\n"
		"date: Tue, 17 May 2016 14:53:09 GMT\r\n"
		"\r\n"
		"Ave client, dummy node says hello";
	mock->read(unexpected_response);
	io.run();
	ASSERT_TRUE(called);
}

TEST(client_connection, pingpong)
{
    boost::asio::io_service io;

	auto tested_object = std::make_shared<client_connection_t>(http::proto_version::HTTP11);
	//now register a mock connector; than go on.

	std::string body{"ciao"};
	http::http_request preamble = make_dumb_request();
	std::string received_data{};
	std::string expected_request = get_expected(preamble, body);

	MockConnector::wcb write_callback;
    auto mock = std::make_shared<MockConnector>(io, write_callback);
	bool finished_request{false};
	int  response_events{0};
	write_callback = [&, mock](dstring d)
		{
			received_data.append(std::string(d));
			if(received_data == expected_request && !finished_request)
			{
				std::string expected_response = "HTTP/1.1 200 OK\r\n"
						"connection: keep-alive\r\n"
						"content-length: 33\r\n"
						"content-type: text/plain\r\n"
						"date: Tue, 17 May 2016 14:53:09 GMT\r\n"
						"\r\n"
						"Ave client, dummy node says hello";
				finished_request = true;
				mock->read(expected_response);
			}
		};
	mock->handler(tested_object);

	auto user_handlers = tested_object->get_user_handlers();
	auto req = user_handlers.second;
	auto res = user_handlers.first;

	res->on_headers([&](auto response){
		ASSERT_EQ(response->preamble().status_code(), 200);
		++response_events;
	});

    res->on_body([&](auto r, std::unique_ptr<char[]> body, size_t s){
		std::string rcvd{body.get(), s};
		ASSERT_EQ(rcvd, "Ave client, dummy node says hello");
		++response_events;
	});

	res->on_finished([&](auto response){
		++response_events;
		response->get_connection()->close();
	});

	req->headers(std::move(preamble));
	req->body("ciao");
	req->end();
	mock->io_service().run();
	ASSERT_EQ(expected_request, received_data);
	ASSERT_TRUE(finished_request && response_events == 3);
}
<|endoftext|>


<commit_before>#include <iostream>
#include <sstream>
#include <string>
#include <proto/stanc.pb.h>
#include <stan/lang/compiler.hpp>

namespace stan {
  namespace proto {
    stan::proto::StanCompileResponse compile(
      const stan::proto::StanCompileRequest& request) {
        stan::proto::StanCompileResponse response;
        std::ostringstream err_stream;
        std::istringstream stan_stream(request.model_code());
        std::ostringstream cpp_stream;

        bool valid_model = stan::lang::compile(&err_stream,
          stan_stream, cpp_stream,
          request.model_name(), request.model_file_name());
        response.set_messages(err_stream.str());
        response.set_cpp_code(cpp_stream.str());
        if (valid_model) {
          if (err_stream.tellp() == 0)
            response.set_state(stan::proto::StanCompileResponse::SUCCESS);
          else
            response.set_state(stan::proto::StanCompileResponse::WARN);
        } else {
          response.set_state(stan::proto::StanCompileResponse::ERROR);
        }
          return response;
      }
  }
}

<commit_msg>Catch exceptions thrown by stan::lang::compile<commit_after>#include <iostream>
#include <sstream>
#include <string>
#include <proto/stanc.pb.h>
#include <stan/lang/compiler.hpp>

namespace stan {
  namespace proto {
    stan::proto::StanCompileResponse compile(
      const stan::proto::StanCompileRequest& request) {

      stan::proto::StanCompileResponse response;
      std::ostringstream err_stream;
      std::istringstream stan_stream(request.model_code());
      std::ostringstream cpp_stream;

      try {
        bool valid_model = stan::lang::compile(&err_stream,
          stan_stream, cpp_stream,
          request.model_name(), request.model_file_name());
        if (valid_model) {
          if (err_stream.tellp() == 0)
            response.set_state(stan::proto::StanCompileResponse::SUCCESS);
          else
            response.set_state(stan::proto::StanCompileResponse::WARN);
        } else {
          response.set_state(stan::proto::StanCompileResponse::ERROR);
        }
      } catch(const std::exception& e) {
        response.set_state(stan::proto::StanCompileResponse::ERROR);
      }
      response.set_messages(err_stream.str());
      response.set_cpp_code(cpp_stream.str());
      return response;
    }
  }
}
<|endoftext|>


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

#include <boost/bind.hpp>

#include <oper/agent_sandesh.h>
#include <ovsdb_types.h>
#include <ovsdb_client_ssl.h>

#include <ovs_tor_agent/tor_agent_param.h>

using OVSDB::OvsdbClientSession;
using OVSDB::OvsdbClientSsl;
using OVSDB::OvsdbClientSslSession;
using OVSDB::OvsdbClientTcpSessionReader;

OvsdbClientSsl::OvsdbClientSsl(Agent *agent, TorAgentParam *params,
        OvsPeerManager *manager) :
    SslServer(agent->event_manager(), boost::asio::ssl::context::tlsv1_server),
    OvsdbClient(manager, params->keepalive_interval()), agent_(agent),
    ssl_server_port_(params->tor_port()), tsn_ip_(params->tsn_ip()),
    shutdown_(false) {
    // Get SSL context from base class and update
    boost::asio::ssl::context *ctx = context();
    boost::system::error_code ec;

    // Verify peer to have a valid certificate
    ctx->set_verify_mode((boost::asio::ssl::verify_peer |
                          boost::asio::ssl::verify_fail_if_no_peer_cert), ec);
    assert(ec.value() == 0);
    ctx->use_certificate_chain_file(params->ssl_cert(), ec);
    assert(ec.value() == 0);
    ctx->use_private_key_file(params->ssl_privkey(),
                              boost::asio::ssl::context::pem, ec);
    assert(ec.value() == 0);
    ctx->load_verify_file(params->ssl_cacert(), ec);
    assert(ec.value() == 0);
}

OvsdbClientSsl::~OvsdbClientSsl() {
}

void OvsdbClientSsl::RegisterClients() {
    Initialize(ssl_server_port_);
}

SslSession *OvsdbClientSsl::AllocSession(SslSocket *socket) {
    SslSession *session = new OvsdbClientSslSession(agent_, peer_manager_,
                                                    this, socket);
    session->set_observer(boost::bind(&OvsdbClientSsl::OnSessionEvent,
                                      this, _1, _2));
    return session;
}

void OvsdbClientSsl::OnSessionEvent(TcpSession *session,
        TcpSession::Event event) {
    OvsdbClientSslSession *ssl = static_cast<OvsdbClientSslSession *>(session);
    ssl->EnqueueEvent(event);
}

const std::string OvsdbClientSsl::protocol() {
    return "PSSL";
}

const std::string OvsdbClientSsl::server() {
    return LocalEndpoint().address().to_string();
}

uint16_t OvsdbClientSsl::port() {
    return LocalEndpoint().port();
}

Ip4Address OvsdbClientSsl::tsn_ip() {
    return tsn_ip_;
}

void OvsdbClientSsl::shutdown() {
    if (shutdown_)
        return;
    shutdown_ = true;
    OvsdbClientSslSession *ssl =
        static_cast<OvsdbClientSslSession *>(NextSession(NULL));
    while (ssl != NULL) {
        if (!ssl->IsClosed()) {
            ssl->TriggerClose();
        }
        ssl = static_cast<OvsdbClientSslSession *>(NextSession(ssl));
    }
}

OvsdbClientSession *OvsdbClientSsl::FindSession(Ip4Address ip, uint16_t port) {
    SessionKey key(ip, port);
    SessionMap::iterator it;
    if (port != 0) {
        it = session_map_.find(key);
    } else {
        it = session_map_.upper_bound(key);
    }
    if (it != session_map_.end() && it->first.first == ip) {
        return it->second;
    }
    return NULL;
}

OvsdbClientSession *OvsdbClientSsl::NextSession(OvsdbClientSession *session) {
    SessionMap::iterator it;
    if (session == NULL) {
        it = session_map_.begin();
    } else {
        OvsdbClientSslSession *ssl =
            static_cast<OvsdbClientSslSession *>(session);
        SessionKey key(ssl->remote_endpoint().address().to_v4(),
                       ssl->remote_endpoint().port());
        it = session_map_.upper_bound(key);
    }
    if (it != session_map_.end()) {
        return it->second;
    }
    return NULL;
}

void OvsdbClientSsl::AddSessionInfo(SandeshOvsdbClient &client) {
    SandeshOvsdbClientSession session;
    std::vector<SandeshOvsdbClientSession> session_list;
    OvsdbClientSslSession *ssl = static_cast<OvsdbClientSslSession *>(NextSession(NULL));
    while (ssl != NULL) {
        session.set_status(ssl->status());
        session.set_remote_ip(ssl->remote_endpoint().address().to_string());
        session.set_remote_port(ssl->remote_endpoint().port());
        session_list.push_back(session);
        ssl = static_cast<OvsdbClientSslSession *>(NextSession(ssl));
    }
    client.set_sessions(session_list);
}

// AcceptSession callback from SSLserver, to accept a session
bool OvsdbClientSsl::AcceptSession(TcpSession *session) {
    if (shutdown_) {
        // don't accept session while shutting down
        return false;
    }
    return true;
}

OvsdbClientSslSession::OvsdbClientSslSession(Agent *agent,
        OvsPeerManager *manager, OvsdbClientSsl *server, SslSocket *sock,
        bool async_ready) : OvsdbClientSession(agent, manager),
    SslSession(server, sock, async_ready), status_("Init") {

    reader_ = new OvsdbClientTcpSessionReader(this,
            boost::bind(&OvsdbClientSslSession::RecvMsg, this, _1, _2));

    // Process session events in KSync workqueue task context,
    session_event_queue_ = new WorkQueue<OvsdbSessionEvent>(
            TaskScheduler::GetInstance()->GetTaskId("Agent::KSync"), 0,
            boost::bind(&OvsdbClientSslSession::ProcessSessionEvent, this, _1));
}

OvsdbClientSslSession::~OvsdbClientSslSession() {
    delete reader_;
    session_event_queue_->Shutdown();
    delete session_event_queue_;
}

void OvsdbClientSslSession::OnRead(Buffer buffer) {
    reader_->OnRead(buffer);
}

void OvsdbClientSslSession::SendMsg(u_int8_t *buf, std::size_t len) {
    OVSDB_PKT_TRACE(Trace, "Sending: " + std::string((char *)buf, len));
    Send(buf, len, NULL);
}

bool OvsdbClientSslSession::RecvMsg(const u_int8_t *buf, std::size_t len) {
    OVSDB_PKT_TRACE(Trace, "Received: " + std::string((const char*)buf, len));
    MessageProcess(buf, len);
    return true;
}

int OvsdbClientSslSession::keepalive_interval() {
    OvsdbClientSsl *ovs_server = static_cast<OvsdbClientSsl *>(server());
    return ovs_server->keepalive_interval();
}

KSyncObjectManager *OvsdbClientSslSession::ksync_obj_manager() {
    OvsdbClientSsl *ovs_server = static_cast<OvsdbClientSsl *>(server());
    return ovs_server->ksync_obj_manager();
}

Ip4Address OvsdbClientSslSession::tsn_ip() {
    OvsdbClientSsl *ovs_server = static_cast<OvsdbClientSsl *>(server());
    return ovs_server->tsn_ip();
}

void OvsdbClientSslSession::OnCleanup() {
    OvsdbClientSsl *ovs_server = static_cast<OvsdbClientSsl *>(server());
    ovs_server->DeleteSession(this);
}

void OvsdbClientSslSession::TriggerClose() {
    // Close the session and return
    Close();

    // SSL session will not notify event for self closed session
    // generate explicit event
    EnqueueEvent(TcpSession::CLOSE);
}

Ip4Address OvsdbClientSslSession::remote_ip() {
    return remote_endpoint().address().to_v4();
}

bool OvsdbClientSslSession::ProcessSessionEvent(OvsdbSessionEvent ovs_event) {
    boost::system::error_code ec;
    switch (ovs_event.event) {
    case TcpSession::CLOSE:
        {
            OvsdbClientSsl *ovs_server =
                static_cast<OvsdbClientSsl *>(server());
            boost::asio::ip::tcp::endpoint ep = remote_endpoint();
            OvsdbClientSsl::SessionKey key(ep.address().to_v4(), ep.port());
            ovs_server->session_map_.erase(key);

            OnClose();
        }
        break;
    case TcpSession::ACCEPT:
        {
            OvsdbClientSsl *ovs_server =
                static_cast<OvsdbClientSsl *>(server());
            boost::asio::ip::tcp::endpoint ep = remote_endpoint();
            OvsdbClientSsl::SessionKey key(ep.address().to_v4(), ep.port());
            std::pair<OvsdbClientSsl::SessionMap::iterator, bool> ret =
                ovs_server->session_map_.insert
                (std::pair<OvsdbClientSsl::SessionKey,
                           OvsdbClientSslSession *>(key, this));
            // assert if entry already exists
            assert(ret.second == true);
        }
        set_status("Established");
        OnEstablish();
        break;
    default:
        assert(false);
        break;
    }
    return true;
}

void OvsdbClientSslSession::EnqueueEvent(TcpSession::Event event) {
    OvsdbSessionEvent ovs_event;
    ovs_event.event = event;
    session_event_queue_->Enqueue(ovs_event);
}

<commit_msg>Change Assertion to Exit with error<commit_after>/*
 * Copyright (c) 2015 Juniper Networks, Inc. All rights reserved.
 */

#include <boost/bind.hpp>
#include <base/logging.h>

#include <oper/agent_sandesh.h>
#include <ovsdb_types.h>
#include <ovsdb_client_ssl.h>

#include <ovs_tor_agent/tor_agent_param.h>

using OVSDB::OvsdbClientSession;
using OVSDB::OvsdbClientSsl;
using OVSDB::OvsdbClientSslSession;
using OVSDB::OvsdbClientTcpSessionReader;

OvsdbClientSsl::OvsdbClientSsl(Agent *agent, TorAgentParam *params,
        OvsPeerManager *manager) :
    SslServer(agent->event_manager(), boost::asio::ssl::context::tlsv1_server),
    OvsdbClient(manager, params->keepalive_interval()), agent_(agent),
    ssl_server_port_(params->tor_port()), tsn_ip_(params->tsn_ip()),
    shutdown_(false) {
    // Get SSL context from base class and update
    boost::asio::ssl::context *ctx = context();
    boost::system::error_code ec;

    // Verify peer to have a valid certificate
    ctx->set_verify_mode((boost::asio::ssl::verify_peer |
                          boost::asio::ssl::verify_fail_if_no_peer_cert), ec);
    assert(ec.value() == 0);

    ctx->use_certificate_chain_file(params->ssl_cert(), ec);
    if (ec.value() != 0) {
        LOG(ERROR, "Error : " << ec.message() << ", while using cert file : "
            << params->ssl_cert());
        exit(EINVAL);
    }

    ctx->use_private_key_file(params->ssl_privkey(),
                              boost::asio::ssl::context::pem, ec);
    if (ec.value() != 0) {
        LOG(ERROR, "Error : " << ec.message() << ", while using privkey file : "
            << params->ssl_privkey());
        exit(EINVAL);
    }

    ctx->load_verify_file(params->ssl_cacert(), ec);
    if (ec.value() != 0) {
        LOG(ERROR, "Error : " << ec.message() << ", while using cacert file : "
            << params->ssl_cacert());
        exit(EINVAL);
    }
}

OvsdbClientSsl::~OvsdbClientSsl() {
}

void OvsdbClientSsl::RegisterClients() {
    Initialize(ssl_server_port_);
}

SslSession *OvsdbClientSsl::AllocSession(SslSocket *socket) {
    SslSession *session = new OvsdbClientSslSession(agent_, peer_manager_,
                                                    this, socket);
    session->set_observer(boost::bind(&OvsdbClientSsl::OnSessionEvent,
                                      this, _1, _2));
    return session;
}

void OvsdbClientSsl::OnSessionEvent(TcpSession *session,
        TcpSession::Event event) {
    OvsdbClientSslSession *ssl = static_cast<OvsdbClientSslSession *>(session);
    ssl->EnqueueEvent(event);
}

const std::string OvsdbClientSsl::protocol() {
    return "PSSL";
}

const std::string OvsdbClientSsl::server() {
    return LocalEndpoint().address().to_string();
}

uint16_t OvsdbClientSsl::port() {
    return LocalEndpoint().port();
}

Ip4Address OvsdbClientSsl::tsn_ip() {
    return tsn_ip_;
}

void OvsdbClientSsl::shutdown() {
    if (shutdown_)
        return;
    shutdown_ = true;
    OvsdbClientSslSession *ssl =
        static_cast<OvsdbClientSslSession *>(NextSession(NULL));
    while (ssl != NULL) {
        if (!ssl->IsClosed()) {
            ssl->TriggerClose();
        }
        ssl = static_cast<OvsdbClientSslSession *>(NextSession(ssl));
    }
}

OvsdbClientSession *OvsdbClientSsl::FindSession(Ip4Address ip, uint16_t port) {
    SessionKey key(ip, port);
    SessionMap::iterator it;
    if (port != 0) {
        it = session_map_.find(key);
    } else {
        it = session_map_.upper_bound(key);
    }
    if (it != session_map_.end() && it->first.first == ip) {
        return it->second;
    }
    return NULL;
}

OvsdbClientSession *OvsdbClientSsl::NextSession(OvsdbClientSession *session) {
    SessionMap::iterator it;
    if (session == NULL) {
        it = session_map_.begin();
    } else {
        OvsdbClientSslSession *ssl =
            static_cast<OvsdbClientSslSession *>(session);
        SessionKey key(ssl->remote_endpoint().address().to_v4(),
                       ssl->remote_endpoint().port());
        it = session_map_.upper_bound(key);
    }
    if (it != session_map_.end()) {
        return it->second;
    }
    return NULL;
}

void OvsdbClientSsl::AddSessionInfo(SandeshOvsdbClient &client) {
    SandeshOvsdbClientSession session;
    std::vector<SandeshOvsdbClientSession> session_list;
    OvsdbClientSslSession *ssl = static_cast<OvsdbClientSslSession *>(NextSession(NULL));
    while (ssl != NULL) {
        session.set_status(ssl->status());
        session.set_remote_ip(ssl->remote_endpoint().address().to_string());
        session.set_remote_port(ssl->remote_endpoint().port());
        session_list.push_back(session);
        ssl = static_cast<OvsdbClientSslSession *>(NextSession(ssl));
    }
    client.set_sessions(session_list);
}

// AcceptSession callback from SSLserver, to accept a session
bool OvsdbClientSsl::AcceptSession(TcpSession *session) {
    if (shutdown_) {
        // don't accept session while shutting down
        return false;
    }
    return true;
}

OvsdbClientSslSession::OvsdbClientSslSession(Agent *agent,
        OvsPeerManager *manager, OvsdbClientSsl *server, SslSocket *sock,
        bool async_ready) : OvsdbClientSession(agent, manager),
    SslSession(server, sock, async_ready), status_("Init") {

    reader_ = new OvsdbClientTcpSessionReader(this,
            boost::bind(&OvsdbClientSslSession::RecvMsg, this, _1, _2));

    // Process session events in KSync workqueue task context,
    session_event_queue_ = new WorkQueue<OvsdbSessionEvent>(
            TaskScheduler::GetInstance()->GetTaskId("Agent::KSync"), 0,
            boost::bind(&OvsdbClientSslSession::ProcessSessionEvent, this, _1));
}

OvsdbClientSslSession::~OvsdbClientSslSession() {
    delete reader_;
    session_event_queue_->Shutdown();
    delete session_event_queue_;
}

void OvsdbClientSslSession::OnRead(Buffer buffer) {
    reader_->OnRead(buffer);
}

void OvsdbClientSslSession::SendMsg(u_int8_t *buf, std::size_t len) {
    OVSDB_PKT_TRACE(Trace, "Sending: " + std::string((char *)buf, len));
    Send(buf, len, NULL);
}

bool OvsdbClientSslSession::RecvMsg(const u_int8_t *buf, std::size_t len) {
    OVSDB_PKT_TRACE(Trace, "Received: " + std::string((const char*)buf, len));
    MessageProcess(buf, len);
    return true;
}

int OvsdbClientSslSession::keepalive_interval() {
    OvsdbClientSsl *ovs_server = static_cast<OvsdbClientSsl *>(server());
    return ovs_server->keepalive_interval();
}

KSyncObjectManager *OvsdbClientSslSession::ksync_obj_manager() {
    OvsdbClientSsl *ovs_server = static_cast<OvsdbClientSsl *>(server());
    return ovs_server->ksync_obj_manager();
}

Ip4Address OvsdbClientSslSession::tsn_ip() {
    OvsdbClientSsl *ovs_server = static_cast<OvsdbClientSsl *>(server());
    return ovs_server->tsn_ip();
}

void OvsdbClientSslSession::OnCleanup() {
    OvsdbClientSsl *ovs_server = static_cast<OvsdbClientSsl *>(server());
    ovs_server->DeleteSession(this);
}

void OvsdbClientSslSession::TriggerClose() {
    // Close the session and return
    Close();

    // SSL session will not notify event for self closed session
    // generate explicit event
    EnqueueEvent(TcpSession::CLOSE);
}

Ip4Address OvsdbClientSslSession::remote_ip() {
    return remote_endpoint().address().to_v4();
}

bool OvsdbClientSslSession::ProcessSessionEvent(OvsdbSessionEvent ovs_event) {
    boost::system::error_code ec;
    switch (ovs_event.event) {
    case TcpSession::CLOSE:
        {
            OvsdbClientSsl *ovs_server =
                static_cast<OvsdbClientSsl *>(server());
            boost::asio::ip::tcp::endpoint ep = remote_endpoint();
            OvsdbClientSsl::SessionKey key(ep.address().to_v4(), ep.port());
            ovs_server->session_map_.erase(key);

            OnClose();
        }
        break;
    case TcpSession::ACCEPT:
        {
            OvsdbClientSsl *ovs_server =
                static_cast<OvsdbClientSsl *>(server());
            boost::asio::ip::tcp::endpoint ep = remote_endpoint();
            OvsdbClientSsl::SessionKey key(ep.address().to_v4(), ep.port());
            std::pair<OvsdbClientSsl::SessionMap::iterator, bool> ret =
                ovs_server->session_map_.insert
                (std::pair<OvsdbClientSsl::SessionKey,
                           OvsdbClientSslSession *>(key, this));
            // assert if entry already exists
            assert(ret.second == true);
        }
        set_status("Established");
        OnEstablish();
        break;
    default:
        assert(false);
        break;
    }
    return true;
}

void OvsdbClientSslSession::EnqueueEvent(TcpSession::Event event) {
    OvsdbSessionEvent ovs_event;
    ovs_event.event = event;
    session_event_queue_->Enqueue(ovs_event);
}

<|endoftext|>


<commit_before>// Checks that the __sanitizer_on_print hook gets the exact same sanitizer
// report as what is printed to stderr.
//
// RUN: %clangxx %s -o %t
// RUN: %run %t %t-onprint.txt 2>%t-stderr.txt || true
// RUN: diff %t-onprint.txt %t-stderr.txt

#include <cassert>
#include <cstdio>
#include <cstdlib>

FILE *f;
volatile void *buf;
volatile char sink;

extern "C" void __sanitizer_on_print(const char *str) {
  fprintf(f, "%s", str);
  fflush(f);
}

int main(int argc, char *argv[]) {
  assert(argc >= 2);
  f = fopen(argv[1], "w");

  // Use-after-free to trigger ASan/TSan reports.
  void *ptr = malloc(1);
  buf = ptr;
  free(ptr);
  sink = *static_cast<char *>(ptr);
  return 0;
}
<commit_msg>[sanitizer_common] Disable onprint.cpp on Android.<commit_after>// Checks that the __sanitizer_on_print hook gets the exact same sanitizer
// report as what is printed to stderr.
//
// RUN: %clangxx %s -o %t
// RUN: %run %t %t-onprint.txt 2>%t-stderr.txt || true
// RUN: diff %t-onprint.txt %t-stderr.txt
//
// UNSUPPORTED: android

#include <cassert>
#include <cstdio>
#include <cstdlib>

FILE *f;
volatile void *buf;
volatile char sink;

extern "C" void __sanitizer_on_print(const char *str) {
  fprintf(f, "%s", str);
  fflush(f);
}

int main(int argc, char *argv[]) {
  assert(argc >= 2);
  f = fopen(argv[1], "w");

  // Use-after-free to trigger ASan/TSan reports.
  void *ptr = malloc(1);
  buf = ptr;
  free(ptr);
  sink = *static_cast<char *>(ptr);
  return 0;
}
<|endoftext|>