Builders vs Messages

Builders vs Messages

The message classes generated by the protocol buffer compiler are all immutable. Once a message object is constructed, it cannot be modified, just like a Java String. To construct a message, you must first construct a builder, set any fields you want to set to your chosen values, then call the builder’s build() method.

You may have noticed that each method of the builder which modifies the message returns another builder. The returned object is actually the same builder on which you called the method. It is returned for convenience so that you can string several setters together on a single line of code.

Here’s an example of how you would create an instance of Person.

Person ashok =
  Person.newBuilder()
    .setId(123)
    .setName("Ashok Kumar")
    .setEmail("[email protected]")
    .addPhone(Person.PhoneNumber.newBuilder()
        .setNumber("+91-9000027370")
        .setType(Person.PhoneType.MOBILE))
    .build();

Standard Message Methods

Each message and builder class also contains a number of other methods that let you check or manipulate the entire message, including:

isInitialized()

Checks if all the required fields have been set.

toString()

Returns a human-readable representation of the message, particularly useful for debugging.

mergeFrom(Message other) (builder only)

Merges the contents of other into this message, overwriting singular fields and concatenating repeated ones.

clear() (builder only) 

Clears all the fields back to the empty state.

These methods implement the Message and Message.Builder interfaces shared by all Java messages and builders. For more information, see the complete API documentation for Message.

Parsing and Serialization

Finally, each protocol buffer class has methods for writing and reading messages of your chosen type using the protocol buffer binary format. These include:

byte[] toByteArray();

Serializes the message and returns a byte array containing its raw bytes.

static Person parseFrom(byte[] data);

Parses a message from the given byte array.

void writeTo(OutputStream output);

Serializes the message and writes it to an OutputStream.

static Person parseFrom(InputStream input);

Reads and parses a message from an InputStream

Writing a message

package com.ashok.protobuf;

import com.ashok.protobuf.AddressBookProtos.AddressBook;
import com.ashok.protobuf.AddressBookProtos.Person;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.PrintStream;

/**
 * 
 * @author ashok.mariyala
 *
 */
public class AddPerson {
   static Person PromptForAddress(BufferedReader stdin, PrintStream stdout) throws IOException {
      Person.Builder person = Person.newBuilder();

      stdout.print("Enter person ID: ");
      person.setId(Integer.valueOf(stdin.readLine()));

      stdout.print("Enter name: ");
      person.setName(stdin.readLine());

      stdout.print("Enter email address (blank for none): ");
      String email = stdin.readLine();
      if (email.length() > 0) {
         person.setEmail(email);
      }

      while (true) {
         stdout.print("Enter a phone number (or leave blank to finish): ");
         String number = stdin.readLine();
         if (number.length() == 0) {
            break;
         }

         Person.PhoneNumber.Builder phoneNumber = Person.PhoneNumber.newBuilder().setNumber(number);

         stdout.print("Is this a mobile, home, or work phone? ");
         String type = stdin.readLine();
         if (type.equals("mobile")) {
            phoneNumber.setType(Person.PhoneType.MOBILE);
         } else if (type.equals("home")) {
            phoneNumber.setType(Person.PhoneType.HOME);
         } else if (type.equals("work")) {
            phoneNumber.setType(Person.PhoneType.WORK);
         } else {
            stdout.println("Unknown phone type.  Using default.");
         }
         person.addPhone(phoneNumber);
      }
      return person.build();
   }

   public static void main(String[] args) throws Exception {
      if (args.length != 1) {
         System.err.println("Usage:  AddPerson ADDRESS_BOOK_FILE");
         System.exit(-1);
      }

      AddressBook.Builder addressBook = AddressBook.newBuilder();

      try {
         addressBook.mergeFrom(new FileInputStream(args[0]));
      } catch (FileNotFoundException e) {
         System.out.println(args[0] + ": File not found.  Creating a new file.");
      }

      addressBook.addPerson(PromptForAddress(new BufferedReader(
            new InputStreamReader(System.in)), System.out));

      FileOutputStream output = new FileOutputStream(args[0]);
      addressBook.build().writeTo(output);
      output.close();
   }
}

Reading a message

package com.ashok.protobuf;

import com.ashok.protobuf.AddressBookProtos.AddressBook;
import com.ashok.protobuf.AddressBookProtos.Person;
import java.io.FileInputStream;

/**
 * 
 * @author ashok.mariyala
 *
 */
public class ListPeople {
   static void Print(AddressBook addressBook) {
      for (Person person : addressBook.getPersonList()) {
         System.out.println("Person ID: " + person.getId());
         System.out.println("  Name: " + person.getName());
         if (person.hasEmail()) {
            System.out.println("  E-mail address: " + person.getEmail());
         }

         for (Person.PhoneNumber phoneNumber : person.getPhoneList()) {
            switch (phoneNumber.getType()) {
            case MOBILE:
               System.out.print("  Mobile phone #: ");
               break;
            case HOME:
               System.out.print("  Home phone #: ");
               break;
            case WORK:
               System.out.print("  Work phone #: ");
               break;
            }
            System.out.println(phoneNumber.getNumber());
         }
      }
   }

   public static void main(String[] args) throws Exception {
      if (args.length != 1) {
         System.err.println("Usage:  ListPeople ADDRESS_BOOK_FILE");
         System.exit(-1);
      }
      AddressBook addressBook = AddressBook.parseFrom(new FileInputStream(args[0]));
      Print(addressBook);
   }
}

That’s it guys. This is all about Google Protocol Buffers Tutorial. Let me know your comments and suggestions about this tutorial. Thank you.

Builders vs Messages


Scroll to top