void CEnemyMeleeAttack::process(const std::shared_ptr<Logic::IMessage> &message)
	{
		if(message->getType() == "CONTROLLER_TOUCHED")
		{
			CEntity* other = dynamic_cast<CONTROLLER_TOUCHED*>(message.get())->getEntidad();

			if(other->getEntityID() == _targetID && _entity->getTag() == "enemy" && canDoDamage())
			{
				ApplyDamage(other);
			}
			
		}

		else if (message->getType() == "CHANGE_TARGET")
		{
			// Si no encuentra la palabra "Minion" en el tipo de entidad, entonces puede canibalizar
			if (_entity->getType().find("Minion") == std::string::npos)
			{
				_target =  dynamic_cast<CHANGE_TARGET*>(message.get())->getLogicEntity(); 

				if (_target)
					_targetID = _target->getEntityID();
			}
		}

	} // process
Example #2
0
bool UILogic::handle(const gearsbox::ViewEventParam & param, const std::shared_ptr<gearsbox::ViewGen> & view){
    if (nullptr == view){
        G_LOG_FC(LOG_ERROR, "handle event viewgen null");
        return false;
    }
    
    //G_LOG_FC(LOG_INFO, "handle event view:%s event:%d text:%s", view->getId().c_str(), param.type, param.text.c_str());
    
    if (ViewType::LABEL == view->getType()){
        
        if (m_input->getText().size() != 0)
            updateValueLabel(view->getId(), false);
        PlatformUtilityGen::instance()->getExcutor()->endEniting(true);
    }
    else if (ViewType::BASE == view->getType()){
        PlatformUtilityGen::instance()->getExcutor()->endEniting(true);
    }
    else if (ViewType::INPUT == view->getType()){
        if (view == m_input && param.text.size()>0){
            view->getText();
            m_value = atof(param.text.c_str());
            //UsnitGen::instance()->setInput(value);
            updateValueLabel("", true);
        }
    }
    
    return true;
}
void models::Property::setValue(std::shared_ptr<libConfig::ConfigValue> newVal)
{
    
    if(!value)
    {
        switch(newVal->getType())
        {
            case libConfig::ConfigValue::ARRAY:
                value.reset(new libConfig::ArrayConfigValue());
                break;
            case libConfig::ConfigValue::COMPLEX:
                value.reset(new libConfig::ComplexConfigValue());
                break;
            case libConfig::ConfigValue::SIMPLE:
                value.reset(new libConfig::SimpleConfigValue(""));
                break;
                
        }
        value->setName(getName());
    }
    
    if(value->getType() != newVal->getType())
        throw std::runtime_error("Error, configuration values may not change !");

    value = newVal;
}
Example #4
0
 std::vector<uint8_t>
 JSZCluster::addArgument(v8::Local<v8::Value> value, const std::shared_ptr<ClusterCmdParamsBase> &cmdParam) {
     if (value->IsUint32()) {
         return cmdParam->getType().getRaw(value->ToUint32()->Value());
     }
     if (value->IsInt32()) {
         return cmdParam->getType().getRaw(value->ToInt32()->Value());
     }
     if (value->IsString()) {
         String::Utf8Value utf8Value(value);
         return cmdParam->getType().getRaw(*utf8Value);
     }
     if (value->IsArray()) {
         Local<Array> array = value.As<Array>();
         std::vector<std::string> strArray;
         for (uint32_t index = 0; index < array->Length(); index++) {
             String::Utf8Value utf8Value(array->Get(index));
             strArray.push_back(*utf8Value);
         }
         return cmdParam->getType().getRaw(strArray);
     }
     stringstream stream;
     stream << "To " << EXECUTE_CMD_BY_ID << " it is passed an invalid argument instead of type "
            << cmdParam->getZCLDataType();
     throw JSException(stream.str());
 }
	bool CShieldSpecialController::accept(const std::shared_ptr<Logic::IMessage> &message)
	{
		return message->getType() == "FALLING" ||
			   message->getType() == "UP_COLLISION" ||
			   message->getType() == "SIDE_COLLISION" ||
			   message->getType() == "TOUCHED";
	} // accept
