PB中扩展嵌套结构

http://aboutfedora.blogspot.com/2012/10/protobuf-examples-for-c-and-java-1.html

Protobuf Examples for C++ and Java (1)

This sample .proto is taken from http://blog.wolfman.com/articles/2011/11/23/how-to-implement-polymorphic-protocol-buffers-in-java. The groovy is rewritten in Java and C++. Also see  example 2

example.proto


package example;

option java_outer_classname = "Commands";

message BaseCommand {
        extensions 100 to max;

        enum CommandType {
                VERSION = 1;
                LOGIN   = 2;
        }
        required CommandType type = 1;
}


message Version {
        extend BaseCommand {
                required Version cmd = 100;
        }

        required fixed32 protocol = 1;
        required fixed32 versions = 2;
}

message Login {
        extend BaseCommand {
                required Login cmd = 101;
        }
        required string username = 1;
        required string password = 2;
}

example.cpp


#include 
#include "example.pb.h"
using namespace std;
using namespace example;

int main()
{
  string sl;


  BaseCommand b;


#if 0
  Version ver;
  ver.set_versions(10);
  ver.set_protocol(15);

  
  b.MutableExtension(Version::cmd)->set_versions(10);
  b.MutableExtension(Version::cmd)->set_protocol(15);

  b.set_type( BaseCommand::VERSION);
#else
  b.set_type( BaseCommand::LOGIN);

  b.MutableExtension(Login::cmd)->set_username("rain");
  b.MutableExtension(Login::cmd)->set_password("heavy");
  

#endif
  b.SerializeToString(&sl);


  printf("%d\n", sl.length());

  BaseCommand* bcmd = new BaseCommand();
  if (bcmd->ParseFromString(sl))
  {
    printf("ParsePartialFromString ok\n");
  }
  

  printf("%d\n", bcmd->type());
  switch(bcmd->type())
  {
    case BaseCommand::LOGIN:
    {
      printf("login\n");
      printf("%s %s\n", b.MutableExtension(Login::cmd)->username().c_str(), b.MutableExtension(Login::cmd)->password().c_str());

      break;
    }
    case BaseCommand::VERSION:
    {
      printf("version\n");


      printf("%d %d\n", b.MutableExtension(Version::cmd)->versions(), b.MutableExtension(Version::cmd)->protocol());
      break;
    }
    default:
      break;
  }

  return 1;
}

example.java


import example.Commands;
import example.Commands.BaseCommand;
import com.google.protobuf.GeneratedMessage;
import com.google.protobuf.ExtensionRegistry;
import java.io.IOException;

 
class ProtoBufExample {
        // Helper which wraps the BaseCommand around the extension command
        static  BaseCommand wrap(BaseCommand.CommandType type, GeneratedMessage.GeneratedExtension extension, Type cmd) {
                return BaseCommand.newBuilder().setType(type).setExtension(extension, cmd).build();
        }
 
        ExtensionRegistry registry;
 
        ProtoBufExample() {
                // we need to register all the extensions and tell the decoder about them
                // otherwise the extension will be ignored
                registry= ExtensionRegistry.newInstance();
                Commands.registerAllExtensions(registry);
        }
 
        BaseCommand buildVersion(int v1, int v2) {
                Commands.Version vers= Commands.Version.newBuilder().setProtocol(v1).setVersions(v2).build();
                // BaseCommand bcmd= BaseCommand.newBuilder().setType(BaseCommand.CommandType.VERSION).setExtension(Commands.Version.cmd, vers).build();
                return wrap(BaseCommand.CommandType.VERSION, Commands.Version.cmd, vers);
        }
 
        BaseCommand buildLogin(String username, String password) {
                Commands.Login l= Commands.Login.newBuilder().setUsername(username).setPassword(password).build();
                return wrap(BaseCommand.CommandType.LOGIN, Commands.Login.cmd, l);
        }
 
