aboutsummaryrefslogtreecommitdiff
path: root/examples
diff options
context:
space:
mode:
authortemporal <temporal@630680e5-0e50-0410-840e-4b1c322b438d>2008-07-10 02:12:20 +0000
committertemporal <temporal@630680e5-0e50-0410-840e-4b1c322b438d>2008-07-10 02:12:20 +0000
commit40ee551715c3a784ea6132dbf604b0e665ca2def (patch)
tree6e3ea9674be5b0f59106f88f3afa1313854beebf /examples
downloadprotobuf-40ee551715c3a784ea6132dbf604b0e665ca2def.tar.gz
protobuf-40ee551715c3a784ea6132dbf604b0e665ca2def.tar.bz2
protobuf-40ee551715c3a784ea6132dbf604b0e665ca2def.zip
Initial checkin.
Diffstat (limited to 'examples')
-rw-r--r--examples/AddPerson.java89
-rw-r--r--examples/ListPeople.java50
-rw-r--r--examples/Makefile56
-rw-r--r--examples/README.txt25
-rw-r--r--examples/add_person.cc92
-rwxr-xr-xexamples/add_person.py58
-rw-r--r--examples/addressbook.proto30
-rw-r--r--examples/list_people.cc65
-rwxr-xr-xexamples/list_people.py38
9 files changed, 503 insertions, 0 deletions
diff --git a/examples/AddPerson.java b/examples/AddPerson.java
new file mode 100644
index 00000000..4917684b
--- /dev/null
+++ b/examples/AddPerson.java
@@ -0,0 +1,89 @@
+// See README.txt for information and build instructions.
+
+import com.example.tutorial.AddressBookProtos.AddressBook;
+import com.example.tutorial.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;
+
+class AddPerson {
+ // This function fills in a Person message based on user input.
+ 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();
+ }
+
+ // Main function: Reads the entire address book from a file,
+ // adds one person based on user input, then writes it back out to the same
+ // file.
+ 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();
+
+ // Read the existing address book.
+ try {
+ FileInputStream input = new FileInputStream(args[0]);
+ addressBook.mergeFrom(input);
+ input.close();
+ } catch (FileNotFoundException e) {
+ System.out.println(args[0] + ": File not found. Creating a new file.");
+ }
+
+ // Add an address.
+ addressBook.addPerson(
+ PromptForAddress(new BufferedReader(new InputStreamReader(System.in)),
+ System.out));
+
+ // Write the new address book back to disk.
+ FileOutputStream output = new FileOutputStream(args[0]);
+ addressBook.build().writeTo(output);
+ output.close();
+ }
+}
diff --git a/examples/ListPeople.java b/examples/ListPeople.java
new file mode 100644
index 00000000..b2f153af
--- /dev/null
+++ b/examples/ListPeople.java
@@ -0,0 +1,50 @@
+// See README.txt for information and build instructions.
+
+import com.example.tutorial.AddressBookProtos.AddressBook;
+import com.example.tutorial.AddressBookProtos.Person;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.PrintStream;
+
+class ListPeople {
+ // Iterates though all people in the AddressBook and prints info about them.
+ 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());
+ }
+ }
+ }
+
+ // Main function: Reads the entire address book from a file and prints all
+ // the information inside.
+ public static void main(String[] args) throws Exception {
+ if (args.length != 1) {
+ System.err.println("Usage: ListPeople ADDRESS_BOOK_FILE");
+ System.exit(-1);
+ }
+
+ // Read the existing address book.
+ AddressBook addressBook =
+ AddressBook.parseFrom(new FileInputStream(args[0]));
+
+ Print(addressBook);
+ }
+}
diff --git a/examples/Makefile b/examples/Makefile
new file mode 100644
index 00000000..999ee94a
--- /dev/null
+++ b/examples/Makefile
@@ -0,0 +1,56 @@
+# See README.txt.
+
+.PHONY: all cpp java python clean
+
+all: cpp java python
+
+cpp: add_person_cpp list_people_cpp
+java: add_person_java list_people_java
+python: add_person_python list_people_python
+
+clean:
+ rm -f add_person_cpp list_people_cpp add_person_java list_people_java add_person_python list_people_python
+ rm -f javac_middleman AddPerson*.class ListPeople*.class com/example/tutorial/*.class
+ rm -f protoc_middleman addressbook.pb.cc addressbook.pb.h addressbook_pb2.py com/example/tutorial/AddressBookProtos.java
+ rm -f *.pyc
+ rmdir com/example/tutorial 2>/dev/null || true
+ rmdir com/example 2>/dev/null || true
+ rmdir com 2>/dev/null || true
+
+protoc_middleman: addressbook.proto
+ protoc --cpp_out=. --java_out=. --python_out=. addressbook.proto
+ @touch protoc_middleman
+
+add_person_cpp: add_person.cc protoc_middleman
+ c++ add_person.cc addressbook.pb.cc -lprotobuf -o add_person_cpp
+
+list_people_cpp: list_people.cc protoc_middleman
+ c++ list_people.cc addressbook.pb.cc -lprotobuf -o list_people_cpp
+
+javac_middleman: AddPerson.java ListPeople.java protoc_middleman
+ javac AddPerson.java ListPeople.java com/example/tutorial/AddressBookProtos.java
+ @touch javac_middleman
+
+add_person_java: javac_middleman
+ @echo "Writing shortcut script add_person_java..."
+ @echo '#! /bin/sh' > add_person_java
+ @echo 'java -classpath .:$$CLASSPATH AddPerson "$$@"' >> add_person_java
+ @chmod +x add_person_java
+
+list_people_java: javac_middleman
+ @echo "Writing shortcut script list_people_java..."
+ @echo '#! /bin/sh' > list_people_java
+ @echo 'java -classpath .:$$CLASSPATH ListPeople "$$@"' >> list_people_java
+ @chmod +x list_people_java
+
+add_person_python: add_person.py protoc_middleman
+ @echo "Writing shortcut script add_person_python..."
+ @echo '#! /bin/sh' > add_person_python
+ @echo './add_person.py "$$@"' >> add_person_python
+ @chmod +x add_person_python
+
+list_people_python: list_people.py protoc_middleman
+ @echo "Writing shortcut script list_people_python..."
+ @echo '#! /bin/sh' > list_people_python
+ @echo './list_people.py "$$@"' >> list_people_python
+ @chmod +x list_people_python
diff --git a/examples/README.txt b/examples/README.txt
new file mode 100644
index 00000000..b0d1a0c2
--- /dev/null
+++ b/examples/README.txt
@@ -0,0 +1,25 @@
+This directory contains example code that uses Protocol Buffers to manage an
+address book. Two programs are provided, each with three different
+implementations, one written in each of C++, Java, and Python. The add_person
+example adds a new person to an address book, prompting the user to input
+the person's information. The list_people example lists people already in the
+address book. The examples use the exact same format in all three languages,
+so you can, for example, use add_person_java to create an address book and then
+use list_people_python to read it.
+
+You must install the protobuf package before you can build these.
+
+To build all the examples (on a unix-like system), simply run "make". This
+creates the following executable files in the current directory:
+ add_person_cpp list_people_cpp
+ add_person_java list_people_java
+ add_person_python list_people_python
+
+If you only want to compile examples in one language, use "make cpp",
+"make java", or "make python".
+
+All of these programs simply take an address book file as their parameter.
+The add_person programs will create the file if it doesn't already exist.
+
+These examples are part of the Protocol Buffers tutorial, located at:
+ http://code.google.com/apis/protocolbuffers/docs/tutorials.html
diff --git a/examples/add_person.cc b/examples/add_person.cc
new file mode 100644
index 00000000..2aca216b
--- /dev/null
+++ b/examples/add_person.cc
@@ -0,0 +1,92 @@
+// See README.txt for information and build instructions.
+
+#include <iostream>
+#include <fstream>
+#include <string>
+#include "addressbook.pb.h"
+using namespace std;
+
+// This function fills in a Person message based on user input.
+void PromptForAddress(tutorial::Person* person) {
+ cout << "Enter person ID number: ";
+ int id;
+ cin >> id;
+ person->set_id(id);
+ cin.ignore(256, '\n');
+
+ cout << "Enter name: ";
+ getline(cin, *person->mutable_name());
+
+ cout << "Enter email address (blank for none): ";
+ string email;
+ getline(cin, email);
+ if (!email.empty()) {
+ person->set_email(email);
+ }
+
+ while (true) {
+ cout << "Enter a phone number (or leave blank to finish): ";
+ string number;
+ getline(cin, number);
+ if (number.empty()) {
+ break;
+ }
+
+ tutorial::Person::PhoneNumber* phone_number = person->add_phone();
+ phone_number->set_number(number);
+
+ cout << "Is this a mobile, home, or work phone? ";
+ string type;
+ getline(cin, type);
+ if (type == "mobile") {
+ phone_number->set_type(tutorial::Person::MOBILE);
+ } else if (type == "home") {
+ phone_number->set_type(tutorial::Person::HOME);
+ } else if (type == "work") {
+ phone_number->set_type(tutorial::Person::WORK);
+ } else {
+ cout << "Unknown phone type. Using default." << endl;
+ }
+ }
+}
+
+// Main function: Reads the entire address book from a file,
+// adds one person based on user input, then writes it back out to the same
+// file.
+int main(int argc, char* argv[]) {
+ // Verify that the version of the library that we linked against is
+ // compatible with the version of the headers we compiled against.
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+ if (argc != 2) {
+ cerr << "Usage: " << argv[0] << " ADDRESS_BOOK_FILE" << endl;
+ return -1;
+ }
+
+ tutorial::AddressBook address_book;
+
+ {
+ // Read the existing address book.
+ fstream input(argv[1], ios::in | ios::binary);
+ if (!input) {
+ cout << argv[1] << ": File not found. Creating a new file." << endl;
+ } else if (!address_book.ParseFromIstream(&input)) {
+ cerr << "Failed to parse address book." << endl;
+ return -1;
+ }
+ }
+
+ // Add an address.
+ PromptForAddress(address_book.add_person());
+
+ {
+ // Write the new address book back to disk.
+ fstream output(argv[1], ios::out | ios::trunc | ios::binary);
+ if (!address_book.SerializeToOstream(&output)) {
+ cerr << "Failed to write address book." << endl;
+ return -1;
+ }
+ }
+
+ return 0;
+}
diff --git a/examples/add_person.py b/examples/add_person.py
new file mode 100755
index 00000000..78e56966
--- /dev/null
+++ b/examples/add_person.py
@@ -0,0 +1,58 @@
+#! /usr/bin/python
+
+# See README.txt for information and build instructions.
+
+import addressbook_pb2
+import sys
+
+# This function fills in a Person message based on user input.
+def PromptForAddress(person):
+ person.id = int(raw_input("Enter person ID number: "))
+ person.name = raw_input("Enter name: ")
+
+ email = raw_input("Enter email address (blank for none): ")
+ if email != "":
+ person.email = email
+
+ while True:
+ number = raw_input("Enter a phone number (or leave blank to finish): ")
+ if number == "":
+ break
+
+ phone_number = person.phone.add()
+ phone_number.number = number
+
+ type = raw_input("Is this a mobile, home, or work phone? ")
+ if type == "mobile":
+ phone_number.type = addressbook_pb2.Person.MOBILE
+ elif type == "home":
+ phone_number.type = addressbook_pb2.Person.HOME
+ elif type == "work":
+ phone_number.type = addressbook_pb2.Person.WORK
+ else:
+ print "Unknown phone type; leaving as default value."
+
+# Main procedure: Reads the entire address book from a file,
+# adds one person based on user input, then writes it back out to the same
+# file.
+if len(sys.argv) != 2:
+ print "Usage:", sys.argv[0], "ADDRESS_BOOK_FILE"
+ sys.exit(-1)
+
+address_book = addressbook_pb2.AddressBook()
+
+# Read the existing address book.
+try:
+ f = open(sys.argv[1], "rb")
+ address_book.ParseFromString(f.read())
+ f.close()
+except IOError:
+ print sys.argv[1] + ": File not found. Creating a new file."
+
+# Add an address.
+PromptForAddress(address_book.person.add())
+
+# Write the new address book back to disk.
+f = open(sys.argv[1], "wb")
+f.write(address_book.SerializeToString())
+f.close()
diff --git a/examples/addressbook.proto b/examples/addressbook.proto
new file mode 100644
index 00000000..b14829e9
--- /dev/null
+++ b/examples/addressbook.proto
@@ -0,0 +1,30 @@
+// See README.txt for information and build instructions.
+
+package tutorial;
+
+option java_package = "com.example.tutorial";
+option java_outer_classname = "AddressBookProtos";
+
+message Person {
+ required string name = 1;
+ required int32 id = 2; // Unique ID number for this person.
+ optional string email = 3;
+
+ enum PhoneType {
+ MOBILE = 0;
+ HOME = 1;
+ WORK = 2;
+ }
+
+ message PhoneNumber {
+ required string number = 1;
+ optional PhoneType type = 2 [default = HOME];
+ }
+
+ repeated PhoneNumber phone = 4;
+}
+
+// Our address book file is just one of these.
+message AddressBook {
+ repeated Person person = 1;
+}
diff --git a/examples/list_people.cc b/examples/list_people.cc
new file mode 100644
index 00000000..bd9a583f
--- /dev/null
+++ b/examples/list_people.cc
@@ -0,0 +1,65 @@
+// See README.txt for information and build instructions.
+
+#include <iostream>
+#include <fstream>
+#include <string>
+#include "addressbook.pb.h"
+using namespace std;
+
+// Iterates though all people in the AddressBook and prints info about them.
+void ListPeople(const tutorial::AddressBook& address_book) {
+ for (int i = 0; i < address_book.person_size(); i++) {
+ const tutorial::Person& person = address_book.person(i);
+
+ cout << "Person ID: " << person.id() << endl;
+ cout << " Name: " << person.name() << endl;
+ if (person.has_email()) {
+ cout << " E-mail address: " << person.email() << endl;
+ }
+
+ for (int j = 0; j < person.phone_size(); j++) {
+ const tutorial::Person::PhoneNumber& phone_number = person.phone(j);
+
+ switch (phone_number.type()) {
+ case tutorial::Person::MOBILE:
+ cout << " Mobile phone #: ";
+ break;
+ case tutorial::Person::HOME:
+ cout << " Home phone #: ";
+ break;
+ case tutorial::Person::WORK:
+ cout << " Work phone #: ";
+ break;
+ }
+ cout << phone_number.number() << endl;
+ }
+ }
+}
+
+// Main function: Reads the entire address book from a file and prints all
+// the information inside.
+int main(int argc, char* argv[]) {
+ // Verify that the version of the library that we linked against is
+ // compatible with the version of the headers we compiled against.
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+ if (argc != 2) {
+ cerr << "Usage: " << argv[0] << " ADDRESS_BOOK_FILE" << endl;
+ return -1;
+ }
+
+ tutorial::AddressBook address_book;
+
+ {
+ // Read the existing address book.
+ fstream input(argv[1], ios::in | ios::binary);
+ if (!address_book.ParseFromIstream(&input)) {
+ cerr << "Failed to parse address book." << endl;
+ return -1;
+ }
+ }
+
+ ListPeople(address_book);
+
+ return 0;
+}
diff --git a/examples/list_people.py b/examples/list_people.py
new file mode 100755
index 00000000..76f4bf1e
--- /dev/null
+++ b/examples/list_people.py
@@ -0,0 +1,38 @@
+#! /usr/bin/python
+
+# See README.txt for information and build instructions.
+
+import addressbook_pb2
+import sys
+
+# Iterates though all people in the AddressBook and prints info about them.
+def ListPeople(address_book):
+ for person in address_book.person:
+ print "Person ID:", person.id
+ print " Name:", person.name
+ if person.HasField('email'):
+ print " E-mail address:", person.email
+
+ for phone_number in person.phone:
+ if phone_number.type == addressbook_pb2.Person.MOBILE:
+ print " Mobile phone #: ",
+ elif phone_number.type == addressbook_pb2.Person.HOME:
+ print " Home phone #: ",
+ elif phone_number.type == addressbook_pb2.Person.WORK:
+ print " Work phone #: ",
+ print phone_number.number
+
+# Main procedure: Reads the entire address book from a file and prints all
+# the information inside.
+if len(sys.argv) != 2:
+ print "Usage:", sys.argv[0], "ADDRESS_BOOK_FILE"
+ sys.exit(-1)
+
+address_book = addressbook_pb2.AddressBook()
+
+# Read the existing address book.
+f = open(sys.argv[1], "rb")
+address_book.ParseFromString(f.read())
+f.close()
+
+ListPeople(address_book)