Example #6
0
bool CIADodge::accept(const std::shared_ptr<Logic::IMessage> &message)
{
    return message->getType() == "DAMAGED" ||
           message->getType() == "FALLING" ||
           message->getType() == "CHANGE_TARGET" ||
           message->getType() == "CAN_IA";
}
Example #7
0
std::string PubSubErrorSerializer::serializePayload(std::shared_ptr<PubSubError> payload) const {
    if (payload->getType() == PubSubError::UnknownType) {
        return "";
    }
    XMLElement element(serializeType(payload->getType()), "http://jabber.org/protocol/pubsub#errors");
    if (payload->getType() == PubSubError::Unsupported) {
        if (payload->getUnsupportedFeatureType() != PubSubError::UnknownUnsupportedFeatureType) {
            element.setAttribute("feature", serializeUnsupportedFeatureType(payload->getUnsupportedFeatureType()));
        }
    }
    return element.serialize();
}
Example #8
0
static void _toArray(const YAML::Node& node, std::shared_ptr<Array>& a) {
  NTA_CHECK(node.Type() == YAML::NodeType::Sequence);

  a->allocateBuffer(node.size());
  void *buffer = a->getBuffer();

  for (size_t i = 0; i < node.size(); i++) {
    const YAML::Node &item = node[i];
    NTA_CHECK(item.Type() == YAML::NodeType::Scalar);
    switch (a->getType()) {
    case NTA_BasicType_Byte:
      // We should have already detected this and gone down the string path
      NTA_THROW << "Internal error: attempting to convert YAML string to array "
                   "of type Byte";
      break;
    case NTA_BasicType_UInt16:
      ((UInt16*)buffer)[i] = item.as<UInt16>();
      break;
    case NTA_BasicType_Int16:
      ((Int16*)buffer)[i] = item.as<Int16>();
      break;
    case NTA_BasicType_UInt32:
     ((UInt32*)buffer)[i] = item.as<UInt32>();
      break;
    case NTA_BasicType_Int32:
     ((Int32*)buffer)[i] = item.as<Int32>();
      break;
    case NTA_BasicType_UInt64:
     ((UInt64*)buffer)[i] = item.as<UInt64>();
      break;
    case NTA_BasicType_Int64:
     ((Int64*)buffer)[i] = item.as<Int64>();
      break;
    case NTA_BasicType_Real32:
     ((Real32*)buffer)[i] = item.as<Real32>();
      break;
    case NTA_BasicType_Real64:
     ((Real64*)buffer)[i] = item.as<Real64>();
      break;
    case NTA_BasicType_Bool:
     ((bool*)buffer)[i] = item.as<bool>();
      break;
    default:
      // should not happen
      NTA_THROW << "Unknown data type " << a->getType();
    }
  }
}
Example #9
0
	void CLife::process(const std::shared_ptr<Logic::IMessage> &message)
	{
		if (message->getType() == "INVINCIBLE")
		{
			_invincible = dynamic_cast<INVINCIBLE*>(message.get())->getBool();
		}
	} // process
