Recently in doing PROTOBUF related projects, which used the dynamic analysis, on-line read the relevant information and blog are relatively few, to write a record of their own learning process. Protocol buffers is a structured data format standard that provides serialization and deserialization methods for storage and exchange. Language neutral, platform-independent, extensible. Currently, the official provides C + +, Java, Python API, and other languages of open source APIs (such as PHP).available through . Protothe file generates the class code for the corresponding languageIf you know which class object the Protobuf content corresponds to, you can use the deserialization method directly (Xxx.parsefrom (InputStream) is converted by binary, Textformat.merge (string, Xxxbuilder) Converted by text) and what we often encounter is that we get a binary content that is serialized by Protobuf, but we don't know its type and cannot get the corresponding class object. This is seen in systems that need to handle a wide variety of unknown protobuf objects. PROTOBUF provides a dynamic parsing mechanism to solve this problem, it requires the provision of binary content, and then provides the corresponding class of descriptor object, at the time of parsing through the Dynamicmessage class member method to obtain the object result. The final question is where does the descriptor object come from? This is achieved by Protoc--descriptor_set_out= $outputpath command to generate the descriptor file. The code is as follows:
1Option java_package= "Com.liulei.cinema";2 3 enummovietype{4Children=1;5adult=2;6Normal=3;7Ohter=4;8 }9 Ten enumgender{ OneMan=1; Awoman=2; -Other=3; - } the - message movie{ -Required String name=1; -Required Movietype type=2; +Optional Int32 releasetimestamp=3; -Optional String description=4; + } A at message customer{ -Required String name=1; -Optional Gender gender=2; -Optional Int32 birthdaytimestamp=3; - } - in message ticket{ -Required Int32 id=1; toRequired Movie movie=2; +Required Customer customer=3; -}Cinema.proto
1 Public Static voidMain (string[] args) {2 3Cinema.Movie.Builder Moviebuilder =Cinema.Movie.newBuilder ();4Moviebuilder.setname ("The Shining");5 Moviebuilder.settype (Cinema.MovieType.ADULT);6Moviebuilder.setreleasetimestamp (327859200);7 8System.out.println ("Dynamic Message Parse by Proto file");9 Try {Ten byte[] Buffer3 =New byte[Moviebuilder.build (). Getserializedsize ()]; OneCodedoutputstream CODEDOUTPUTSTREAM3 =codedoutputstream.newinstance (buffer3); A Try { - moviebuilder.build (). WriteTo (CODEDOUTPUTSTREAM3); - System.out.println (buffer3); the}Catch(IOException e) { - e.printstacktrace (); - } -String protoccmd = "Protoc--descriptor_set_out=cinema.description./cinema.proto--proto_path=."; +Process Process =runtime.getruntime (). exec (protoccmd); - process.waitfor (); + intExitvalue =Process.exitvalue (); A if(Exitvalue! = 0) { atSystem.out.println ("Protoc Execute Failed"); - return; - } -Descriptors.descriptor Pbdescritpor =NULL; -Descriptorprotos.filedescriptorset Descriptorset = DescriptorProtos.FileDescriptorSet.parseFrom (NewFileInputStream ("./cinema.description")); - for(Descriptorprotos.filedescriptorproto fdp:descriptorSet.getFileList ()) { inDescriptors.filedescriptor filedescriptor = Descriptors.FileDescriptor.buildFrom (FDP,Newdescriptors.filedescriptor[]{}); - for(Descriptors.descriptor descriptor:fileDescriptor.getMessageTypes ()) { to if(Descriptor.getname (). Equals ("Movie")) { +SYSTEM.OUT.PRINTLN ("Movie descriptor found"); -Pbdescritpor =descriptor; the Break; * } $ }Panax Notoginseng } - if(Pbdescritpor = =NULL) { theSystem.out.println ("No matched descriptor"); + return; A } theDynamicmessage.builder Pbbuilder =Dynamicmessage.newbuilder (Pbdescritpor); + -Message Pbmessage =Pbbuilder.mergefrom (BUFFER3). build (); $ System.out.println (pbmessage); $ -}Catch(Exception e) { -System.out.println ("Exception"); the e.printstacktrace (); - }Wuyi}Main.javaExecution Result:
Dynamic Message Parse from byte array
[[email protected]
Movie descriptor found
Name: "The Shining"
Type:adult
releasetimestamp:327859200
Explain the process: 0. Use the PROTOC command for the. proto file first, and the resulting descriptor file contains the Descriptor class information for the multiple classes (serialized Descriptorset content) 1. First remove the serialized descriptorset content, Filede The Scriptorset.parsefrom method deserializes the Filedescriptorset object by 2. Remove the descriptor that corresponds to the message type. The Descriptorset member Method Getfilelist (), gets multiple Filedescriptorproto objects, and then constructs the corresponding filedescriptor. The member method of the FileDescriptor getmessagetypes () obtains the descriptor object of all the message, and finds the Descriptor3 of the corresponding name. Deserializing objects with Descriptor objects Build the Dynamicmessage.builder object Builder, and then call the builder's Mergefrom/merge method to get the message object Where descriptor related classes: DescriptorProtos.DescriptorSet:protoc compiled class file containing this class, describes the multiple. proto files in the class Descriptorprotos.filedescriptorproto: Description Class Descriptorprotos.filedescriptor in a complete. Proto file: Constructed by Descriptorprotos.filedescriptorproto (Buildfrom), describes all the contents of 1 complete. Proto files , including the message type of descriptor and other descriptor of the imported file.Getmessagetypes() Method: ReturnsList<Descriptors.descriptor>. Get filedescriptor inside, all message types Direct Son's descriptor List Descriptorprotos.descriptor: Describes a message type, through GetName () Please specify the source of the class name of the message to be reproduced. Welcome to shoot Bricks ~
PROTOBUF application of dynamic parsing in Java contains example programs