Esempio n. 1
0
static int 
_mongoproxy_cmd(MongoOP op, const google::protobuf::Message & msg, bool update,
                const dcorm::MongoOPReq * ex, const char * cb_data , int cb_size){
	mongo_msg_t mongo_msg;
	mongo_msg.set_op(op);
	mongo_msg.set_db(msg.GetDescriptor()->file()->package());
	mongo_msg.set_coll(msg.GetDescriptor()->name());
    if (cb_data && cb_size > 0){
        mongo_msg.set_cb(cb_data, cb_size);
    }
	string json;
	pbjson::pb2json(&msg, json);
	GLOG_TRA("pb2json :%s", json.c_str());
    if (ex){
        mongo_msg.mutable_req()->MergeFrom(*ex);
    }
	if (update){
		mongo_msg.mutable_req()->set_u(json);
	}
	else {
		mongo_msg.mutable_req()->set_q(json);
	}
	if (!mongo_msg.Pack(MONGO.msg_buffer)){
		GLOG_WAR("pack error :%s", mongo_msg.Debug());
		return -1;
	}
	return dcnode_send(MONGO.dc, "", MONGO.msg_buffer.buffer, MONGO.msg_buffer.valid_size);
}
Esempio n. 2
0
/** Send a message.
 * @param client ID of the client to addresss
 * @param m Message to send, the message must have an CompType enum type to
 * specify component ID and message type.
 */
void
ProtobufStreamServer::send(ClientID client, google::protobuf::Message &m)
{
  const google::protobuf::Descriptor *desc = m.GetDescriptor();
  const google::protobuf::EnumDescriptor *enumdesc = desc->FindEnumTypeByName("CompType");
  if (! enumdesc) {
    throw std::logic_error("Message does not have CompType enum");
  }
  const google::protobuf::EnumValueDescriptor *compdesc =
    enumdesc->FindValueByName("COMP_ID");
  const google::protobuf::EnumValueDescriptor *msgtdesc =
    enumdesc->FindValueByName("MSG_TYPE");
  if (! compdesc || ! msgtdesc) {
    throw std::logic_error("Message CompType enum hs no COMP_ID or MSG_TYPE value");
  }
  int comp_id = compdesc->number();
  int msg_type = msgtdesc->number();
  if (comp_id < 0 || comp_id > std::numeric_limits<uint16_t>::max()) {
    throw std::logic_error("Message has invalid COMP_ID");
  }
  if (msg_type < 0 || msg_type > std::numeric_limits<uint16_t>::max()) {
    throw std::logic_error("Message has invalid MSG_TYPE");
  }

  send(client, comp_id, msg_type, m);
}
Esempio n. 3
0
	Handle<Object> ParsePart(const google::protobuf::Message &message) {
		HandleScope scope;
		const Reflection* r = message.GetReflection();
		const Descriptor* descriptor = message.GetDescriptor();

		Local<Array> properties = Array::New(descriptor->field_count());
		for (int i = 0; i < descriptor->field_count(); i++) {
			const FieldDescriptor* field = descriptor->field(i);
			bool repeated = field->is_repeated();
			if (repeated && !r->FieldSize(message, field)) continue;
			if (!repeated && !r->HasField(message, field)) continue;

			Handle<Value> value;
			if (field->is_repeated()) {
				int size = r->FieldSize(message, field);
				Handle<Array> array = Array::New(size);
				for (int j = 0; j < size; j++)
					array->Set(j, ParseField(message, r, field, j));
				value = array;
			} else {
				value = ParseField(message, r, field, -1);
			}

			if (value->IsNull()) continue;

			properties->Set(i, value);
		}

		Local<Function> from_array = handle_->GetInternalField(2).As<Function>();

		Handle<Value> args = properties;
		return scope.Close(from_array->NewInstance(1, &args));
	}
Esempio n. 4
0
void SoapServerInternal::CallMethod(const string& serviceName, const string& methodName, const google::protobuf::Message& request, SoapProtocol::ResponseCallback callback)
{
  Log(string("<ProtobuOutboundReq>") + request.DebugString() + "</ProtobuOutboundReq>");

  map<string, ServiceBinding>::iterator it = m_soapMappings.find(serviceName);

  if (it == m_soapMappings.end())
  {
    throw exception("Cant find service binding");
  }

  lock_guard<mutex> guard(m_protocolLock);
  map<string, SoapProtocol*>::iterator sp = m_protocolBindings.begin();

  //if (sp == m_protocolBindings.end())
  //{
  //  throw exception("Cant find protocol binding");
  //}

  tinyxml2::XMLDocument doc;

  ClassBinding& binding = GetClassBinding(request.GetDescriptor());
  tinyxml2::XMLElement* resp = binding.GetProtobufHelper()->GenerateRequest(methodName, request, doc);

  string actionUrl = it->second.GetActionUrl() + "/" + methodName;
  sp->second->SendRequest(actionUrl, doc, resp, callback);
}
Esempio n. 5
0
void ProtobufBsonFormatter::formatMessage(const google::protobuf::Message& message,
    BSONObjBuilder& builder) {
    const google::protobuf::Reflection* reflection = message.GetReflection();
    const google::protobuf::Descriptor* descriptor = message.GetDescriptor();

    int fieldCnt = descriptor->field_count();

    for (int i = 0; i < fieldCnt; ++i) {
        bool serialized = formatField(message, descriptor->field(i), builder);
    }
}
Esempio n. 6
0
Try<Nothing> checkpoint(
    const string& path,
    const google::protobuf::Message& message)
{
  std::cout << "Checkpointing " << message.GetDescriptor()->name()
            << " to '" << path << "'" << std::endl;

  // Create the base directory.
  Try<Nothing> result = os::mkdir(os::dirname(path).get());
  if (result.isError()) {
    return Error("Failed to create directory '" + os::dirname(path).get() +
                 "': " + result.error());
  }

  // Now checkpoint the protobuf to disk.
  result = ::protobuf::write(path, message);
  if (result.isError()) {
    return Error("Failed to checkpoint \n" + message.DebugString() +
                 "\n to '" + path + "': " + result.error());
  }

  return Nothing();
}
bool ProtobufTree::addTreeData(QTreeWidgetItem* parent,
                               const google::protobuf::Message& msg) {
    const Reflection* ref = msg.GetReflection();

    // Get fields in the message
    vector<const FieldDescriptor*> fields;
    ref->ListFields(msg, &fields);

    // Get map of field numbers to child items
    FieldMap fieldMap =
        parent->data(Column_Tag, FieldMapRole).value<FieldMap>();

    bool newFields = false;

    // Clear data for missing fields
    const Descriptor* desc = msg.GetDescriptor();
    for (FieldMap::const_iterator i = fieldMap.begin(); i != fieldMap.end();
         ++i) {
        const FieldDescriptor* field = desc->FindFieldByNumber(i.key());
        if (!field) {
            // Field has left the descriptor - should never happen
            printf("Lost field %s.%d\n", desc->name().c_str(), i.key());
            continue;
        }

        QTreeWidgetItem* item = i.value();

        bool hasData;
        if (field->is_repeated()) {
            hasData = ref->FieldSize(msg, field);

            if (!hasData && item->childCount()) {
                // Remove and delete children
                for (QTreeWidgetItem* child : item->takeChildren()) {
                    delete child;
                }
            }
        } else {
            hasData = ref->HasField(msg, field);
        }

        if (!hasData) {
            item->setText(Column_Value, QString());
            item->setData(Column_Value, Qt::CheckStateRole, QVariant());
        }
    }

    for (const FieldDescriptor* field : fields) {
        // Get the item for this field if the field has been seen before
        QTreeWidgetItem* item;
        FieldMap::iterator fieldIter = fieldMap.find(field->number());
        if (fieldIter != fieldMap.end()) {
            // Field is already in parent
            item = *fieldIter;
        } else {
            // New field
            item = new QTreeWidgetItem(parent);
            fieldMap.insert(field->number(), item);

            item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
            parent->setData(Column_Tag, FieldMapRole,
                            QVariant::fromValue<FieldMap>(fieldMap));
            item->setData(Column_Tag, Qt::DisplayRole, field->number());
            item->setData(Column_Tag, FieldDescriptorRole,
                          QVariant::fromValue(field));
            item->setText(Column_Field, QString::fromStdString(field->name()));

            if (field->type() == FieldDescriptor::TYPE_MESSAGE &&
                !field->is_repeated()) {
                // Singular messages are expanded by default
                expandItem(item);
            }

            newFields = true;
        }

        if (field->is_repeated()) {
            // Repeated field
            int n = ref->FieldSize(msg, field);

            // Show the number of elements as the value for the field itself
            item->setData(Column_Value, Qt::DisplayRole, n);

            // Make sure we have enough children
            int children = item->childCount();
            if (children < n) {
                // Add children
                for (int i = children; i < n; ++i) {
                    QTreeWidgetItem* child = new QTreeWidgetItem(item);
                    child->setText(Column_Field, QString("[%1]").arg(i));

                    child->setData(Column_Tag, FieldDescriptorRole, field);

                    // For repeated items, the tag column holds the index in the
                    // field
                    child->setData(Column_Tag, Qt::DisplayRole, i);

                    // A FieldMap is not used here because the items don't
                    // actually have tags. The item's position in its parent is
                    // its position in the repeated field.
                }

                newFields = true;
            } else if (children > n) {
                // Remove excess children
                // Internally, QTreeWidgetItem stores a QList of children.
                // Hopefully this is efficient.
                QList<QTreeWidgetItem*> kids = item->takeChildren();
                for (int i = 0; i < (children - n); ++i) {
                    delete kids.back();
                    kids.pop_back();
                }
                item->addChildren(kids);
            }

            // Set data for children
            for (int i = 0; i < n; ++i) {
                QTreeWidgetItem* child = item->child(i);

                switch (field->type()) {
                    case FieldDescriptor::TYPE_INT32:
                    case FieldDescriptor::TYPE_SINT32:
                    case FieldDescriptor::TYPE_FIXED32:
                    case FieldDescriptor::TYPE_SFIXED32:
                        child->setData(Column_Value, Qt::DisplayRole,
                                       ref->GetRepeatedInt32(msg, field, i));
                        break;

                    case FieldDescriptor::TYPE_INT64:
                    case FieldDescriptor::TYPE_SINT64:
                    case FieldDescriptor::TYPE_FIXED64:
                    case FieldDescriptor::TYPE_SFIXED64:
                        child->setData(
                            Column_Value, Qt::DisplayRole,
                            (qlonglong)ref->GetRepeatedInt64(msg, field, i));
                        break;

                    case FieldDescriptor::TYPE_UINT32:
                        child->setData(Column_Value, Qt::DisplayRole,
                                       ref->GetRepeatedUInt32(msg, field, i));
                        break;

                    case FieldDescriptor::TYPE_UINT64:
                        child->setData(
                            Column_Value, Qt::DisplayRole,
                            (qulonglong)ref->GetRepeatedUInt64(msg, field, i));
                        break;

                    case FieldDescriptor::TYPE_FLOAT:
                        child->setData(Column_Value, Qt::DisplayRole,
                                       ref->GetRepeatedFloat(msg, field, i));
                        break;

                    case FieldDescriptor::TYPE_DOUBLE:
                        child->setData(Column_Value, Qt::DisplayRole,
                                       ref->GetRepeatedDouble(msg, field, i));
                        break;

                    case FieldDescriptor::TYPE_BOOL:
                        child->setCheckState(Column_Value,
                                             ref->GetRepeatedBool(msg, field, i)
                                                 ? Qt::Checked
                                                 : Qt::Unchecked);
                        break;

                    case FieldDescriptor::TYPE_ENUM: {
                        const EnumValueDescriptor* ev =
                            ref->GetRepeatedEnum(msg, field, i);
                        child->setText(Column_Value,
                                       QString::fromStdString(ev->name()));
                        break;
                    }

                    case FieldDescriptor::TYPE_STRING:
                        child->setText(Column_Value, QString::fromStdString(
                                                         ref->GetRepeatedString(
                                                             msg, field, i)));
                        break;

                    case FieldDescriptor::TYPE_MESSAGE:
                        child->setData(Column_Tag, IsMessageRole, true);
                        newFields |= addTreeData(
                            child, ref->GetRepeatedMessage(msg, field, i));
                        break;

                    case FieldDescriptor::TYPE_BYTES:
                        addBytes(child, ref->GetRepeatedString(msg, field, i));
                        break;

                    default:
                        child->setText(Column_Value,
                                       QString("??? %1").arg(field->type()));
                        break;
                }
            }
        } else
            switch (field->type()) {
                case FieldDescriptor::TYPE_INT32:
                case FieldDescriptor::TYPE_SINT32:
                case FieldDescriptor::TYPE_FIXED32:
                case FieldDescriptor::TYPE_SFIXED32:
                    item->setData(Column_Value, Qt::DisplayRole,
                                  ref->GetInt32(msg, field));
                    break;

                case FieldDescriptor::TYPE_INT64:
                case FieldDescriptor::TYPE_SINT64:
                case FieldDescriptor::TYPE_FIXED64:
                case FieldDescriptor::TYPE_SFIXED64:
                    item->setData(Column_Value, Qt::DisplayRole,
                                  (qlonglong)ref->GetInt64(msg, field));
                    break;

                case FieldDescriptor::TYPE_UINT32:
                    item->setData(Column_Value, Qt::DisplayRole,
                                  ref->GetUInt32(msg, field));
                    break;

                case FieldDescriptor::TYPE_UINT64:
                    item->setData(Column_Value, Qt::DisplayRole,
                                  (qulonglong)ref->GetUInt64(msg, field));
                    break;

                case FieldDescriptor::TYPE_FLOAT:
                    item->setData(Column_Value, Qt::DisplayRole,
                                  ref->GetFloat(msg, field));
                    break;

                case FieldDescriptor::TYPE_DOUBLE:
                    item->setData(Column_Value, Qt::DisplayRole,
                                  ref->GetDouble(msg, field));
                    break;

                case FieldDescriptor::TYPE_BOOL:
                    item->setCheckState(Column_Value, ref->GetBool(msg, field)
                                                          ? Qt::Checked
                                                          : Qt::Unchecked);
                    break;

                case FieldDescriptor::TYPE_ENUM: {
                    const EnumValueDescriptor* ev = ref->GetEnum(msg, field);
                    item->setText(Column_Value,
                                  QString::fromStdString(ev->name()));
                    break;
                }

                case FieldDescriptor::TYPE_STRING:
                    item->setText(
                        Column_Value,
                        QString::fromStdString(ref->GetString(msg, field)));
                    break;

                case FieldDescriptor::TYPE_MESSAGE:
                    item->setData(Column_Tag, IsMessageRole, true);
                    newFields |= addTreeData(item, ref->GetMessage(msg, field));
                    break;

                case FieldDescriptor::TYPE_BYTES:
                    addBytes(item, ref->GetString(msg, field));
                    break;

                default:
                    item->setText(Column_Value,
                                  QString("??? %1").arg(field->type()));
                    break;
            }
    }

    return newFields;
}
Esempio n. 8
0
void DynamicParse::ReadDesAndInsert(const google::protobuf::Message& message, 	Map_Message*& map_content)
{
	map_content = new Map_Message;

	const google::protobuf::Descriptor* des = message.GetDescriptor();
	const google::protobuf::Reflection* refl = message.GetReflection();
	int count = des->field_count();
	for (int i=0; i<count; ++i)
	{
		const google::protobuf::FieldDescriptor* field_des = des->field(i);
		string str_name = field_des->name();


		StructValue* str_value = new StructValue;
		str_value->type1 = field_des->label();
		str_value->type2 = field_des->type();
		str_value->key_name = str_name;

		map_content->insert(make_pair(str_name, str_value));

		//repeated
		if (field_des->is_repeated())
		{
//			HTREEITEM hSubItem = m_tree.InsertItem(str_name.c_str(),hItem);
			int field_size = refl->FieldSize(message, field_des);
			for (int j=0; j<field_size; ++j)
			{	

	//			CString str_show;

				if (field_des->type() == FieldDescriptor::TYPE_STRING 
					|| field_des->type() == FieldDescriptor::TYPE_BYTES)
				{
					//str_show.Format("[%d]%s", j, (refl->GetRepeatedString(message, field_des, j)).c_str());
					//hSubItem = m_tree.InsertItem((LPCSTR)str_show, hSubItem);

					str_value->vec_value.push_back(refl->GetRepeatedString(message, field_des, j));
				}
				else if (field_des->type() == FieldDescriptor::TYPE_MESSAGE)
				{
					//str_show.Format("[%d]", j);
					//HTREEITEM hItem_temp = m_tree.InsertItem((LPCSTR)str_show, hSubItem);
					const google::protobuf::Message& msg_sub = refl->GetRepeatedMessage(message, field_des, j);
					//ReadDesAndInsert(msg_sub, hItem_temp);

					Map_Message* map_msg;
					ReadDesAndInsert(msg_sub, map_msg);
					str_value->vec_message.push_back(map_msg);
				}
				else
				{
					char value[128] = {0};
			//		uint64 temp_value = 0;
					switch (field_des->type())
					{
					case FieldDescriptor::TYPE_INT32:
						//itoa(refl->GetRepeatedInt32(message, field_des, j), value, 10);
						sprintf(value, "%d", refl->GetRepeatedInt32(message, field_des, j));
						break;
					case FieldDescriptor::TYPE_UINT32:
						//itoa(refl->GetRepeatedUInt32(message, field_des, j), value, 10);
						sprintf(value, "%u", refl->GetRepeatedUInt32(message, field_des, j));
						break;
					case FieldDescriptor::TYPE_INT64:
						//_i64toa(refl->GetRepeatedInt64(message, field_des, j), value, 10);
						sprintf(value, "%lld", refl->GetRepeatedInt64(message, field_des, j));
						break;
					case FieldDescriptor::TYPE_UINT64:
						//_ui64toa(refl->GetRepeatedUInt64(message, field_des, j), value, 10);
						sprintf(value, "%llu", refl->GetRepeatedUInt64(message, field_des, j));
						break;
					default:
						break;
					}
					//str_show.Format("[%d]%I64u", j, temp_value);
					//m_tree.InsertItem((LPCSTR)str_show, hSubItem);
			//		str_show.Format("%I64u", temp_value);
			//		string val_temp = str_show;
					str_value->vec_value.push_back(string(value));
				}
			}
		}
		else
		{
//			CString str_show;
			if (field_des->type() == FieldDescriptor::TYPE_STRING 
				|| field_des->type() == FieldDescriptor::TYPE_BYTES)
			{
				//str_show.Format("[%s]%s", str_name.c_str(), (refl->GetString(message, field_des)).c_str());
				//m_tree.InsertItem((LPCSTR)str_show, hItem);
				str_value->vec_value.push_back(refl->GetString(message, field_des));
			}
			else if (field_des->type() == FieldDescriptor::TYPE_MESSAGE)
			{
				//str_show.Format("%s", str_name.c_str());
				//HTREEITEM hSubItem = m_tree.InsertItem((LPCSTR)str_show, hItem);
				const google::protobuf::Message& msg_sub = refl->GetMessage(message, field_des);
				//ReadDesAndInsert(msg_sub, hSubItem);

				Map_Message* map_msg;
				ReadDesAndInsert(msg_sub, map_msg);
				str_value->vec_message.push_back(map_msg);
			}
			else
			{
				char value[128] = {0};
			//	string val_temp;
			//	ULONGLONG temp_value = 0;
				switch (field_des->type())
				{
				case FieldDescriptor::TYPE_INT32:
					//_itoa(refl->GetInt32(message, field_des), value, 10);
					sprintf(value, "%d", refl->GetInt32(message, field_des));
					break;
				case FieldDescriptor::TYPE_UINT32:
					//_itoa(refl->GetUInt32(message, field_des), value, 10);
					sprintf(value, "%u", refl->GetUInt32(message, field_des));
					break;
				case FieldDescriptor::TYPE_INT64:
					//_i64toa(refl->GetInt64(message, field_des), value, 10);
					sprintf(value, "%llu", refl->GetInt64(message, field_des));
					break;
				case FieldDescriptor::TYPE_UINT64:
					//_ui64toa(refl->GetUInt64(message, field_des), value, 10);
					sprintf(value, "%llu", refl->GetUInt64(message, field_des));
					break;
				default:
					break;
				}
				//str_show.Format("[%s]%I64u", str_name.c_str(), temp_value);
				//m_tree.InsertItem((LPCSTR)str_show, hItem);

			//	str_show.Format("%I64u", temp_value);
			//	string val_temp = str_show;
				str_value->vec_value.push_back(string(value));
			}
		}
	}
}
int MachinetalkService::recurseMessage(const google::protobuf::Message &message, QObject *object, const QString &tempDir, const QString &fieldFilter)
{
    Q_ASSERT(object != nullptr);

    const bool filterEnabled = !fieldFilter.isEmpty();
    bool isPosition = false;
    const gpb::Reflection *reflection = message.GetReflection();
    gpb::vector< const gpb::FieldDescriptor * > output;
    reflection->ListFields(message, &output);

    if (message.GetDescriptor() == machinetalk::File::descriptor())  // handle files with binary data
    {
        machinetalk::File file;
        file.MergeFrom(message);
        fileToObject(file, object, tempDir);
        return static_cast<int>(output.size());
    }
    else if (message.GetDescriptor() == machinetalk::Position::descriptor()) // handle position vectors
    {
        isPosition = true;
    }

    for (const gpb::FieldDescriptor *field: output)
    {
        const auto &name = QByteArray::fromStdString(field->camelcase_name());

        if ((name == "index") || (filterEnabled && (name != fieldFilter))) {
            continue;
        }

        if (!field->is_repeated())
        {
            if (field->cpp_type() != gpb::FieldDescriptor::CPPTYPE_MESSAGE)
            {
                const auto &value = simpleFieldValueToVariant(message, field);
                object->setProperty(name, value);
                if (isPosition) {
                    object->setProperty(QString::number(field->index()).toLocal8Bit(), value);
                }
            }
            else {
                QObject *memberObject = qvariant_cast<QObject *>(object->property(name));
                Q_ASSERT(memberObject != nullptr);
                recurseMessage(reflection->GetMessage(message, field), memberObject, tempDir);
            }

        }
        else if (field->cpp_type() == gpb::FieldDescriptor::CPPTYPE_MESSAGE)
        {
            if (field->message_type()->field_count() != 2) // not only index and value field
            {
                updateComplexRepeatedField(object, message, field, tempDir);
            }
            else {
                updateSimpleRepeatedField(object, message, field);
            }
        }
    }

    return static_cast<int>(output.size());
}
Esempio n. 10
0
void CMetadata::toProtobuf(google::protobuf::Message &message)
{
	//protobuf
	const google::protobuf::Reflection	*pReflection = message.GetReflection();
	const google::protobuf::Descriptor	*pDescriptor = message.GetDescriptor();
	google::protobuf::FieldDescriptor	*pFieldDescriptor = NULL;
	std::string tmpStr;
	std::string NameStr;

	for(int i = 0; i < pDescriptor->field_count(); i++) {
		
		pFieldDescriptor = (google::protobuf::FieldDescriptor *)pDescriptor->field(i);
		
		NameStr = pFieldDescriptor->name();
		if (!m_members.HasMember(NameStr.data()))
			continue;

		if (pFieldDescriptor->is_repeated()) {
			if (this->isFieldVec(m_members[NameStr.data()])) {
				switch(pFieldDescriptor->cpp_type())
				{
					case google::protobuf::FieldDescriptor::CPPTYPE_INT32:
						for(int idx = 0; idx < this->_getVecCount(m_members[NameStr.data()]); ++idx) {
							pReflection->AddInt32(&message, pFieldDescriptor, this->getFieldInt(m_members[NameStr.data()][idx]));
						}
						break;
					case google::protobuf::FieldDescriptor::CPPTYPE_INT64:
						for(int idx = 0; idx < this->_getVecCount(m_members[NameStr.data()]); ++idx) {
							pReflection->AddInt64(&message, pFieldDescriptor, this->getFieldI64(m_members[NameStr.data()][idx]));
						}
						break;
					case google::protobuf::FieldDescriptor::CPPTYPE_STRING:
						for(int idx = 0; idx < this->_getVecCount(m_members[NameStr.data()]); ++idx) {
							pReflection->AddString(&message, pFieldDescriptor,this->getFieldStr(m_members[NameStr.data()][idx]));
						}
						break;
					default:
						return;
				}
			}
		} else {
			switch(pFieldDescriptor->cpp_type())
			{
				case google::protobuf::FieldDescriptor::CPPTYPE_INT32:
					if (this->isFieldInt(m_members[NameStr.data()])) {
						pReflection->SetInt32(&message, pFieldDescriptor, this->getFieldInt(m_members[NameStr.data()]));	
					}
					break;
				case google::protobuf::FieldDescriptor::CPPTYPE_INT64:
					if (this->isFieldI64(m_members[NameStr.data()])) {
						pReflection->SetInt64(&message, pFieldDescriptor, this->getFieldI64(m_members[NameStr.data()]));
					}
					break;
				case google::protobuf::FieldDescriptor::CPPTYPE_STRING:
					if (this->isFieldStr(m_members[NameStr.data()])) {
						tmpStr.assign(this->getFieldStr(m_members[NameStr.data()]));
						pReflection->SetString(&message, pFieldDescriptor, tmpStr);
					}
					break;
				default:
					return;
			}
		}
	}
}
GameEventStorageItem::GameEventStorageItem(const ::google::protobuf::Message &_event, int _playerId, EventRecipients _recipients)
	: event(new GameEvent), recipients(_recipients)
{
	event->GetReflection()->MutableMessage(event, _event.GetDescriptor()->FindExtensionByName("ext"))->CopyFrom(_event);
	event->set_player_id(_playerId);
}
void GameEventStorage::setGameEventContext(const ::google::protobuf::Message &_gameEventContext)
{
	delete gameEventContext;
	gameEventContext = new GameEventContext;
	gameEventContext->GetReflection()->MutableMessage(gameEventContext, _gameEventContext.GetDescriptor()->FindExtensionByName("ext"))->CopyFrom(_gameEventContext);
}
Esempio n. 13
0
void parseMessageToFILE(const google::protobuf::Message& message, FILE* output, int tabcount = 0) {
    using google::protobuf::FieldDescriptor;
    using google::protobuf::UnknownField;
    using google::protobuf::UnknownFieldSet;
    using google::protobuf::EnumValueDescriptor;

    auto* reflection = message.GetReflection();
    auto* descriptor = message.GetDescriptor();
    size_t expected_size = descriptor->field_count();
    std::vector< const FieldDescriptor* > ref_fields; // array of known fields in the message
    UnknownFieldSet unknown_fields;

    ref_fields.reserve(expected_size);

    for (int i=0, n=descriptor->field_count(); i<n; ++i) {
        auto* field_desc = descriptor->field(i);
        ref_fields.push_back(field_desc);
    }

    fprintf(output, "%s\n", /*std::string(tabcount,' ').c_str(),*/ message.GetTypeName().c_str());
    ++tabcount;
    for(const auto& ref : ref_fields) {
        switch(ref->cpp_type()) {
        case FieldDescriptor::CPPTYPE_INT32 : {
            if (ref->is_repeated()) {
                printRepeatedType(reflection->GetRepeatedField<google::protobuf::int32>(message, ref), ref->camelcase_name(), output, tabcount);
            }else {
                printType(reflection->GetInt32(message, ref), ref->camelcase_name(), output, tabcount);
            }
        } break;
        case FieldDescriptor::CPPTYPE_INT64  : {
            if (ref->is_repeated()) {
                printRepeatedType(reflection->GetRepeatedField<google::protobuf::int64>(message, ref), ref->camelcase_name(), output, tabcount);
            }else {
                printType(reflection->GetInt64(message, ref), ref->camelcase_name(), output, tabcount);
            }
        } break;
        case FieldDescriptor::CPPTYPE_UINT32 : {
            if (ref->is_repeated()) {
                printRepeatedType(reflection->GetRepeatedField<google::protobuf::uint32>(message, ref), ref->camelcase_name(), output, tabcount);
            }else {
                printType(reflection->GetUInt32(message, ref), ref->camelcase_name(), output, tabcount);
            }
        } break;
        case FieldDescriptor::CPPTYPE_UINT64 : {
            if (ref->is_repeated()) {
                printRepeatedType(reflection->GetRepeatedField<google::protobuf::uint64>(message, ref), ref->camelcase_name(), output, tabcount);
            }else {
                printType(reflection->GetUInt64(message, ref), ref->camelcase_name(), output, tabcount);
            }
        } break;
        case FieldDescriptor::CPPTYPE_DOUBLE : {
            if (ref->is_repeated()) {
                printRepeatedType(reflection->GetRepeatedField<double>(message, ref), ref->camelcase_name(), output, tabcount);
            }else {
                printType(reflection->GetDouble(message, ref), ref->camelcase_name(), output, tabcount);
            }
        } break;
        case FieldDescriptor::CPPTYPE_FLOAT  : {
            if (ref->is_repeated()) {
                printRepeatedType(reflection->GetRepeatedField<float>(message, ref), ref->camelcase_name(), output, tabcount);
            }else {
                printType(reflection->GetFloat(message, ref), ref->camelcase_name(), output, tabcount);
            }
        } break;
        case FieldDescriptor::CPPTYPE_BOOL   : {
            if (ref->is_repeated()) {
                printRepeatedType(reflection->GetRepeatedField<bool>(message, ref), ref->camelcase_name(), output, tabcount);
            }else {
                printType(reflection->GetBool(message, ref), ref->camelcase_name(), output, tabcount);
            }
        } break;
        case FieldDescriptor::CPPTYPE_ENUM   : {
            // Enums are a little akward...
            if (ref->is_repeated()) {
                for (int i=0, n=reflection->FieldSize(message, ref); i<n; ++i) {
                    printTypeArray(*reflection->GetEnum(message, ref), ref->camelcase_name(), output, tabcount, i);
                }
            }else {
                printType(*reflection->GetEnum(message, ref), ref->camelcase_name(), output, tabcount);
            }
        } break;
        case FieldDescriptor::CPPTYPE_STRING : {
            //TODO: Output binary as HEX numbers.
            // can't print bytes 
            if (ref->type() == FieldDescriptor::TYPE_BYTES) {
                fprintf(output, "%s%s=<BINARY DATA>\n", std::string(tabcount,' ').c_str(), ref->camelcase_name().c_str());
                break;
            }
            if (ref->is_repeated()) {
                printRepeatedType(reflection->GetRepeatedPtrField<std::string>(message, ref), ref->camelcase_name(), output, tabcount);
            }else {
                printType(reflection->GetString(message, ref), ref->camelcase_name(), output, tabcount);
            }
        } break;
        case FieldDescriptor::CPPTYPE_MESSAGE: {
            if (ref->is_repeated()) {
                printRepeatedType(reflection->GetRepeatedPtrField<google::protobuf::Message>(message, ref), ref->camelcase_name(), output, tabcount);
            }else {
                printType(reflection->GetMessage(message, ref), ref->camelcase_name(), output, tabcount);
            }
        } break;
        }
    }
}
Esempio n. 14
0
int			
protobuf_msg_to_xml_string(const google::protobuf::Message & msg, std::string & sxml){
    protobuf_msg_sax(msg.GetDescriptor()->name(), msg, convert_to_xml, &sxml);
    dcs::strrereplace(sxml, "\\s*\n", "\n");
    return 0;
}
Esempio n. 15
0
bool ProtoMessageToXmlWithoutRoot(
    const google::protobuf::Message& message,
    std::string* xml_string,
    std::string* error)
{
    using namespace std;
    using namespace google::protobuf;

    const Reflection* reflection = message.GetReflection();
    const Descriptor* descriptor = message.GetDescriptor();

    vector<const FieldDescriptor*> fields;
    for (int i = 0; i < descriptor->extension_range_count(); i++) {
        const Descriptor::ExtensionRange* ext_range = descriptor->extension_range(i);
        for (int tag_number = ext_range->start; tag_number < ext_range->end; tag_number++) {
            const FieldDescriptor* field = reflection->FindKnownExtensionByNumber(tag_number);
            if (field) {
                fields.push_back(field);
            }
        }
    }
    for (int i = 0; i < descriptor->field_count(); i++) {
        fields.push_back(descriptor->field(i));
    }

    for (size_t i = 0; i < fields.size(); i++) {
        const FieldDescriptor* field = fields[i];
        if (!field->is_repeated() && !reflection->HasField(message, field)) {
            if (field->is_required()) {
                if (error)
                    error->assign("missed required field " + field->full_name() + ".");
                return false;
            }
            continue;
        }

        switch (field->cpp_type()) {
#define CASE_FIELD_TYPE(cpptype, method, ToString, as_binary)           \
            case FieldDescriptor::CPPTYPE_##cpptype:  {                 \
                if (field->is_repeated()) {                             \
                    int field_size = reflection->FieldSize(message, field); \
                    for (int index = 0; index < field_size; ++index) {  \
                        AppendAsXml(                                    \
                            field->name(), ToString(                    \
                                reflection->GetRepeated##method(message, field, index)), \
                            xml_string, as_binary);                     \
                    }                                                   \
                } else {                                                \
                    AppendAsXml(                                        \
                        field->name(), ToString(                        \
                            reflection->Get##method(message, field)),   \
                        xml_string, as_binary);                         \
                }                                                       \
                break;                                                  \
            }

            CASE_FIELD_TYPE(INT32,  Int32,  SimpleItoa, false);
            CASE_FIELD_TYPE(INT64,  Int64,  SimpleItoa, false);
            CASE_FIELD_TYPE(UINT32, UInt32, SimpleItoa, false);
            CASE_FIELD_TYPE(UINT64, UInt64, SimpleItoa, false);
            CASE_FIELD_TYPE(FLOAT,  Float,  SimpleFtoa, false);
            CASE_FIELD_TYPE(DOUBLE, Double, SimpleDtoa, false);
            CASE_FIELD_TYPE(STRING, String, SimpleStoa, true);

#undef CASE_FIELD_TYPE

        case FieldDescriptor::CPPTYPE_ENUM: {
            if (field->is_repeated()) {
                int field_size = reflection->FieldSize(message, field);
                for (int index = 0; index < field_size; index++) {
                    AppendAsXml(
                        field->name(),
                        SimpleItoa(reflection->GetRepeatedEnum(message, field, index)->number()),
                        xml_string);
                }
            } else {
                AppendAsXml(
                    field->name(),
                    SimpleItoa(reflection->GetEnum(message, field)->number()),
                    xml_string);
            }
            break;
        }

        case FieldDescriptor::CPPTYPE_BOOL: {
            if (field->is_repeated()) {
                int field_size = reflection->FieldSize(message, field);
                for (int index = 0; index < field_size; index++) {
                    AppendAsXml(
                        field->name(),
                        reflection->GetRepeatedBool(message, field, index) ? "true" : "false",
                        xml_string);
                }
            } else {
                AppendAsXml(
                    field->name(),
                    reflection->GetBool(message, field) ? "true" : "false",
                    xml_string);
            }
            break;
        }

        case FieldDescriptor::CPPTYPE_MESSAGE: {
            if (field->is_repeated()) {
                int field_size = reflection->FieldSize(message, field);
                for (int index = 0; index < field_size; index++) {
                    StringAppend(xml_string, '<', field->name(), '>');
                    if (!ProtoMessageToXmlWithoutRoot(
                            reflection->GetRepeatedMessage(message, field, index), xml_string, error)) {
                        return false;
                    }
                    StringAppend(xml_string, "</", field->name(), '>');
                }
            } else {
                StringAppend(xml_string, '<', field->name(), '>');
                if (!ProtoMessageToXmlWithoutRoot(
                        reflection->GetMessage(message, field), xml_string, error)) {
                    return false;
                }
                StringAppend(xml_string, "</", field->name(), '>');
            }
            break;
        }

        } ///< switch
    } ///< for

    return true;
}
Esempio n. 16
0
mori::TcpConnBuffer						Codec::Encode( const google::protobuf::Message& msg, const SEncodeContext& context )
{
	assert(msg.IsInitialized());

	CodecProtocol::Codec encodeMsg;
	encodeMsg.set_msgname(msg.GetDescriptor()->full_name());
	encodeMsg.set_clienttype(context.ClientType_);
	if ( context.UserID_ )
	{
		encodeMsg.set_userid(*context.UserID_);
	}
	if ( context.VerifyCode_ )
	{
		encodeMsg.set_verifycode(*context.VerifyCode_);
	}

	std::string msgBuf;
	msg.SerializeToString(&msgBuf);

	auto bContinue = true;
	auto step = 0;
	while ( bContinue )
	{	
		switch (step)
		{
		case 0:
			{
				if ( !context.AESKey_.empty() )
				{
					msgBuf = FastEncrypt::AES_CBCEncrypt(context.AESKey_, msgBuf);
					encodeMsg.set_aeskey(context.AESKey_);
				}

				++step;
			}break;
		case 1:
			{
				if ( !context.RSAKey_.empty() && !context.AESKey_.empty() )
				{
					auto EncryptAESKey = FastEncrypt::RSA_PubEncrypt(context.RSAKey_, context.AESKey_);
					encodeMsg.mutable_aeskey()->swap(EncryptAESKey);
					encodeMsg.set_rsaencode(true);
				}

				++step;
			}
			break;
		case 2:
			{
				if ( context.Compress_ )
				{
					auto compSize = compressBound(msgBuf.size());
					std::string tmpbuf;
					tmpbuf.resize(compSize);

					auto err = compress(reinterpret_cast<Bytef*>(&tmpbuf[0]), &compSize, reinterpret_cast<const Bytef*>(msgBuf.data()), msgBuf.size());
					if ( Z_OK != err )
					{
						assert(0);
						bContinue = false;
					}
					else
					{
						encodeMsg.set_rawsize(msgBuf.size());

						msgBuf.clear();
						tmpbuf.resize(compSize);
						
						msgBuf.swap(tmpbuf);
					}
				}

				++step;
			}
			break;
		default:
			{
				bContinue = false;
			}
			break;
		}
	}

	mori::TcpConnBuffer ret(sizeof(uint32_t)+encodeMsg.ByteSize());

	encodeMsg.SerializeToArray(ret.data()+sizeof(uint32_t), ret.size()-sizeof(uint32_t));
	
	uint32_t* pSize = reinterpret_cast<uint32_t*>(ret.data());
	*pSize = boost::asio::detail::socket_ops::host_to_network_long(encodeMsg.ByteSize());

	ret.reserve(ret.size()+msgBuf.size());
	std::copy(msgBuf.begin(), msgBuf.end(), std::back_inserter(ret));

	return std::move(ret);
}
Esempio n. 17
0
void CMetadata::fromProtobuf(google::protobuf::Message& message)
{
	//protobuf
	const google::protobuf::Reflection *pReflection = message.GetReflection();
	const google::protobuf::Descriptor *pDescriptor = message.GetDescriptor();
	google::protobuf::FieldDescriptor *pFieldDescriptor = NULL;
	std::string NameStr;
	int32  FieldNum;

	for(int i = 0; i < pDescriptor->field_count(); i++){

		pFieldDescriptor = (google::protobuf::FieldDescriptor *)pDescriptor->field(i);

		NameStr = pFieldDescriptor->name();
		if (!m_members.HasMember(NameStr.data()))
			continue;

		if (pFieldDescriptor->is_repeated()) {
			if (this->isFieldVec(m_members[NameStr.data()])) {
				switch(pFieldDescriptor->cpp_type())
				{
					case google::protobuf::FieldDescriptor::CPPTYPE_INT32:
						for(FieldNum = 0; FieldNum < pReflection->FieldSize(message, pFieldDescriptor); FieldNum++){
							this->setFieldVec(NameStr, FieldNum, (int)pReflection->GetRepeatedInt32(message, pFieldDescriptor, FieldNum));
						}
						break;
					case google::protobuf::FieldDescriptor::CPPTYPE_INT64:
						for(FieldNum = 0; FieldNum < pReflection->FieldSize(message, pFieldDescriptor); FieldNum++){
							this->setFieldVec(NameStr, FieldNum, (int64)pReflection->GetRepeatedInt64(message, pFieldDescriptor, FieldNum));
						}
						break;
					case google::protobuf::FieldDescriptor::CPPTYPE_STRING:
						for(FieldNum = 0; FieldNum < pReflection->FieldSize(message, pFieldDescriptor); FieldNum++){
							this->setFieldVec(NameStr, FieldNum, pReflection->GetRepeatedString(message, pFieldDescriptor, FieldNum).c_str());
						}
						break;
					default:
						return;
				}
			}
		} else {
			switch(pFieldDescriptor->cpp_type())
			{
				case google::protobuf::FieldDescriptor::CPPTYPE_INT32:
					if (this->isFieldInt(m_members[NameStr.data()])) {
						this->setFieldInt(NameStr, pReflection->GetInt32(message, pFieldDescriptor));
					}
					break;
				case google::protobuf::FieldDescriptor::CPPTYPE_INT64:
					if (this->isFieldI64(m_members[NameStr.data()])) {
						this->setFieldI64(NameStr, pReflection->GetInt64(message, pFieldDescriptor));
					}
					break;
				case google::protobuf::FieldDescriptor::CPPTYPE_STRING:
					if (this->isFieldStr(m_members[NameStr.data()])) {
						this->setFieldString(NameStr, pReflection->GetString(message, pFieldDescriptor));
					}
					break;
				default:
					return;
			}
		}
	}
}