void PubSubOwnerAffiliationConvertor::doConvertToLua(lua_State* L, std::shared_ptr<PubSubOwnerAffiliation> payload) {
    lua_createtable(L, 0, 0);
    lua_pushstring(L, payload->getJID().toString().c_str());
    lua_setfield(L, -2, "jid");
    switch (payload->getType()) {
        case PubSubOwnerAffiliation::None:
            lua_pushstring(L, "none");
            break;
        case PubSubOwnerAffiliation::Member:
            lua_pushstring(L, "member");
            break;
        case PubSubOwnerAffiliation::Outcast:
            lua_pushstring(L, "outcast");
            break;
        case PubSubOwnerAffiliation::Owner:
            lua_pushstring(L, "owner");
            break;
        case PubSubOwnerAffiliation::Publisher:
            lua_pushstring(L, "publisher");
            break;
        case PubSubOwnerAffiliation::PublishOnly:
            lua_pushstring(L, "publish_only");
            break;
    }
    lua_setfield(L, -2, "type");
}
	void CAltStatesController::process(const std::shared_ptr<Logic::IMessage> &message)
	{
		if(message->getType().compare("SET_ALTSTATE") == 0)
		{
			std::string state = dynamic_cast<SET_ALTSTATE*>(message.get())->getString();

			// Buscamos a ver si ya ha contraido el estado alterado, y de ser así no hacemos nada
			bool found = false;

			for (int i = 0; i < _vecAltStates.size(); ++i)
			{
				if (_vecAltStates.at(i).name == state)
					found = true;

			}

			// Si no lo tenia ya el enemigo, se lo aplicamos
			if (!found)
			{
				AltState altState = {state, false, true, 0};

				_vecAltStates.push_back(altState);
			}

		}
	}
	void CSwordSlashController::process(const std::shared_ptr<Logic::IMessage> &message)
	{
		if((message->getType().compare("TOUCHED") == 0))
		{
			Logic::CEntity *otherEntity = dynamic_cast<TOUCHED*>(message.get())->getEntidad();

			if(otherEntity)
			{
				if (otherEntity->getTag() == "enemy")
				{
					if(_damage>0)
					{
						std::shared_ptr<DAMAGED> m(new DAMAGED());
						m->setFloat(_damage);
						m->setString(_entity->getType());
						otherEntity->emitMessage(m);

						std::shared_ptr<PUSH> pushMessage(new PUSH());
						pushMessage->setDirection(_direction);
						pushMessage->setSpeed(0.5f);
						otherEntity->emitMessage(pushMessage, this);

						//BaseSubsystems::Log::Debug("ÑAPA: " + std::to_string(_damage));
					}

					Logic::CEntityFactory::getSingletonPtr()->createEntityByType("ChispaDanhoEnemy",
						otherEntity->getCenterPosition(), 
						_entity->getMap());
				}
			}
		}
	} // process
Example #13
0
std::shared_ptr<BaseType> buildJavaNode(JNIEnv *jvEnv, std::shared_ptr<Node> node,
        std::list<std::shared_ptr<BaseType> > stack)
{
    std::shared_ptr<BaseType> obj;
    switch (node->getType()) {
        case Node::kDictionary:
            obj.reset(new DictionaryType(jvEnv));
            break;
        case Node::kCollection:
            obj.reset(new CollectionType(jvEnv));
            break;
        case Node::kInt8: case Node::kInt32: case Node::kInt64:
        case Node::kUInt8: case Node::kUInt32: case Node::kUInt64:
            obj.reset(new IntegerType(jvEnv));
            break;
        case Node::kFloat: case Node::kDouble:
            obj.reset(new DoubleType(jvEnv));
            break;
        case Node::kString:
            obj.reset(new StringType(jvEnv));
            break;
        default:
            obj.reset(new UnknownType(jvEnv));
            break;
    }

    if (stack.size() > 0) {
        std::shared_ptr<BaseType> parent = stack.back();
        parent->append(node->getName(), obj);
    }

    return obj;
}
Example #14
0
std::unique_ptr<SatelliteServer>
SatelliteServer::Create(std::shared_ptr<SatelliteServerInfo> info) {
  std::unique_ptr<SatelliteServer> satellite;
  if (info->getPort()) {
    switch (info->getType()) {
    case Type::KindOfInternalPageServer:
      satellite.reset(new InternalPageServer(info));
      break;
    case Type::KindOfDanglingPageServer:
      satellite.reset(new DanglingPageServer(info));
      break;
    case Type::KindOfRPCServer:
      satellite.reset(new RPCServer(info));
      break;
    case Type::KindOfXboxServer:
      satellite.reset(new RPCServer(info));
      break;
    default:
      assert(false);
    }
    if (satellite) {
      satellite->setName(info->getName());
    }
  }
  return satellite;
}
Example #15
0
bool ComplexConfigValue::merge(std::shared_ptr<ConfigValue> other)
{
    if(other->getType() != COMPLEX)
        return false;

    if(name != other->getName())
    {
        throw std::runtime_error("Internal Error, merge between mismatching value");
    }

    const ComplexConfigValue *cother = dynamic_cast<const ComplexConfigValue *>(other.get());
    
    for(const auto &it : cother->values)
    {
        std::map<std::string, std::shared_ptr<ConfigValue> >::iterator entry = values.find(it.first);
        if(entry != values.end())
        {
            if(!entry->second->merge(it.second))
                return false;
        }
        else
        {
            values.insert(it);
        }
    }    
    return true;
}
Example #16
0
 void GameState::onNotify(std::shared_ptr<baseEvent> e){
     switch(e->getType()){
         case EventType::LEVEL_COMPLETE:{
             if(currentLevel<(totalLevels-1)){
                 ++currentLevel;
                 eventQueue = level->getEventQueue(currentLevel);
                 gameEventDispatcher = level->getGameEventDispatcher(currentLevel);
                 gameEventDispatcher->LevelComplete.addObserver(this);
                 gameEventDispatcher->LevelFailed.addObserver(this);
                 gameEventDispatcher->UpdateScore.addObserver(this);
             }else if(currentLevel == (totalLevels-1)){
                 requestStackPush(AppStates::GameSucceed);
             }
         }
             break;
         case EventType::LEVEL_FAILED:{
             requestStackPush(AppStates::GameFailed);
         }
             break;
         case EventType::UPDATE_SCORE:{
             score += std::get<0>(e->getAttributes<EventsAlias::update_score>());
             textScore.setString(Utils::toString(score));
         }
             break;
         default:
             break;
     }
 }