        BaseCommand decodeIt(byte [] ba) {
                // use the registry so extensions will be decoded
            try{
                BaseCommand b=BaseCommand.newBuilder().mergeFrom(ba, registry).build();
                return b;
            }
            catch (IOException e) {
                System.out.println("Unable to create  " +e.getMessage());
                return buildVersion(0,1);
            }

        }

 
    public static void main(String[] args) throws Exception {
        ProtoBufExample pb= new ProtoBufExample();
        BaseCommand b= pb.buildVersion(1234, 5678);
        //BaseCommand b= pb.buildLogin("user1", "test");
 
        System.out.println(b);
        System.out.println ("size: " + b.toByteArray().length);
 
        BaseCommand decoded= pb.decodeIt(b.toByteArray());
 
        System.out.println ("We got a "+ decoded.getType() +" message");
 
        // We can switch on the CommandType enum and extract the specific command type (extension) we got
        switch(decoded.getType()) {
        case VERSION:
            System.out.println (decoded.getExtension(Commands.Version.cmd));
            break;
                
        case LOGIN:
            System.out.println (decoded.getExtension(Commands.Login.cmd));
            break;
 
        default:
            System.out.println ("Don't know this type");
        }
    }
    
}

FirCmpt组件库1.0: PB专用组件,内容如下: 1.Z01库 应用库 2.WinApi库 Window提供的API函数的包装对象库包含以下组件。 TAPI 该对象提供了一些API函数。 TDialog 基本对象框控件。 TColorDialog 颜色对象框。 TFolderDialog 选择一个目录 TFontDialog 选择一种字体 TOpenDialog 选择一个已存在的文件。 TSaveDialog 选择要保存的文件。 TSystemTime 系统时间操作 3.FirCmpts库 Fir组件,有字符串管理与操作对象,可视化容器对象,分隔条对象,屏幕对象。 TList 基本列表管理对象,可用于管理多种不同类型的数据或对象的对象。 TStrings 基本字符串管理对象。 TCompartStringList 是TStrings的扩充,可以指定分隔符。 TStringList 是TStrings的扩充,可以给每一个串命名。 TVisualManager 可视化对象的管理对象,可以管理一组Fir组件或PB的可视化组件。 TComponent 基本组件对象,该对象有基本的排列方式属性 TPanel 是TComponent的扩充,该对象是基本容器。可以容纳其它的可视化对象或TPanel对象(任何从TComponent继承的对象)。 Tcontrol 单一容器对象,可容纳一个可视化对象或Fir可视对象,将容纳的对象的大小设置与自己一样。 TSpliterBar 分隔条对象 TScreen对象 没什么特殊的地方,可以取到当前屏幕的分辨率。 TExchange 数制转换对象。 TForm对象 基本的窗口对象,以上的可视化对象都必须放置在TForm继承的窗口才会有作用。 4.Types库 一些Fir组件用到的基本结构类型。 TComponentInfo 组件信息。 TGraphObjectInfo PB可视化组件信息。 TObjectInfo Fir对象信息。 TPointer 表示一个点的坐标。 TRecBrush 一个Windows 基本刷子结构 TRecSystemTime Windows系统时间操作结构 TRect 表示一个矩形范围。 TRectangle 同上。 TRectPos 同上。 5.ZhtBase库 Fir原始组件库。 TBaseComponent, TBaseObject, TExternal, TObject, TVisual。 6.Functions 库 一些常用函数。 checkComponent 检查一个对象是否是Fir组件。 ConvertRect 转换一个矩形范围(PB单位与象素转换) FindStr 查找一个串是否有指定的子串。 FormatStr, gf_Format 得到格式化字符串。 gf_Connect 通过加密的口令进行数据库连接。 gf_PipeLine 执行数据管道 HyperLink 执行一个超链接。 ReplaceStr 把一个串指定的子替换为另一种子串。 具体了例子可以运行程序。 有好建议请与我联系 _z_h_t_@163.com
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值