Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Protobuf for Lazy Java Coders

DZone's Guide to

Protobuf for Lazy Java Coders

Don't want to bother with downloading a .proto file, loading up Terminal, and commanding from there? Just have Maven do it for you.

· Java Zone
Free Resource

Download Microservices for Java Developers: A hands-on introduction to frameworks and containers. Brought to you in partnership with Red Hat.

Sometimes you are just plain lazy and would rather have Maven create the Java files out of .proto. The alternative would have been to download the protoc, fire up the terminal and issue one simple command. Not a big deal at all. But as I said sometimes you are just plain lazy.

So how do you go about it? Follow the steps given below.

Think up a super critical message that you want to send across over the wire.

If you don't know how to write a .proto file, perhaps one of the links below would help.

Below is the super critical hello world that I want to send across.

Create Your Message

syntax = "proto2";

// This is the package where the java source code will be placed. 
option java_package = "le.arn";

// This is the name of the class. 
// If not provided, it will be created as <message name>OuterClass. 
option java_outer_classname = "GreetingProtos";

message Greeting {
  required string greeting = 1;
  
} 


Maven

Create a vanilla Maven project. 

Say thanks to open source and add protoc-jar-maven-plugin to the project. 

<!-- protobuf. (de)serialize proto buffers using java api. -->
<dependency>
  <groupId>com.google.protobuf</groupId>
  <artifactId>protobuf-java</artifactId>
  <version>3.2.0</version>
</dependency>


This would create the Java files.

Add the Protobuf Libraries

However, they will complain that the Google libraries are not around. 

So you will have to add the protobuf libraries. 

<!-- compile proto file into java files. -->
<plugin>
    <groupId>com.github.os72</groupId>
    <artifactId>protoc-jar-maven-plugin</artifactId>
    <version>3.2.0.1</version>
    <executions>
        <execution>
            <phase>generate-sources</phase>
            <goals>
                <goal>run</goal>
            </goals>
            <configuration>
                <!-- <includeDirectories> <include>src/main/protobuf</include> </includeDirectories> -->
                <inputDirectories>
                    <include>src/main/protobuf</include>
                </inputDirectories>
                <!-- Create java files. And put them in the src/main/java directory. -->
                <outputTargets>
                    <outputTarget>
                        <type>java</type>
                        <outputDirectory>src/main/java</outputDirectory>
                    </outputTarget>
                </outputTargets>
            </configuration>
        </execution>
    </executions>
</plugin>


The proof of the pudding is in eating it. 

Testing

Let's write a test to serialize and deserialize the super critical message.

// 1 : Create a Greeting object using the Protobuf builder.
Builder greetingBuilder = GreetingProtos.Greeting.newBuilder();
greetingBuilder.setGreeting(HELLO_WORLD);
Greeting greeting = greetingBuilder.build();
try {
    // 2 : Write the message into a file. Serialize the object.
    FileOutputStream output = new FileOutputStream(SER_FILE);
    greeting.writeTo(output);
    output.close();
    // 3 : Deserialize the object from the file.
    Greeting greetingFromFile = Greeting.parseFrom(new FileInputStream(
        SER_FILE));
    logger.debug("We read this from the file {}", greetingFromFile);
    // 4 : All is well?
    assertEquals(HELLO_WORLD, greetingFromFile.getGreeting());
} catch (IOException e) {
    e.printStackTrace();
}


That's it. You have a Java project that does the basic steps, i.e. serialization/deserialization, using protobuf. I hope that is helpful. If you know an easier, quicker way, please share it as well. 

Either way, your comments will be appreciated. Please take a couple of minutes and write back. 

Download Building Reactive Microservices in Java: Asynchronous and Event-Based Application Design. Brought to you in partnership with Red Hat

Topics:
java ,protobuf ,maven ,tutorial ,file creation

Published at DZone with permission of Partha Bhattacharjee, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}