Example #17
0
void
StatBucketOperation::onReceive(DistributorMessageSender& sender, const std::shared_ptr<api::StorageReply> & msg)
{
    assert(msg->getType() == api::MessageType::STATBUCKET_REPLY);
    api::StatBucketReply& myreply(dynamic_cast<api::StatBucketReply&>(*msg));

    std::map<uint64_t, uint16_t>::iterator found = _sent.find(msg->getMsgId());

    if (found != _sent.end()) {
        std::ostringstream ost;
        if (myreply.getResult().getResult() == api::ReturnCode::OK) {
            ost << "\tBucket information from node " << found->second << ":\n" << myreply.getResults() << "\n\n";
        } else {
            ost << "\tBucket information retrieval failed on node " << found->second << ": " << myreply.getResult() << "\n\n";
        }
        _results[found->second] = ost.str();

        _sent.erase(found);
    }

    if (_sent.empty()) {
        std::ostringstream ost;
        for (std::map<uint16_t, std::string>::iterator iter = _results.begin();
             iter != _results.end();
             iter++) {
            ost << iter->second;
        }

        api::StatBucketReply::SP reply(new api::StatBucketReply(*_command, ost.str()));
        sender.sendReply(reply);
    }
}
Example #18
0
bool ArrayConfigValue::merge(std::shared_ptr< ConfigValue > other)
{
    if(other->getType() != ARRAY)
        return false;

    if(name != other->getName())
    {
        throw std::runtime_error("Internal Error, merge between mismatching value");
    }
    
    const ArrayConfigValue *aother = dynamic_cast<const ArrayConfigValue *>(other.get());
    
    //we only support direct overwrite by index
    for(size_t i = 0; i < aother->values.size(); i++)
    {
        if(i < values.size())
        {
            values[i] = aother->values[i];
        }
        else
        {
            values.push_back(aother->values[i]);
        }
    }
    
    return true;
}
	void CIARunAway::process(const std::shared_ptr<Logic::IMessage> &message)
	{

		if (message->getType() == "CHANGE_TARGET")
		{
			CEntity* ent = dynamic_cast<CHANGE_TARGET*>(message.get())->getLogicEntity();
			if(ent != NULL)
			{
				if(!ent->getIsDead())
				{
					_target = ent; 
					if (_target->getCenterPosition().x > _entity->getCenterPosition().x)
					{
						_direction = -1;
					}
					else
					{
						_direction = 1;
					}
						
					std::shared_ptr<Logic::TURN> m(new Logic::TURN());
					m->setInt(_direction);
					_entity->emitMessage(m);
				}
			}  

			
		}
	} // process
