Sunday, November 25, 2012

Google Protocol Buffers, JX-RS & Maven


             1.    Purpose:

Protocol buffers are Google's language-neutral, platform-neutral, extensible mechanism for serializing structured data – think XML, but smaller, faster, and simpler. You define how you want your data to be structured once and then you can use special generated source code to easily write and read your structured data to and from a variety of data streams. Protocol Buffers are a way of encoding structured data in an efficient yet extensible format. Google uses Protocol Buffers for almost all of its internal RPC protocols and file formats. The blow languages support reading/writing data via Google protocol buffers. 

·         C++
·         JAVA
·         Python 

2.    Prerequisite :

·         Create a web service project. I am using maven for web project creation.
·         Here is an example Maven base JX-RS resteasy web service project.
·         After updating the dependencies for spring security we have the latest pom.xml.

3.    Development:

·         First we will create a (.proto) file(s).This File(s) will represent object and we can compile (.proto) file into class (es) of any of above mentioned languages. I am going to choose java for this tutorial.
·         After creating a maven base web project and installing jx-rs web service into that project. I am creating a user.proto file and I will compile it to make UserDTO.java. Server and client side program will use this file to as stream to communicate (read/write data). 
·         To use start add Add dependency Google Protocol Buffers in pom.xml.
 <dependency>  
<groupId>com.google.protobuf</groupId>   
<artifactId>protobuf-java</artifactId>   
<version>2.4.1</version>   
</dependency>
·         Create a file user.proto. You can see the details under the link.
                 option java_outer_classname = "UserDTO";
                 option java_package = "com.maven.work.dto";

                 message User {
                        required string sessionId = 1;
                       optional string name = 2;
                       repeated string authorites = 3;
                 }



  •   To Compile the user.proto file use protoc.exe
  •   Command is : 
                 protoc -I=$SRC_DIR --java_out=$DST_DIR $SRC_DIR/user.proto 

    •  I am using windows xp and I used this command: 
                   protoc -I=./ --java_out=C:\\ ./user.proto
      •   Now use this User.Java to fill user session id and name. Take a look into service    code
      •   Name of service is  ( /get_user )





No comments:

Post a Comment