Skip to content

Commit

Permalink
add protobuf_examples
Browse files Browse the repository at this point in the history
  • Loading branch information
zhaoqingqing committed Sep 3, 2016
1 parent 140ec6f commit eec0f66
Show file tree
Hide file tree
Showing 15 changed files with 1,022 additions and 0 deletions.
6 changes: 6 additions & 0 deletions unity_protobuf_sample/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,9 @@ protobuf_tools
build_server_protobuf.bat(自动生成proto服务器代码)

</pre>



### protobuf_examples

protobuf_examples目录是从google官方checkout的example https://github.com/google/protobuf/trunk/examples
95 changes: 95 additions & 0 deletions unity_protobuf_sample/protobuf_examples/AddPerson.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
// 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.addPhones(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]);
try {
addressBook.mergeFrom(input);
} finally {
try { input.close(); } catch (Throwable ignore) {}
}
} catch (FileNotFoundException e) {
System.out.println(args[0] + ": File not found. Creating a new file.");
}

// Add an address.
addressBook.addPeople(
PromptForAddress(new BufferedReader(new InputStreamReader(System.in)),
System.out));

// Write the new address book back to disk.
FileOutputStream output = new FileOutputStream(args[0]);
try {
addressBook.build().writeTo(output);
} finally {
output.close();
}
}
}
63 changes: 63 additions & 0 deletions unity_protobuf_sample/protobuf_examples/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
# Minimum CMake required
cmake_minimum_required(VERSION 2.8.12)

# Project
project(protobuf-examples)

# Find required protobuf package
find_package(protobuf CONFIG REQUIRED)

if(protobuf_VERBOSE)
message(STATUS "Using Protocol Buffers ${Protobuf_VERSION}")
endif()

set(CMAKE_INCLUDE_CURRENT_DIR TRUE)

# http://www.cmake.org/Wiki/CMake_FAQ#How_can_I_build_my_MSVC_application_with_a_static_runtime.3F
if(MSVC AND protobuf_MSVC_STATIC_RUNTIME)
foreach(flag_var
CMAKE_CXX_FLAGS CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_RELEASE
CMAKE_CXX_FLAGS_MINSIZEREL CMAKE_CXX_FLAGS_RELWITHDEBINFO)
if(${flag_var} MATCHES "/MD")
string(REGEX REPLACE "/MD" "/MT" ${flag_var} "${${flag_var}}")
endif(${flag_var} MATCHES "/MD")
endforeach()
endif()

foreach(example add_person list_people)
set(${example}_SRCS ${example}.cc)
set(${example}_PROTOS addressbook.proto)

#Code Generation
if(protobuf_MODULE_COMPATIBLE) #Legacy Support
protobuf_generate_cpp(${example}_PROTO_SRCS ${example}_PROTO_HDRS ${${example}_PROTOS})
list(APPEND ${example}_SRCS ${${example}_PROTO_SRCS} ${${example}_PROTO_HDRS})
else()

foreach(proto_file ${${example}_PROTOS})
get_filename_component(proto_file_abs ${proto_file} ABSOLUTE)
get_filename_component(basename ${proto_file} NAME_WE)
set(generated_files ${basename}.pb.cc ${basename}.pb.h)
list(APPEND ${example}_SRCS ${generated_files})

add_custom_command(
OUTPUT ${generated_files}
COMMAND protobuf::protoc
ARGS --cpp_out ${CMAKE_CURRENT_BINARY_DIR} -I ${CMAKE_CURRENT_SOURCE_DIR} ${proto_file_abs}
COMMENT "Generating ${generated_files} from ${proto_file}"
VERBATIM
)
endforeach()
endif()

#Executable setup
set(executable_name ${example}_cpp)
add_executable(${executable_name} ${${example}_SRCS} ${${example}_PROTOS})
if(protobuf_MODULE_COMPATIBLE) #Legacy mode
target_include_directories(${executable_name} PUBLIC ${PROTOBUF_INCLUDE_DIRS})
target_link_libraries(${executable_name} ${PROTOBUF_LIBRARIES})
else()
target_link_libraries(${executable_name} protobuf::libprotobuf)
endif()

endforeach()
50 changes: 50 additions & 0 deletions unity_protobuf_sample/protobuf_examples/ListPeople.java
Original file line number Diff line number Diff line change
@@ -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.getPeopleList()) {
System.out.println("Person ID: " + person.getId());
System.out.println(" Name: " + person.getName());
if (!person.getEmail().isEmpty()) {
System.out.println(" E-mail address: " + person.getEmail());
}

for (Person.PhoneNumber phoneNumber : person.getPhonesList()) {
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);
}
}
79 changes: 79 additions & 0 deletions unity_protobuf_sample/protobuf_examples/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
# See README.txt.

.PHONY: all cpp java python clean

all: cpp java python

cpp: add_person_cpp list_people_cpp
go: add_person_go list_people_go
gotest: add_person_gotest list_people_gotest
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
rm -f protoc_middleman_go tutorial/*.pb.go add_person_go list_people_go
rmdir tutorial 2>/dev/null || true
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

protoc_middleman_go: addressbook.proto
mkdir tutorial # make directory for go package
protoc --go_out=tutorial addressbook.proto
@touch protoc_middleman_go

add_person_cpp: add_person.cc protoc_middleman
pkg-config --cflags protobuf # fails if protobuf is not installed
c++ add_person.cc addressbook.pb.cc -o add_person_cpp `pkg-config --cflags --libs protobuf`

list_people_cpp: list_people.cc protoc_middleman
pkg-config --cflags protobuf # fails if protobuf is not installed
c++ list_people.cc addressbook.pb.cc -o list_people_cpp `pkg-config --cflags --libs protobuf`

add_person_go: add_person.go protoc_middleman_go
go build -o add_person_go add_person.go

add_person_gotest: add_person_test.go add_person_go
go test add_person.go add_person_test.go

list_people_go: list_people.go protoc_middleman_go
go build -o list_people_go list_people.go

list_people_gotest: list_people.go list_people_go
go test list_people.go list_people_test.go

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
54 changes: 54 additions & 0 deletions unity_protobuf_sample/protobuf_examples/README.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
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:
https://developers.google.com/protocol-buffers/docs/tutorials

* Note that on some platforms you may have to edit the Makefile and remove
"-lpthread" from the linker commands (perhaps replacing it with something else).
We didn't do this automatically because we wanted to keep the example simple.

## Go ##

The Go example requires a plugin to the protocol buffer compiler, so it is not
build with all the other examples. See:
https://github.com/golang/protobuf
for more information about Go protocol buffer support.

First, install the Protocol Buffers compiler (protoc).
Then, install the Go Protocol Buffers plugin
($GOPATH/bin must be in your $PATH for protoc to find it):
go get github.com/golang/protobuf/protoc-gen-go

Build the Go samples in this directory with "make go". This creates the
following executable files in the current directory:
add_person_go list_people_go
To run the example:
./add_person_go addressbook.data
to add a person to the protocol buffer encoded file addressbook.data. The file
is created if it does not exist. To view the data, run:
./list_people_go addressbook.data

Observe that the C++, Python, and Java examples in this directory run in a
similar way and can view/modify files created by the Go example and vice
versa.
Loading

0 comments on commit eec0f66

Please sign in to comment.