bool checkSolidTileIntersection(std::shared_ptr<Tile>& tile, HitboxMovementController& object) {

    if(!object.getHitbox()) {

        return false;
    }

    TileType type = tile->getType();

    sf::FloatRect tileBoundingBox = tile->getBoundingBox();
    sf::FloatRect objBoundingBox = object.getHitbox()->getActiveHitboxWorldSpace();

    switch(type) {

        case TileType::SOLID: {

            return tileBoundingBox.intersects(objBoundingBox);
        }

        default:
            return false;
    }

    return false;
}
Example #21
0
WarningShapeNode::WarningShapeNode(std::shared_ptr<dart::dynamics::Shape> shape,
                                   ShapeFrameNode* parent)
  : ShapeNode(shape, parent, this)
{
  dtwarn << "Shape type (" << shape->getType()
         << ") found in Entity '" << parent->getName()
         << "' is not currently supported by dart::gui::osg, "
         << "and will not be rendered\n";
}
Example #22
0
	void CGraphics::process(const std::shared_ptr<Logic::IMessage> &message)
	{
		if(message->getType().compare("SET_MATERIAL") == 0)
		{
			std::string nameMat = dynamic_cast<SET_MATERIAL*>(message.get())->getString();

			_graphicsEntity->setMaterial(nameMat);
		}

	} // process
