Skip to content

Instantly share code, notes, and snippets.

@kaunjovi
Created May 1, 2017 08:18
Show Gist options
  • Save kaunjovi/672b452d0b21c5e243029a5d5a79ce58 to your computer and use it in GitHub Desktop.
Save kaunjovi/672b452d0b21c5e243029a5d5a79ce58 to your computer and use it in GitHub Desktop.
Getting started with protobuf.
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;
}
<!-- protobuf. (de)serialize proto buffers using java api. -->
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
<version>3.2.0</version>
</dependency>
<!-- 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>
// 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();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment