aboutsummaryrefslogtreecommitdiffstats
path: root/proto
diff options
context:
space:
mode:
Diffstat (limited to 'proto')
-rw-r--r--proto/pom.xml198
-rw-r--r--proto/src/main/java/com/google/gson/protobuf/ProtoTypeAdapter.java138
-rw-r--r--proto/src/main/protobuf/bag.proto29
-rw-r--r--proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithComplexAndRepeatedFieldsTest.java64
-rw-r--r--proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithPrimitiveTypesTest.java65
5 files changed, 494 insertions, 0 deletions
diff --git a/proto/pom.xml b/proto/pom.xml
new file mode 100644
index 00000000..c004fea8
--- /dev/null
+++ b/proto/pom.xml
@@ -0,0 +1,198 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+
+ <modelVersion>4.0.0</modelVersion>
+ <groupId>com.google.code.gson</groupId>
+ <artifactId>proto</artifactId>
+ <packaging>jar</packaging>
+ <version>0.5</version>
+ <name>Gson Protobuf Support</name>
+ <description>Gson support for Protobufs</description>
+ <distributionManagement>
+ <repository>
+ <id>local.repo</id>
+ <name>file repository to svn</name>
+ <url>file://${basedir}/../../mavenrepo</url>
+ </repository>
+ </distributionManagement>
+ <repositories>
+ <repository>
+ <id>gson</id>
+ <url>http://google-gson.googlecode.com/svn/mavenrepo</url>
+ <snapshots>
+ <enabled>true</enabled>
+ </snapshots>
+ <releases>
+ <enabled>true</enabled>
+ </releases>
+ </repository>
+ </repositories>
+ <licenses>
+ <license>
+ <name>The Apache Software License, Version 2.0</name>
+ <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
+ <distribution>repo</distribution>
+ </license>
+ </licenses>
+ <scm>
+ <connection>scm:svn:http://google-gson.googlecode.com/svn/trunk/proto</connection>
+ <developerConnection>scm:svn:https://google-gson.googlecode.com/svn/trunk/proto</developerConnection>
+ <url>http://google-gson.codegoogle.com/svn/trunk/proto</url>
+ </scm>
+ <issueManagement>
+ <system>Google Code Issue Tracking</system>
+ <url>http://code.google.com/p/google-gson/issues/list</url>
+ </issueManagement>
+
+ <dependencies>
+
+ <!-- Gson: Java to Json conversion -->
+ <dependency>
+ <groupId>com.google.code.gson</groupId>
+ <artifactId>gson</artifactId>
+ <version>1.7.1</version>
+ <scope>compile</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>com.google.protobuf</groupId>
+ <artifactId>protobuf-java</artifactId>
+ <version>2.4.0a</version>
+ <scope>compile</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <version>3.8.2</version>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+
+ <build>
+ <finalName>gson-proto</finalName>
+ <plugins>
+ <plugin>
+ <artifactId>maven-antrun-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>compile-protoc</id>
+ <phase>generate-sources</phase>
+ <configuration>
+ <tasks>
+ <mkdir dir="target/generated" />
+ <path id="proto.path">
+ <fileset dir="src/main/protobuf">
+ <include name="**/*.proto" />
+ </fileset>
+ </path>
+ <pathconvert pathsep=" " property="proto.files" refid="proto.path" />
+ <exec executable="protoc" failonerror="true">
+ <arg value="--java_out=src/main/java" />
+ <arg value="-I${project.basedir}/src/main/protobuf" />
+ <arg line="${proto.files}" />
+ </exec>
+ </tasks>
+ </configuration>
+ <goals>
+ <goal>run</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <version>2.3.2</version>
+ <configuration>
+ <source>1.6</source>
+ <target>1.6</target>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-eclipse-plugin</artifactId>
+ <version>2.8</version>
+ <configuration>
+ <downloadSources>true</downloadSources>
+ <downloadJavadocs>true</downloadJavadocs>
+ <workspace>../eclipse-ws</workspace>
+ <workspaceCodeStylesURL>file:///${basedir}/../lib/gson-formatting-styles.xml</workspaceCodeStylesURL>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-install-plugin</artifactId>
+ <!-- configuration>
+ <updateReleaseInfo>true</updateReleaseInfo>
+ <createChecksum>true</createChecksum>
+ <groupId>${groupId}</groupId>
+ <artifactId>${artifactId}</artifactId>
+ <version>${version}</version>
+ <packaging>jar</packaging>
+ <classifier>sources</classifier>
+ <file>target/proto-sources.jar</file>
+ </configuration -->
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-release-plugin</artifactId>
+ <version>2.1</version>
+ <configuration>
+ <arguments>-DenableCiProfile=true</arguments>
+ <tagBase>https://google-gson.googlecode.com/svn/tags/</tagBase>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-source-plugin</artifactId>
+ <version>2.1.2</version>
+ <executions>
+ <execution>
+ <id>attach-sources</id>
+ <goals>
+ <goal>jar</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-javadoc-plugin</artifactId>
+ <version>2.7</version>
+ <executions>
+ <execution>
+ <id>attach-javadocs</id>
+ <goals>
+ <goal>jar</goal>
+ </goals>
+ </execution>
+ </executions>
+ <configuration>
+ <links>
+ <link>http://download.oracle.com/javase/1.5.0/docs/api/</link>
+ </links>
+ <version>true</version>
+ <show>public</show>
+ </configuration>
+ </plugin>
+ <plugin>
+ <artifactId>maven-assembly-plugin</artifactId>
+ <configuration>
+ <descriptor>src/main/resources/assembly-descriptor.xml</descriptor>
+ <finalName>proto-${version}</finalName>
+ <outputDirectory>target/dist</outputDirectory>
+ <workDirectory>target/assembly/work</workDirectory>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+ <developers>
+ <developer>
+ <name>Inderjeet Singh</name>
+ <organization>Google Inc.</organization>
+ </developer>
+ </developers>
+</project>
diff --git a/proto/src/main/java/com/google/gson/protobuf/ProtoTypeAdapter.java b/proto/src/main/java/com/google/gson/protobuf/ProtoTypeAdapter.java
new file mode 100644
index 00000000..7a6be05f
--- /dev/null
+++ b/proto/src/main/java/com/google/gson/protobuf/ProtoTypeAdapter.java
@@ -0,0 +1,138 @@
+/*
+ * Copyright (C) 2010 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.protobuf;
+
+import com.google.gson.JsonArray;
+import com.google.gson.JsonDeserializationContext;
+import com.google.gson.JsonDeserializer;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParseException;
+import com.google.gson.JsonSerializationContext;
+import com.google.gson.JsonSerializer;
+import com.google.protobuf.Descriptors.Descriptor;
+import com.google.protobuf.Descriptors.FieldDescriptor;
+import com.google.protobuf.GeneratedMessage;
+
+import java.lang.reflect.Field;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.lang.reflect.Type;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Gson type adapter for protocol buffers
+ *
+ * @author Inderjeet Singh
+ */
+public class ProtoTypeAdapter implements JsonSerializer<GeneratedMessage>,
+ JsonDeserializer<GeneratedMessage> {
+
+ @Override
+ public JsonElement serialize(GeneratedMessage src, Type typeOfSrc,
+ JsonSerializationContext context) {
+ JsonObject ret = new JsonObject();
+ final Map<FieldDescriptor, Object> fields = src.getAllFields();
+
+ for (Map.Entry<FieldDescriptor, Object> fieldPair : fields.entrySet()) {
+ final FieldDescriptor desc = fieldPair.getKey();
+ if (desc.isRepeated()) {
+ List<?> fieldList = (List<?>) fieldPair.getValue();
+ if (fieldList.size() != 0) {
+ JsonArray array = new JsonArray();
+ for (Object o : fieldList) {
+ array.add(context.serialize(o));
+ }
+ ret.add(desc.getName(), array);
+ }
+ } else {
+ ret.add(desc.getName(), context.serialize(fieldPair.getValue()));
+ }
+ }
+ return ret;
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public GeneratedMessage deserialize(JsonElement json, Type typeOfT,
+ JsonDeserializationContext context) throws JsonParseException {
+ try {
+ JsonObject jsonObject = json.getAsJsonObject();
+ Class<? extends GeneratedMessage> protoClass =
+ (Class<? extends GeneratedMessage>) typeOfT;
+ try {
+ // Invoke the ProtoClass.newBuilder() method
+ Object protoBuilder = getCachedMethod(protoClass, "newBuilder")
+ .invoke(null);
+ Class<?> builderClass = protoBuilder.getClass();
+
+ Descriptor protoDescriptor = (Descriptor) getCachedMethod(
+ protoClass, "getDescriptor").invoke(null);
+ // Call setters on all of the available fields
+ for (FieldDescriptor fieldDescriptor : protoDescriptor.getFields()) {
+ String name = fieldDescriptor.getName();
+ if (jsonObject.has(name)) {
+ JsonElement jsonElement = jsonObject.get(name);
+ String fieldName = name + "_";
+ Field field = protoClass.getDeclaredField(fieldName);
+ Type fieldType = field.getGenericType();
+ Object fieldValue = context.deserialize(jsonElement, fieldType);
+ Method method = getCachedMethod(
+ builderClass, "setField", FieldDescriptor.class, Object.class);
+ method.invoke(protoBuilder, fieldDescriptor, fieldValue);
+ }
+ }
+
+ // Invoke the build method to return the final proto
+ return (GeneratedMessage) getCachedMethod(builderClass, "build")
+ .invoke(protoBuilder);
+ } catch (SecurityException e) {
+ throw new JsonParseException(e);
+ } catch (NoSuchMethodException e) {
+ throw new JsonParseException(e);
+ } catch (IllegalArgumentException e) {
+ throw new JsonParseException(e);
+ } catch (IllegalAccessException e) {
+ throw new JsonParseException(e);
+ } catch (InvocationTargetException e) {
+ throw new JsonParseException(e);
+ }
+ } catch (Exception e) {
+ throw new JsonParseException("Error while parsing proto: ", e);
+ }
+ }
+
+ private static Method getCachedMethod(Class<?> clazz, String methodName,
+ Class<?>... methodParamTypes) throws NoSuchMethodException {
+ Map<Class<?>, Method> mapOfMethods = mapOfMapOfMethods.get(methodName);
+ if (mapOfMethods == null) {
+ mapOfMethods = new HashMap<Class<?>, Method>();
+ mapOfMapOfMethods.put(methodName, mapOfMethods);
+ }
+ Method method = mapOfMethods.get(clazz);
+ if (method == null) {
+ method = clazz.getMethod(methodName, methodParamTypes);
+ mapOfMethods.put(clazz, method);
+ }
+ return method;
+ }
+
+ private static Map<String, Map<Class<?>, Method>> mapOfMapOfMethods =
+ new HashMap<String, Map<Class<?>, Method>>();
+} \ No newline at end of file
diff --git a/proto/src/main/protobuf/bag.proto b/proto/src/main/protobuf/bag.proto
new file mode 100644
index 00000000..6df147a0
--- /dev/null
+++ b/proto/src/main/protobuf/bag.proto
@@ -0,0 +1,29 @@
+//
+// Copyright (C) 2010 Google Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+package com.google.gson.protobuf.generated;
+option java_package = "com.google.gson.protobuf.generated";
+
+message SimpleProto {
+ optional string msg = 1;
+ optional int32 count = 2;
+}
+
+message ProtoWithRepeatedFields {
+ repeated int64 numbers = 1;
+ repeated SimpleProto simples = 2;
+ optional string name = 3;
+} \ No newline at end of file
diff --git a/proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithComplexAndRepeatedFieldsTest.java b/proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithComplexAndRepeatedFieldsTest.java
new file mode 100644
index 00000000..7b9a1c66
--- /dev/null
+++ b/proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithComplexAndRepeatedFieldsTest.java
@@ -0,0 +1,64 @@
+/*
+ * Copyright (C) 2010 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.google.gson.protobuf.functional;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.protobuf.ProtoTypeAdapter;
+import com.google.gson.protobuf.generated.Bag.ProtoWithRepeatedFields;
+import com.google.gson.protobuf.generated.Bag.SimpleProto;
+import com.google.protobuf.GeneratedMessage;
+
+import junit.framework.TestCase;
+
+/**
+ * Functional tests for protocol buffers using complex and repeated fields
+ *
+ * @author Inderjeet Singh
+ */
+public class ProtosWithComplexAndRepeatedFieldsTest extends TestCase {
+ private Gson gson;
+
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+ gson = new GsonBuilder().registerTypeHierarchyAdapter(
+ GeneratedMessage.class, new ProtoTypeAdapter()).create();
+ }
+
+ public void testSerializeRepeatedFields() {
+ ProtoWithRepeatedFields proto = ProtoWithRepeatedFields.newBuilder()
+ .addNumbers(2)
+ .addNumbers(3)
+ .addSimples(SimpleProto.newBuilder().setMsg("foo").build())
+ .addSimples(SimpleProto.newBuilder().setCount(3).build())
+ .build();
+ String json = gson.toJson(proto);
+ assertTrue(json.contains("[2,3]"));
+ assertTrue(json.contains("foo"));
+ assertTrue(json.contains("count"));
+ }
+
+ public void testDeserializeRepeatedFieldsProto() {
+ String json = "{numbers:[4,6],simples:[{msg:'bar'},{count:7}]}";
+ ProtoWithRepeatedFields proto =
+ gson.fromJson(json, ProtoWithRepeatedFields.class);
+ assertEquals(4, proto.getNumbers(0));
+ assertEquals(6, proto.getNumbers(1));
+ assertEquals("bar", proto.getSimples(0).getMsg());
+ assertEquals(7, proto.getSimples(1).getCount());
+ }
+}
diff --git a/proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithPrimitiveTypesTest.java b/proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithPrimitiveTypesTest.java
new file mode 100644
index 00000000..55628bc5
--- /dev/null
+++ b/proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithPrimitiveTypesTest.java
@@ -0,0 +1,65 @@
+/*
+ * Copyright (C) 2010 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.google.gson.protobuf.functional;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.protobuf.ProtoTypeAdapter;
+import com.google.gson.protobuf.generated.Bag.SimpleProto;
+import com.google.protobuf.Descriptors.Descriptor;
+import com.google.protobuf.GeneratedMessage;
+
+import junit.framework.TestCase;
+
+public class ProtosWithPrimitiveTypesTest extends TestCase {
+ private Gson gson;
+
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+ gson = new GsonBuilder().registerTypeHierarchyAdapter(
+ GeneratedMessage.class, new ProtoTypeAdapter()).create();
+ }
+
+ public void testSerializeEmptyProto() {
+ SimpleProto proto = SimpleProto.newBuilder().build();
+ String json = gson.toJson(proto);
+ assertEquals("{}", json);
+ }
+
+ public void testDeserializeEmptyProto() {
+ SimpleProto proto = gson.fromJson("{}", SimpleProto.class);
+ assertFalse(proto.hasCount());
+ assertFalse(proto.hasMsg());
+ }
+
+ public void testSerializeProto() {
+ Descriptor descriptor = SimpleProto.getDescriptor();
+ SimpleProto proto = SimpleProto.newBuilder()
+ .setCount(3)
+ .setMsg("foo")
+ .build();
+ String json = gson.toJson(proto);
+ assertTrue(json.contains("\"msg\":\"foo\""));
+ assertTrue(json.contains("\"count\":3"));
+ }
+
+ public void testDeserializeProto() {
+ SimpleProto proto = gson.fromJson("{msg:'foo',count:3}", SimpleProto.class);
+ assertEquals("foo", proto.getMsg());
+ assertEquals(3, proto.getCount());
+ }
+}