Vector3d RandomPointGenerator::pointOnShape(std::shared_ptr<SurgSim::Math::Shape> shape)
{
	SURGSIM_ASSERT(shape != nullptr) << "Empty shape passed in.";

	auto shapeType = shape->getType();
	SURGSIM_ASSERT(SurgSim::Math::SHAPE_TYPE_NONE < shapeType && shapeType < SurgSim::Math::SHAPE_TYPE_COUNT) <<
		"Unknown shape type passed in.";

	return m_pointGenerators[shapeType]->pointOnShape(shape);
}
Example #24
0
static void _toScalar(const YAML::Node &node, std::shared_ptr<Scalar> &s) {
  NTA_CHECK(node.Type() == YAML::NodeType::Scalar);
  switch (s->getType()) {
  case NTA_BasicType_Byte:
    // We should have already detected this and gone down the string path
    NTA_THROW << "Internal error: attempting to convert YAML string to scalar of type Byte";
    break;
  case NTA_BasicType_UInt16:
    s->value.uint16 = node.as<UInt16>();
    break;
  case NTA_BasicType_Int16:
    s->value.int16 = node.as<Int16>();
    break;
  case NTA_BasicType_UInt32:
    s->value.uint32 = node.as<UInt32>();
    break;
  case NTA_BasicType_Int32:
    s->value.int32 = node.as<Int32>();
    break;
  case NTA_BasicType_UInt64:
    s->value.uint64 = node.as<UInt64>();
    break;
  case NTA_BasicType_Int64:
    s->value.int64 = node.as<Int64>();
    break;
  case NTA_BasicType_Real32:
    s->value.real32 = node.as<Real32>();
    break;
  case NTA_BasicType_Real64:
    s->value.real64 = node.as<Real64>();
    break;
  case NTA_BasicType_Bool:
    s->value.boolean = node.as<bool>();
    break;
  case NTA_BasicType_Handle:
    NTA_THROW << "Attempt to specify a YAML value for a scalar of type Handle";
    break;
  default:
    // should not happen
    const std::string val = node.as<std::string>();
    NTA_THROW << "Unknown data type " << s->getType() << " for yaml node '" << val << "'";
  }
}
Example #25
0
std::shared_ptr<XMLElement> FormSerializer::fieldToXML(std::shared_ptr<FormField> field, bool withTypeAttribute) const {
    std::shared_ptr<XMLElement> fieldElement(new XMLElement("field"));
    if (!field->getName().empty()) {
        fieldElement->setAttribute("var", field->getName());
    }
    if (!field->getLabel().empty()) {
        fieldElement->setAttribute("label", field->getLabel());
    }
    if (field->getRequired()) {
        fieldElement->addNode(std::make_shared<XMLElement>("required"));
    }
    if (!field->getDescription().empty()) {
        std::shared_ptr<XMLElement> descriptionElement(new XMLElement("desc"));
        descriptionElement->addNode(std::make_shared<XMLTextNode>(field->getDescription()));
        fieldElement->addNode(descriptionElement);
    }

    // Set the value and type
    std::string fieldType;
    switch (field->getType()) {
        case FormField::UnknownType: fieldType = ""; break;
        case FormField::BooleanType: fieldType = "boolean"; break;
        case FormField::FixedType: fieldType = "fixed"; break;
        case FormField::HiddenType: fieldType = "hidden"; break;
        case FormField::ListSingleType: fieldType = "list-single"; break;
        case FormField::TextMultiType: fieldType = "text-multi"; break;
        case FormField::TextPrivateType: fieldType = "text-private"; break;
        case FormField::TextSingleType: fieldType = "text-single"; break;
        case FormField::JIDSingleType: fieldType = "jid-single"; break;
        case FormField::JIDMultiType: fieldType = "jid-multi"; break;
        case FormField::ListMultiType: fieldType = "list-multi"; break;
    }
    if (!fieldType.empty() && withTypeAttribute) {
        fieldElement->setAttribute("type", fieldType);
    }
    for (const auto& value : field->getValues()) {
        std::shared_ptr<XMLElement> valueElement = std::make_shared<XMLElement>("value");
        valueElement->addNode(std::make_shared<XMLTextNode>(value));
        fieldElement->addNode(valueElement);
    }

    for (const auto& option : field->getOptions()) {
        std::shared_ptr<XMLElement> optionElement(new XMLElement("option"));
        if (!option.label.empty()) {
            optionElement->setAttribute("label", option.label);
        }

        std::shared_ptr<XMLElement> valueElement(new XMLElement("value"));
        valueElement->addNode(XMLTextNode::create(option.value));
        optionElement->addNode(valueElement);
        fieldElement->addNode(optionElement);
    }
    return fieldElement;
}
Example #26
0
RippleState::pointer
RippleState::makeItem (
    AccountID const& accountID,
        std::shared_ptr<SLE const> sle)
{
    // VFALCO Does this ever happen in practice?
    if (! sle || sle->getType () != ltRIPPLE_STATE)
        return {};
    return std::make_shared<RippleState>(
        std::move(sle), accountID);
}
Example #27
0
bool ExpDotWriter::postVisit(const std::shared_ptr<TypedExp> &exp)
{
    *m_os << "e_" << HostAddress(exp.get()) << " [shape=record,label=\"{";
    *m_os << "opTypedExp\\n" << HostAddress(exp.get()) << " | ";
    // Just display the C type for now
    *m_os << exp->getType()->getCtype() << " | <p1>";
    *m_os << " }\"];\n";
    *m_os << "e_" << HostAddress(exp.get()) << ":p1->e_" << HostAddress(exp->getSubExp1().get())
          << ";\n";

    return true;
}
    std::shared_ptr<Format> TwicAccessControlCardService::readFormat(std::shared_ptr<Format> format, std::shared_ptr<Location> location, std::shared_ptr<AccessInfo> /*aiToUse*/)
    {
        bool ret = false;

        std::shared_ptr<Format> formatret;
        if (format)
        {
            formatret = Format::getByFormatType(format->getType());
            formatret->unSerialize(format->serialize(), "");
        }
        else
        {
            formatret.reset(new FASCN200BitFormat());
        }

        std::shared_ptr<TwicLocation> pLocation;
        if (location)
        {
            pLocation = std::dynamic_pointer_cast<TwicLocation>(location);
        }
        else
        {
            if (std::dynamic_pointer_cast<FASCN200BitFormat>(formatret))
            {
                pLocation.reset(new TwicLocation());
                pLocation->dataObject = 0x5FC104;
                pLocation->tag = 0x30;
            }
        }

        if (pLocation)
        {
            size_t length = (formatret->getDataLength() + 7) / 8;
			std::vector<unsigned char> formatBuf;

            std::shared_ptr<StorageCardService> storage = std::dynamic_pointer_cast<StorageCardService>(getTwicChip()->getService(CST_STORAGE));
            if (storage)
            {
                formatBuf = storage->readData(pLocation, std::shared_ptr<AccessInfo>(), length, CB_DEFAULT);
                formatret->setLinearData(&formatBuf[0], formatBuf.size());

                ret = true;
            }
        }

        if (!ret)
        {
            formatret.reset();
        }

        return formatret;
    }
Example #29
0
void ConstraintElement::flattenAndFilter(const std::shared_ptr<OSSIA::StateElement>& element)
{
    if (!element)
        return;
    
    switch (element->getType())
    {
        case OSSIA::StateElement::Type::MESSAGE :
        {
            std::shared_ptr<OSSIA::Message> messageToAppend = std::dynamic_pointer_cast<OSSIA::Message>(element);
            
            // find message with the same address to replace it
            bool found = false;
            for (auto it = m_state_on_play->stateElements().begin();
                 it != m_state_on_play->stateElements().end();
                 it++)
            {
                std::shared_ptr<OSSIA::Message> messageToCheck = std::dynamic_pointer_cast<OSSIA::Message>(*it);
                
                // replace if addresses are the same
                if (messageToCheck->getAddress() == messageToAppend->getAddress())
                {
                    *it = element;
                    found = true;
                    break;
                }
            }
            
            // if not found append it
            if (!found)
                m_state_on_play->stateElements().push_back(element);
            
            break;
        }
        case OSSIA::StateElement::Type::STATE :
        {
            std::shared_ptr<OSSIA::State> stateToFlatAndFilter = std::dynamic_pointer_cast<OSSIA::State>(element);
            
            for (const auto& e : stateToFlatAndFilter->stateElements())
            {
                flattenAndFilter(e);
            }
            break;
        }
            
        default:
        {
            m_state_on_play->stateElements().push_back(element);
            break;
        }
    }
}
Example #30
0
std::string FormSerializer::serializePayload(std::shared_ptr<Form> form)  const {
    if (!form) {
        return "";
    }

    std::shared_ptr<XMLElement> formElement(new XMLElement("x", "jabber:x:data"));
    std::string type;
    switch (form->getType()) {
        case Form::FormType: type = "form"; break;
        case Form::SubmitType: type = "submit"; break;
        case Form::CancelType: type = "cancel"; break;
        case Form::ResultType: type = "result"; break;
    }
    formElement->setAttribute("type", type);
    if (!form->getTitle().empty()) {
        multiLineify(form->getTitle(), "title", formElement);
    }
    if (!form->getInstructions().empty()) {
        multiLineify(form->getInstructions(), "instructions", formElement);
    }
    for (const auto& page : form->getPages()) {
        formElement->addNode(pageToXML(page));
    }
    for (const auto& field : form->getFields()) {
        formElement->addNode(fieldToXML(field, true));
    }
    if (!form->getReportedFields().empty()) {
        std::shared_ptr<XMLElement> reportedElement(new XMLElement("reported"));
        for (const auto& field : form->getReportedFields()) {
            reportedElement->addNode(fieldToXML(field, true));
        }
        formElement->addNode(reportedElement);
    }

    for (const auto& item : form->getItems()) {
        std::shared_ptr<XMLElement> itemElement(new XMLElement("item"));
        for (const auto& field : item) {
            itemElement->addNode(fieldToXML(field, false));
        }
        formElement->addNode(itemElement);
    }

    for (const auto& text : form->getTextElements()) {
        formElement->addNode(textToXML(text));
    }

    for (const auto& field : fields_) {
        formElement->addNode(fieldToXML(field,true));
    }

    return formElement->serialize();
}