google-gson/ 0000775 0001750 0001750 00000000000 12207114637 012633 5 ustar ebourg ebourg google-gson/LICENSE 0000664 0001750 0001750 00000026452 11551141143 013642 0 ustar ebourg ebourg Google Gson
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2008-2011 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.
google-gson/README 0000664 0001750 0001750 00000000601 11053601477 013511 0 ustar ebourg ebourg Gson is a Java library that can be used to convert a Java object into its
JSON representation. It can also be used to convert a JSON string into an
equivalent Java object. Gson can work with arbitrary Java objects including
pre-existing objects that you do not have source-code of.
Complete Gson documentation is available at its project page
http://code.google.com/p/google-gson
google-gson/pom.xml 0000664 0001750 0001750 00000017565 12144256347 014173 0 ustar ebourg ebourg 4.0.0com.google.code.gsongsonjar2.2.42008Gsonorg.sonatype.ossoss-parent7http://code.google.com/p/google-gson/Google Gson libraryUTF-8The Apache Software License, Version 2.0http://www.apache.org/licenses/LICENSE-2.0.txtreposcm:svn:http://google-gson.googlecode.com/svn/tags/gson-2.2.4scm:svn:https://google-gson.googlecode.com/svn/tags/gson-2.2.4http://google-gson.googlecode.com/svn/tags/gson-2.2.4Google Code Issue Trackinghttp://code.google.com/p/google-gson/issues/listGoogle, Inc.http://www.google.comjunitjunit3.8.2testrelease-sign-artifactsperformReleasetrueorg.apache.maven.pluginsmaven-gpg-plugin1.4sign-artifactsverifysignpackageorg.apache.maven.pluginsmaven-compiler-plugin3.11.51.5org.apache.maven.pluginsmaven-jar-plugin2.4packagejarfalseJ2SE-1.5${project.version}http://code.google.com/p/google-gson/Google Gson Project${project.name}${project.description}.2com.google.gsonorg.apache.maven.pluginsmaven-source-plugin2.2.1attach-sourcesverifyjarcom.google.gson;version="${project.version}"com.google.gson.source2${project.version}org.apache.maven.pluginsmaven-javadoc-plugin2.9attach-javadocsjarcom.google.gsoncom.google.gson.internal:com.google.gson.internal.bind
http://docs.oracle.com/javase/1.5.0/docs/api/
trueprotectedorg.apache.maven.pluginsmaven-eclipse-plugin2.9truetrue
../eclipse-ws/
file:///${basedir}/../lib/gson-formatting-styles.xml
org.apache.maven.pluginsmaven-release-plugin-DenableCiProfile=truehttps://google-gson.googlecode.com/svn/tagsmaven-assembly-plugin2.4assembly-descriptor.xmlgoogle-gson-${project.version}target/disttarget/assembly/workInderjeet SinghTrymph Inc.Joel LeitchGoogle Inc.Jesse WilsonSquare Inc.
google-gson/Gson 2.1 notes.txt 0000664 0001750 0001750 00000000454 11663107727 015706 0 ustar ebourg ebourg Dropped support for GsonBuilder.registerTypeHierarchyAdapter+InstanceCreator
Relax registerTypeHierarchyAdapter order
Gson 2.0 failed if you registered Manager then Employee would fail
Gson 2.1 it isn't a problem
com.google.gson.functional.TypeHierarchyAdapterTest#testRegisterSubTypeFirstNotAllowed google-gson/src/ 0000775 0001750 0001750 00000000000 12207114635 013420 5 ustar ebourg ebourg google-gson/src/metric/ 0000775 0001750 0001750 00000000000 12207114635 014703 5 ustar ebourg ebourg google-gson/src/metric/java/ 0000775 0001750 0001750 00000000000 12207114635 015624 5 ustar ebourg ebourg google-gson/src/metric/java/com/ 0000775 0001750 0001750 00000000000 12207114635 016402 5 ustar ebourg ebourg google-gson/src/metric/java/com/google/ 0000775 0001750 0001750 00000000000 12207114635 017656 5 ustar ebourg ebourg google-gson/src/metric/java/com/google/gson/ 0000775 0001750 0001750 00000000000 12207114635 020624 5 ustar ebourg ebourg google-gson/src/test/ 0000775 0001750 0001750 00000000000 12207114634 014376 5 ustar ebourg ebourg google-gson/src/test/java/ 0000775 0001750 0001750 00000000000 12207114634 015317 5 ustar ebourg ebourg google-gson/src/test/java/com/ 0000775 0001750 0001750 00000000000 12207114634 016075 5 ustar ebourg ebourg google-gson/src/test/java/com/google/ 0000775 0001750 0001750 00000000000 12207114634 017351 5 ustar ebourg ebourg google-gson/src/test/java/com/google/gson/ 0000775 0001750 0001750 00000000000 12207114635 020320 5 ustar ebourg ebourg google-gson/src/test/java/com/google/gson/PrimitiveTypeAdapter.java 0000664 0001750 0001750 00000005046 11633056630 025305 0 ustar ebourg ebourg /*
* Copyright (C) 2008 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;
import com.google.gson.internal.Primitives;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* Handles type conversion from some object to some primitive (or primitive
* wrapper instance).
*
* @author Joel Leitch
*/
final class PrimitiveTypeAdapter {
@SuppressWarnings("unchecked")
public T adaptType(Object from, Class to) {
Class> aClass = Primitives.wrap(to);
if (Primitives.isWrapperType(aClass)) {
if (aClass == Character.class) {
String value = from.toString();
if (value.length() == 1) {
return (T) (Character) from.toString().charAt(0);
}
throw new JsonParseException("The value: " + value + " contains more than a character.");
}
try {
Constructor> constructor = aClass.getConstructor(String.class);
return (T) constructor.newInstance(from.toString());
} catch (NoSuchMethodException e) {
throw new JsonParseException(e);
} catch (IllegalAccessException e) {
throw new JsonParseException(e);
} catch (InvocationTargetException e) {
throw new JsonParseException(e);
} catch (InstantiationException e) {
throw new JsonParseException(e);
}
} else if (Enum.class.isAssignableFrom(to)) {
// Case where the type being adapted to is an Enum
// We will try to convert from.toString() to the enum
try {
Method valuesMethod = to.getMethod("valueOf", String.class);
return (T) valuesMethod.invoke(null, from.toString());
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
} else {
throw new JsonParseException("Can not adapt type " + from.getClass() + " to " + to);
}
}
}
google-gson/src/test/java/com/google/gson/ExposeAnnotationExclusionStrategyTest.java 0000664 0001750 0001750 00000005645 11662650451 030755 0 ustar ebourg ebourg /*
* Copyright (C) 2011 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;
import com.google.gson.annotations.Expose;
import com.google.gson.internal.Excluder;
import junit.framework.TestCase;
import java.lang.reflect.Field;
/**
* Unit tests for GsonBuilder.REQUIRE_EXPOSE_DESERIALIZE.
*
* @author Joel Leitch
*/
public class ExposeAnnotationExclusionStrategyTest extends TestCase {
private Excluder excluder = Excluder.DEFAULT.excludeFieldsWithoutExposeAnnotation();
public void testNeverSkipClasses() throws Exception {
assertFalse(excluder.excludeClass(MockObject.class, true));
assertFalse(excluder.excludeClass(MockObject.class, false));
}
public void testSkipNonAnnotatedFields() throws Exception {
Field f = createFieldAttributes("hiddenField");
assertTrue(excluder.excludeField(f, true));
assertTrue(excluder.excludeField(f, false));
}
public void testSkipExplicitlySkippedFields() throws Exception {
Field f = createFieldAttributes("explicitlyHiddenField");
assertTrue(excluder.excludeField(f, true));
assertTrue(excluder.excludeField(f, false));
}
public void testNeverSkipExposedAnnotatedFields() throws Exception {
Field f = createFieldAttributes("exposedField");
assertFalse(excluder.excludeField(f, true));
assertFalse(excluder.excludeField(f, false));
}
public void testNeverSkipExplicitlyExposedAnnotatedFields() throws Exception {
Field f = createFieldAttributes("explicitlyExposedField");
assertFalse(excluder.excludeField(f, true));
assertFalse(excluder.excludeField(f, false));
}
public void testDifferentSerializeAndDeserializeField() throws Exception {
Field f = createFieldAttributes("explicitlyDifferentModeField");
assertFalse(excluder.excludeField(f, true));
assertTrue(excluder.excludeField(f, false));
}
private static Field createFieldAttributes(String fieldName) throws Exception {
return MockObject.class.getField(fieldName);
}
@SuppressWarnings("unused")
private static class MockObject {
@Expose
public final int exposedField = 0;
@Expose(serialize=true, deserialize=true)
public final int explicitlyExposedField = 0;
@Expose(serialize=false, deserialize=false)
public final int explicitlyHiddenField = 0;
@Expose(serialize=true, deserialize=false)
public final int explicitlyDifferentModeField = 0;
public final int hiddenField = 0;
}
}
google-gson/src/test/java/com/google/gson/JsonObjectTest.java 0000664 0001750 0001750 00000012100 12035434745 024063 0 ustar ebourg ebourg /*
* Copyright (C) 2008 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;
import com.google.gson.common.MoreAsserts;
import junit.framework.TestCase;
/**
* Unit test for the {@link JsonObject} class.
*
* @author Joel Leitch
*/
public class JsonObjectTest extends TestCase {
public void testAddingAndRemovingObjectProperties() throws Exception {
JsonObject jsonObj = new JsonObject();
String propertyName = "property";
assertFalse(jsonObj.has(propertyName));
assertNull(jsonObj.get(propertyName));
JsonPrimitive value = new JsonPrimitive("blah");
jsonObj.add(propertyName, value);
assertEquals(value, jsonObj.get(propertyName));
JsonElement removedElement = jsonObj.remove(propertyName);
assertEquals(value, removedElement);
assertFalse(jsonObj.has(propertyName));
assertNull(jsonObj.get(propertyName));
}
public void testAddingNullPropertyValue() throws Exception {
String propertyName = "property";
JsonObject jsonObj = new JsonObject();
jsonObj.add(propertyName, null);
assertTrue(jsonObj.has(propertyName));
JsonElement jsonElement = jsonObj.get(propertyName);
assertNotNull(jsonElement);
assertTrue(jsonElement.isJsonNull());
}
public void testAddingNullOrEmptyPropertyName() throws Exception {
JsonObject jsonObj = new JsonObject();
try {
jsonObj.add(null, JsonNull.INSTANCE);
fail("Should not allow null property names.");
} catch (NullPointerException expected) { }
jsonObj.add("", JsonNull.INSTANCE);
jsonObj.add(" \t", JsonNull.INSTANCE);
}
public void testAddingBooleanProperties() throws Exception {
String propertyName = "property";
JsonObject jsonObj = new JsonObject();
jsonObj.addProperty(propertyName, true);
assertTrue(jsonObj.has(propertyName));
JsonElement jsonElement = jsonObj.get(propertyName);
assertNotNull(jsonElement);
assertTrue(jsonElement.getAsBoolean());
}
public void testAddingStringProperties() throws Exception {
String propertyName = "property";
String value = "blah";
JsonObject jsonObj = new JsonObject();
jsonObj.addProperty(propertyName, value);
assertTrue(jsonObj.has(propertyName));
JsonElement jsonElement = jsonObj.get(propertyName);
assertNotNull(jsonElement);
assertEquals(value, jsonElement.getAsString());
}
public void testAddingCharacterProperties() throws Exception {
String propertyName = "property";
char value = 'a';
JsonObject jsonObj = new JsonObject();
jsonObj.addProperty(propertyName, value);
assertTrue(jsonObj.has(propertyName));
JsonElement jsonElement = jsonObj.get(propertyName);
assertNotNull(jsonElement);
assertEquals(String.valueOf(value), jsonElement.getAsString());
assertEquals(value, jsonElement.getAsCharacter());
}
/**
* From bug report http://code.google.com/p/google-gson/issues/detail?id=182
*/
public void testPropertyWithQuotes() {
JsonObject jsonObj = new JsonObject();
jsonObj.add("a\"b", new JsonPrimitive("c\"d"));
String json = new Gson().toJson(jsonObj);
assertEquals("{\"a\\\"b\":\"c\\\"d\"}", json);
}
/**
* From issue 227.
*/
public void testWritePropertyWithEmptyStringName() {
JsonObject jsonObj = new JsonObject();
jsonObj.add("", new JsonPrimitive(true));
assertEquals("{\"\":true}", new Gson().toJson(jsonObj));
}
public void testReadPropertyWithEmptyStringName() {
JsonObject jsonObj = new JsonParser().parse("{\"\":true}").getAsJsonObject();
assertEquals(true, jsonObj.get("").getAsBoolean());
}
public void testEqualsOnEmptyObject() {
MoreAsserts.assertEqualsAndHashCode(new JsonObject(), new JsonObject());
}
public void testEqualsNonEmptyObject() {
JsonObject a = new JsonObject();
JsonObject b = new JsonObject();
assertEquals(a, a);
a.add("foo", new JsonObject());
assertFalse(a.equals(b));
assertFalse(b.equals(a));
b.add("foo", new JsonObject());
MoreAsserts.assertEqualsAndHashCode(a, b);
a.add("bar", new JsonObject());
assertFalse(a.equals(b));
assertFalse(b.equals(a));
b.add("bar", JsonNull.INSTANCE);
assertFalse(a.equals(b));
assertFalse(b.equals(a));
}
public void testDeepCopy() {
JsonObject original = new JsonObject();
JsonArray firstEntry = new JsonArray();
original.add("key", firstEntry);
JsonObject copy = original.deepCopy();
firstEntry.add(new JsonPrimitive("z"));
assertEquals(1, original.get("key").getAsJsonArray().size());
assertEquals(0, copy.get("key").getAsJsonArray().size());
}
}
google-gson/src/test/java/com/google/gson/intercept/ 0000775 0001750 0001750 00000000000 12207114634 022314 5 ustar ebourg ebourg google-gson/src/test/java/com/google/gson/JsonParserTest.java 0000664 0001750 0001750 00000010120 12035434745 024111 0 ustar ebourg ebourg /*
* Copyright (C) 2009 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;
import java.io.CharArrayReader;
import java.io.CharArrayWriter;
import java.io.StringReader;
import junit.framework.TestCase;
import com.google.gson.common.TestTypes.BagOfPrimitives;
import com.google.gson.internal.Streams;
import com.google.gson.stream.JsonReader;
/**
* Unit test for {@link JsonParser}
*
* @author Inderjeet Singh
*/
public class JsonParserTest extends TestCase {
private JsonParser parser;
@Override
protected void setUp() throws Exception {
super.setUp();
parser = new JsonParser();
}
public void testParseInvalidJson() {
try {
parser.parse("[[]");
fail();
} catch (JsonSyntaxException expected) { }
}
public void testParseUnquotedStringArrayFails() {
JsonElement element = parser.parse("[a,b,c]");
assertEquals("a", element.getAsJsonArray().get(0).getAsString());
assertEquals("b", element.getAsJsonArray().get(1).getAsString());
assertEquals("c", element.getAsJsonArray().get(2).getAsString());
assertEquals(3, element.getAsJsonArray().size());
}
public void testParseString() {
String json = "{a:10,b:'c'}";
JsonElement e = parser.parse(json);
assertTrue(e.isJsonObject());
assertEquals(10, e.getAsJsonObject().get("a").getAsInt());
assertEquals("c", e.getAsJsonObject().get("b").getAsString());
}
public void testParseEmptyString() {
JsonElement e = parser.parse("\" \"");
assertTrue(e.isJsonPrimitive());
assertEquals(" ", e.getAsString());
}
public void testParseEmptyWhitespaceInput() {
JsonElement e = parser.parse(" ");
assertTrue(e.isJsonNull());
}
public void testParseUnquotedSingleWordStringFails() {
assertEquals("Test", parser.parse("Test").getAsString());
}
public void testParseUnquotedMultiWordStringFails() {
String unquotedSentence = "Test is a test..blah blah";
try {
parser.parse(unquotedSentence);
fail();
} catch (JsonSyntaxException expected) { }
}
public void testParseMixedArray() {
String json = "[{},13,\"stringValue\"]";
JsonElement e = parser.parse(json);
assertTrue(e.isJsonArray());
JsonArray array = e.getAsJsonArray();
assertEquals("{}", array.get(0).toString());
assertEquals(13, array.get(1).getAsInt());
assertEquals("stringValue", array.get(2).getAsString());
}
public void testParseReader() {
StringReader reader = new StringReader("{a:10,b:'c'}");
JsonElement e = parser.parse(reader);
assertTrue(e.isJsonObject());
assertEquals(10, e.getAsJsonObject().get("a").getAsInt());
assertEquals("c", e.getAsJsonObject().get("b").getAsString());
}
public void testReadWriteTwoObjects() throws Exception {
Gson gson = new Gson();
CharArrayWriter writer = new CharArrayWriter();
BagOfPrimitives expectedOne = new BagOfPrimitives(1, 1, true, "one");
writer.write(gson.toJson(expectedOne).toCharArray());
BagOfPrimitives expectedTwo = new BagOfPrimitives(2, 2, false, "two");
writer.write(gson.toJson(expectedTwo).toCharArray());
CharArrayReader reader = new CharArrayReader(writer.toCharArray());
JsonReader parser = new JsonReader(reader);
parser.setLenient(true);
JsonElement element1 = Streams.parse(parser);
JsonElement element2 = Streams.parse(parser);
BagOfPrimitives actualOne = gson.fromJson(element1, BagOfPrimitives.class);
assertEquals("one", actualOne.stringValue);
BagOfPrimitives actualTwo = gson.fromJson(element2, BagOfPrimitives.class);
assertEquals("two", actualTwo.stringValue);
}
}
google-gson/src/test/java/com/google/gson/InnerClassExclusionStrategyTest.java 0000664 0001750 0001750 00000003456 11662650451 027516 0 ustar ebourg ebourg /*
* Copyright (C) 2008 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;
import com.google.gson.internal.Excluder;
import java.lang.reflect.Field;
import junit.framework.TestCase;
/**
* Unit test for GsonBuilder.EXCLUDE_INNER_CLASSES.
*
* @author Joel Leitch
*/
public class InnerClassExclusionStrategyTest extends TestCase {
public InnerClass innerClass = new InnerClass();
public StaticNestedClass staticNestedClass = new StaticNestedClass();
private Excluder excluder = Excluder.DEFAULT.disableInnerClassSerialization();
public void testExcludeInnerClassObject() throws Exception {
Class> clazz = innerClass.getClass();
assertTrue(excluder.excludeClass(clazz, true));
}
public void testExcludeInnerClassField() throws Exception {
Field f = getClass().getField("innerClass");
assertTrue(excluder.excludeField(f, true));
}
public void testIncludeStaticNestedClassObject() throws Exception {
Class> clazz = staticNestedClass.getClass();
assertFalse(excluder.excludeClass(clazz, true));
}
public void testIncludeStaticNestedClassField() throws Exception {
Field f = getClass().getField("staticNestedClass");
assertFalse(excluder.excludeField(f, true));
}
class InnerClass {
}
static class StaticNestedClass {
}
}
google-gson/src/test/java/com/google/gson/MixedStreamTest.java 0000664 0001750 0001750 00000016321 11651170612 024247 0 ustar ebourg ebourg /*
* 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;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.List;
import junit.framework.TestCase;
public final class MixedStreamTest extends TestCase {
private static final Car BLUE_MUSTANG = new Car("mustang", 0x0000FF);
private static final Car BLACK_BMW = new Car("bmw", 0x000000);
private static final Car RED_MIATA = new Car("miata", 0xFF0000);
private static final String CARS_JSON = "[\n"
+ " {\n"
+ " \"name\": \"mustang\",\n"
+ " \"color\": 255\n"
+ " },\n"
+ " {\n"
+ " \"name\": \"bmw\",\n"
+ " \"color\": 0\n"
+ " },\n"
+ " {\n"
+ " \"name\": \"miata\",\n"
+ " \"color\": 16711680\n"
+ " }\n"
+ "]";
public void testWriteMixedStreamed() throws IOException {
Gson gson = new Gson();
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.beginArray();
jsonWriter.setIndent(" ");
gson.toJson(BLUE_MUSTANG, Car.class, jsonWriter);
gson.toJson(BLACK_BMW, Car.class, jsonWriter);
gson.toJson(RED_MIATA, Car.class, jsonWriter);
jsonWriter.endArray();
assertEquals(CARS_JSON, stringWriter.toString());
}
public void testReadMixedStreamed() throws IOException {
Gson gson = new Gson();
StringReader stringReader = new StringReader(CARS_JSON);
JsonReader jsonReader = new JsonReader(stringReader);
jsonReader.beginArray();
assertEquals(BLUE_MUSTANG, gson.fromJson(jsonReader, Car.class));
assertEquals(BLACK_BMW, gson.fromJson(jsonReader, Car.class));
assertEquals(RED_MIATA, gson.fromJson(jsonReader, Car.class));
jsonReader.endArray();
}
public void testReaderDoesNotMutateState() throws IOException {
Gson gson = new Gson();
JsonReader jsonReader = new JsonReader(new StringReader(CARS_JSON));
jsonReader.beginArray();
jsonReader.setLenient(false);
gson.fromJson(jsonReader, Car.class);
assertFalse(jsonReader.isLenient());
jsonReader.setLenient(true);
gson.fromJson(jsonReader, Car.class);
assertTrue(jsonReader.isLenient());
}
public void testWriteDoesNotMutateState() throws IOException {
Gson gson = new Gson();
JsonWriter jsonWriter = new JsonWriter(new StringWriter());
jsonWriter.beginArray();
jsonWriter.setHtmlSafe(true);
jsonWriter.setLenient(true);
gson.toJson(BLUE_MUSTANG, Car.class, jsonWriter);
assertTrue(jsonWriter.isHtmlSafe());
assertTrue(jsonWriter.isLenient());
jsonWriter.setHtmlSafe(false);
jsonWriter.setLenient(false);
gson.toJson(BLUE_MUSTANG, Car.class, jsonWriter);
assertFalse(jsonWriter.isHtmlSafe());
assertFalse(jsonWriter.isLenient());
}
public void testReadInvalidState() throws IOException {
Gson gson = new Gson();
JsonReader jsonReader = new JsonReader(new StringReader(CARS_JSON));
jsonReader.beginArray();
jsonReader.beginObject();
try {
gson.fromJson(jsonReader, String.class);
fail();
} catch (JsonParseException expected) {
}
}
public void testReadClosed() throws IOException {
Gson gson = new Gson();
JsonReader jsonReader = new JsonReader(new StringReader(CARS_JSON));
jsonReader.close();
try {
gson.fromJson(jsonReader, new TypeToken>() {}.getType());
fail();
} catch (JsonParseException expected) {
}
}
public void testWriteInvalidState() throws IOException {
Gson gson = new Gson();
JsonWriter jsonWriter = new JsonWriter(new StringWriter());
jsonWriter.beginObject();
try {
gson.toJson(BLUE_MUSTANG, Car.class, jsonWriter);
fail();
} catch (IllegalStateException expected) {
}
}
public void testWriteClosed() throws IOException {
Gson gson = new Gson();
JsonWriter jsonWriter = new JsonWriter(new StringWriter());
jsonWriter.beginArray();
jsonWriter.endArray();
jsonWriter.close();
try {
gson.toJson(BLUE_MUSTANG, Car.class, jsonWriter);
fail();
} catch (IllegalStateException expected) {
}
}
public void testWriteNulls() {
Gson gson = new Gson();
try {
gson.toJson(new JsonPrimitive("hello"), (JsonWriter) null);
fail();
} catch (NullPointerException expected) {
}
StringWriter stringWriter = new StringWriter();
gson.toJson(null, new JsonWriter(stringWriter));
assertEquals("null", stringWriter.toString());
}
public void testReadNulls() {
Gson gson = new Gson();
try {
gson.fromJson((JsonReader) null, Integer.class);
fail();
} catch (NullPointerException expected) {
}
try {
gson.fromJson(new JsonReader(new StringReader("true")), null);
fail();
} catch (NullPointerException expected) {
}
}
public void testWriteHtmlSafe() {
List contents = Arrays.asList("<", ">", "&", "=", "'");
Type type = new TypeToken>() {}.getType();
StringWriter writer = new StringWriter();
new Gson().toJson(contents, type, new JsonWriter(writer));
assertEquals("[\"\\u003c\",\"\\u003e\",\"\\u0026\",\"\\u003d\",\"\\u0027\"]",
writer.toString());
writer = new StringWriter();
new GsonBuilder().disableHtmlEscaping().create()
.toJson(contents, type, new JsonWriter(writer));
assertEquals("[\"<\",\">\",\"&\",\"=\",\"'\"]",
writer.toString());
}
public void testWriteLenient() {
List doubles = Arrays.asList(Double.NaN, Double.NEGATIVE_INFINITY,
Double.POSITIVE_INFINITY, -0.0d, 0.5d, 0.0d);
Type type = new TypeToken>() {}.getType();
StringWriter writer = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(writer);
new GsonBuilder().serializeSpecialFloatingPointValues().create()
.toJson(doubles, type, jsonWriter);
assertEquals("[NaN,-Infinity,Infinity,-0.0,0.5,0.0]", writer.toString());
try {
new Gson().toJson(doubles, type, new JsonWriter(new StringWriter()));
fail();
} catch (IllegalArgumentException expected) {
}
}
static final class Car {
String name;
int color;
Car(String name, int color) {
this.name = name;
this.color = color;
}
// used by Gson
Car() {}
@Override public int hashCode() {
return name.hashCode() ^ color;
}
@Override public boolean equals(Object o) {
return o instanceof Car
&& ((Car) o).name.equals(name)
&& ((Car) o).color == color;
}
}
}
google-gson/src/test/java/com/google/gson/DefaultInetAddressTypeAdapterTest.java 0000664 0001750 0001750 00000002566 11512710124 027702 0 ustar ebourg ebourg /*
* Copyright (C) 2011 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;
import java.net.InetAddress;
import junit.framework.TestCase;
/**
* Unit tests for the default serializer/deserializer for the {@code InetAddress} type.
*
* @author Joel Leitch
*/
public class DefaultInetAddressTypeAdapterTest extends TestCase {
private Gson gson;
@Override
protected void setUp() throws Exception {
super.setUp();
gson = new Gson();
}
public void testInetAddressSerializationAndDeserialization() throws Exception {
InetAddress localhost = InetAddress.getLocalHost();
String localInetAddress = gson.toJson(localhost);
assertEquals("\"" + localhost.getHostAddress() + "\"", localInetAddress);
InetAddress value = gson.fromJson(localInetAddress, InetAddress.class);
assertEquals(localhost, value);
}
}
google-gson/src/test/java/com/google/gson/JsonNullTest.java 0000664 0001750 0001750 00000002440 12132064744 023571 0 ustar ebourg ebourg /*
* Copyright (C) 2011 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;
import com.google.gson.common.MoreAsserts;
import junit.framework.TestCase;
/**
* @author Jesse Wilson
*/
public final class JsonNullTest extends TestCase {
@SuppressWarnings("deprecation")
public void testEqualsAndHashcode() {
MoreAsserts.assertEqualsAndHashCode(new JsonNull(), new JsonNull());
MoreAsserts.assertEqualsAndHashCode(new JsonNull(), JsonNull.INSTANCE);
MoreAsserts.assertEqualsAndHashCode(JsonNull.INSTANCE, JsonNull.INSTANCE);
}
public void testDeepCopy() {
@SuppressWarnings("deprecation")
JsonNull a = new JsonNull();
assertSame(JsonNull.INSTANCE, a.deepCopy());
assertSame(JsonNull.INSTANCE, JsonNull.INSTANCE.deepCopy());
}
}
google-gson/src/test/java/com/google/gson/MockExclusionStrategy.java 0000664 0001750 0001750 00000002236 11546442367 025507 0 ustar ebourg ebourg /*
* Copyright (C) 2008 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;
/**
* This is a configurable {@link ExclusionStrategy} that can be used for
* unit testing.
*
* @author Joel Leitch
*/
final class MockExclusionStrategy implements ExclusionStrategy {
private final boolean skipClass;
private final boolean skipField;
public MockExclusionStrategy(boolean skipClass, boolean skipField) {
this.skipClass = skipClass;
this.skipField = skipField;
}
public boolean shouldSkipField(FieldAttributes f) {
return skipField;
}
public boolean shouldSkipClass(Class> clazz) {
return skipClass;
}
}
google-gson/src/test/java/com/google/gson/CommentsTest.java 0000664 0001750 0001750 00000002415 11435665115 023620 0 ustar ebourg ebourg /*
* 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;
import com.google.gson.reflect.TypeToken;
import java.util.Arrays;
import java.util.List;
import junit.framework.TestCase;
/**
* @author Jesse Wilson
*/
public final class CommentsTest extends TestCase {
/**
* Test for issue 212.
*/
public void testParseComments() {
String json = "[\n"
+ " // this is a comment\n"
+ " \"a\",\n"
+ " /* this is another comment */\n"
+ " \"b\",\n"
+ " # this is yet another comment\n"
+ " \"c\"\n"
+ "]";
List abc = new Gson().fromJson(json, new TypeToken>() {}.getType());
assertEquals(Arrays.asList("a", "b", "c"), abc);
}
}
google-gson/src/test/java/com/google/gson/JsonPrimitiveTest.java 0000664 0001750 0001750 00000022043 12014561057 024626 0 ustar ebourg ebourg /*
* Copyright (C) 2008 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;
import com.google.gson.common.MoreAsserts;
import junit.framework.TestCase;
import java.math.BigDecimal;
import java.math.BigInteger;
/**
* Unit test for the {@link JsonPrimitive} class.
*
* @author Joel Leitch
*/
public class JsonPrimitiveTest extends TestCase {
public void testBoolean() throws Exception {
JsonPrimitive json = new JsonPrimitive(Boolean.TRUE);
assertTrue(json.isBoolean());
assertTrue(json.getAsBoolean());
// Extra support for booleans
json = new JsonPrimitive(1);
assertFalse(json.getAsBoolean());
json = new JsonPrimitive("1");
assertFalse(json.getAsBoolean());
json = new JsonPrimitive("true");
assertTrue(json.getAsBoolean());
json = new JsonPrimitive("TrUe");
assertTrue(json.getAsBoolean());
json = new JsonPrimitive("1.3");
assertFalse(json.getAsBoolean());
}
public void testParsingStringAsBoolean() throws Exception {
JsonPrimitive json = new JsonPrimitive("true");
assertFalse(json.isBoolean());
assertTrue(json.getAsBoolean());
}
public void testParsingStringAsNumber() throws Exception {
JsonPrimitive json = new JsonPrimitive("1");
assertFalse(json.isNumber());
assertEquals(1D, json.getAsDouble(), 0.00001);
assertEquals(1F, json.getAsFloat(), 0.00001);
assertEquals(1, json.getAsInt());
assertEquals(1L, json.getAsLong());
assertEquals((short) 1, json.getAsShort());
assertEquals((byte) 1, json.getAsByte());
assertEquals(new BigInteger("1"), json.getAsBigInteger());
assertEquals(new BigDecimal("1"), json.getAsBigDecimal());
}
public void testStringsAndChar() throws Exception {
JsonPrimitive json = new JsonPrimitive("abc");
assertTrue(json.isString());
assertEquals('a', json.getAsCharacter());
assertEquals("abc", json.getAsString());
json = new JsonPrimitive('z');
assertTrue(json.isString());
assertEquals('z', json.getAsCharacter());
assertEquals("z", json.getAsString());
}
public void testExponential() throws Exception {
JsonPrimitive json = new JsonPrimitive("1E+7");
assertEquals(new BigDecimal("1E+7"), json.getAsBigDecimal());
assertEquals(new Double("1E+7"), json.getAsDouble(), 0.00001);
assertEquals(new Float("1E+7"), json.getAsDouble(), 0.00001);
try {
json.getAsInt();
fail("Integers can not handle exponents like this.");
} catch (NumberFormatException expected) { }
}
public void testByteEqualsShort() {
JsonPrimitive p1 = new JsonPrimitive(new Byte((byte)10));
JsonPrimitive p2 = new JsonPrimitive(new Short((short)10));
assertEquals(p1, p2);
assertEquals(p1.hashCode(), p2.hashCode());
}
public void testByteEqualsInteger() {
JsonPrimitive p1 = new JsonPrimitive(new Byte((byte)10));
JsonPrimitive p2 = new JsonPrimitive(new Integer(10));
assertEquals(p1, p2);
assertEquals(p1.hashCode(), p2.hashCode());
}
public void testByteEqualsLong() {
JsonPrimitive p1 = new JsonPrimitive(new Byte((byte)10));
JsonPrimitive p2 = new JsonPrimitive(new Long(10L));
assertEquals(p1, p2);
assertEquals(p1.hashCode(), p2.hashCode());
}
public void testByteEqualsBigInteger() {
JsonPrimitive p1 = new JsonPrimitive(new Byte((byte)10));
JsonPrimitive p2 = new JsonPrimitive(new BigInteger("10"));
assertEquals(p1, p2);
assertEquals(p1.hashCode(), p2.hashCode());
}
public void testShortEqualsInteger() {
JsonPrimitive p1 = new JsonPrimitive(new Short((short)10));
JsonPrimitive p2 = new JsonPrimitive(new Integer(10));
assertEquals(p1, p2);
assertEquals(p1.hashCode(), p2.hashCode());
}
public void testShortEqualsLong() {
JsonPrimitive p1 = new JsonPrimitive(new Short((short)10));
JsonPrimitive p2 = new JsonPrimitive(new Long(10));
assertEquals(p1, p2);
assertEquals(p1.hashCode(), p2.hashCode());
}
public void testShortEqualsBigInteger() {
JsonPrimitive p1 = new JsonPrimitive(new Short((short)10));
JsonPrimitive p2 = new JsonPrimitive(new BigInteger("10"));
assertEquals(p1, p2);
assertEquals(p1.hashCode(), p2.hashCode());
}
public void testIntegerEqualsLong() {
JsonPrimitive p1 = new JsonPrimitive(new Integer(10));
JsonPrimitive p2 = new JsonPrimitive(new Long(10L));
assertEquals(p1, p2);
assertEquals(p1.hashCode(), p2.hashCode());
}
public void testIntegerEqualsBigInteger() {
JsonPrimitive p1 = new JsonPrimitive(new Integer(10));
JsonPrimitive p2 = new JsonPrimitive(new BigInteger("10"));
assertEquals(p1, p2);
assertEquals(p1.hashCode(), p2.hashCode());
}
public void testLongEqualsBigInteger() {
JsonPrimitive p1 = new JsonPrimitive(new Long(10L));
JsonPrimitive p2 = new JsonPrimitive(new BigInteger("10"));
assertEquals(p1, p2);
assertEquals(p1.hashCode(), p2.hashCode());
}
public void testFloatEqualsDouble() {
JsonPrimitive p1 = new JsonPrimitive(new Float(10.25F));
JsonPrimitive p2 = new JsonPrimitive(new Double(10.25D));
assertEquals(p1, p2);
assertEquals(p1.hashCode(), p2.hashCode());
}
public void testFloatEqualsBigDecimal() {
JsonPrimitive p1 = new JsonPrimitive(new Float(10.25F));
JsonPrimitive p2 = new JsonPrimitive(new BigDecimal("10.25"));
assertEquals(p1, p2);
assertEquals(p1.hashCode(), p2.hashCode());
}
public void testDoubleEqualsBigDecimal() {
JsonPrimitive p1 = new JsonPrimitive(new Double(10.25D));
JsonPrimitive p2 = new JsonPrimitive(new BigDecimal("10.25"));
assertEquals(p1, p2);
assertEquals(p1.hashCode(), p2.hashCode());
}
public void testValidJsonOnToString() throws Exception {
JsonPrimitive json = new JsonPrimitive("Some\nEscaped\nValue");
assertEquals("\"Some\\nEscaped\\nValue\"", json.toString());
json = new JsonPrimitive(new BigDecimal("1.333"));
assertEquals("1.333", json.toString());
}
public void testEquals() {
MoreAsserts.assertEqualsAndHashCode(new JsonPrimitive("A"), new JsonPrimitive("A"));
MoreAsserts.assertEqualsAndHashCode(new JsonPrimitive(true), new JsonPrimitive(true));
MoreAsserts.assertEqualsAndHashCode(new JsonPrimitive(5L), new JsonPrimitive(5L));
MoreAsserts.assertEqualsAndHashCode(new JsonPrimitive('a'), new JsonPrimitive('a'));
MoreAsserts.assertEqualsAndHashCode(new JsonPrimitive(Float.NaN), new JsonPrimitive(Float.NaN));
MoreAsserts.assertEqualsAndHashCode(new JsonPrimitive(Float.NEGATIVE_INFINITY),
new JsonPrimitive(Float.NEGATIVE_INFINITY));
MoreAsserts.assertEqualsAndHashCode(new JsonPrimitive(Float.POSITIVE_INFINITY),
new JsonPrimitive(Float.POSITIVE_INFINITY));
MoreAsserts.assertEqualsAndHashCode(new JsonPrimitive(Double.NaN), new JsonPrimitive(Double.NaN));
MoreAsserts.assertEqualsAndHashCode(new JsonPrimitive(Double.NEGATIVE_INFINITY),
new JsonPrimitive(Double.NEGATIVE_INFINITY));
MoreAsserts.assertEqualsAndHashCode(new JsonPrimitive(Double.POSITIVE_INFINITY),
new JsonPrimitive(Double.POSITIVE_INFINITY));
assertFalse(new JsonPrimitive("a").equals(new JsonPrimitive("b")));
assertFalse(new JsonPrimitive(true).equals(new JsonPrimitive(false)));
assertFalse(new JsonPrimitive(0).equals(new JsonPrimitive(1)));
}
public void testEqualsAcrossTypes() {
MoreAsserts.assertEqualsAndHashCode(new JsonPrimitive("a"), new JsonPrimitive('a'));
MoreAsserts.assertEqualsAndHashCode(new JsonPrimitive(new BigInteger("0")), new JsonPrimitive(0));
MoreAsserts.assertEqualsAndHashCode(new JsonPrimitive(0), new JsonPrimitive(0L));
MoreAsserts.assertEqualsAndHashCode(new JsonPrimitive(new BigInteger("0")), new JsonPrimitive(0));
MoreAsserts.assertEqualsAndHashCode(new JsonPrimitive(Float.NaN), new JsonPrimitive(Double.NaN));
}
public void testEqualsIntegerAndBigInteger() {
JsonPrimitive a = new JsonPrimitive(5L);
JsonPrimitive b = new JsonPrimitive(new BigInteger("18446744073709551621")); // 2^64 + 5
// Ideally, the following assertion should have failed but the price is too much to pay
// assertFalse(a + " equals " + b, a.equals(b));
assertTrue(a + " equals " + b, a.equals(b));
}
public void testEqualsDoesNotEquateStringAndNonStringTypes() {
assertFalse(new JsonPrimitive("true").equals(new JsonPrimitive(true)));
assertFalse(new JsonPrimitive("0").equals(new JsonPrimitive(0)));
assertFalse(new JsonPrimitive("NaN").equals(new JsonPrimitive(Float.NaN)));
}
public void testDeepCopy() {
JsonPrimitive a = new JsonPrimitive("a");
assertSame(a, a.deepCopy()); // Primitives are immutable!
}
}
google-gson/src/test/java/com/google/gson/GsonTypeAdapterTest.java 0000664 0001750 0001750 00000012654 12043527451 025106 0 ustar ebourg ebourg /*
* Copyright (C) 2008 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;
import java.lang.reflect.Type;
import java.math.BigInteger;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import junit.framework.TestCase;
/**
* Contains numerous tests involving registered type converters with a Gson instance.
*
* @author Inderjeet Singh
* @author Joel Leitch
*/
public class GsonTypeAdapterTest extends TestCase {
private Gson gson;
@Override
protected void setUp() throws Exception {
super.setUp();
gson = new GsonBuilder()
.registerTypeAdapter(AtomicLong.class, new ExceptionTypeAdapter())
.registerTypeAdapter(AtomicInteger.class, new AtomicIntegerTypeAdapter())
.create();
}
public void testDefaultTypeAdapterThrowsParseException() throws Exception {
try {
gson.fromJson("{\"abc\":123}", BigInteger.class);
fail("Should have thrown a JsonParseException");
} catch (JsonParseException expected) { }
}
public void testTypeAdapterThrowsException() throws Exception {
try {
gson.toJson(new AtomicLong(0));
fail("Type Adapter should have thrown an exception");
} catch (IllegalStateException expected) { }
try {
gson.fromJson("123", AtomicLong.class);
fail("Type Adapter should have thrown an exception");
} catch (JsonParseException expected) { }
}
public void testTypeAdapterProperlyConvertsTypes() throws Exception {
int intialValue = 1;
AtomicInteger atomicInt = new AtomicInteger(intialValue);
String json = gson.toJson(atomicInt);
assertEquals(intialValue + 1, Integer.parseInt(json));
atomicInt = gson.fromJson(json, AtomicInteger.class);
assertEquals(intialValue, atomicInt.get());
}
public void testTypeAdapterDoesNotAffectNonAdaptedTypes() throws Exception {
String expected = "blah";
String actual = gson.toJson(expected);
assertEquals("\"" + expected + "\"", actual);
actual = gson.fromJson(actual, String.class);
assertEquals(expected, actual);
}
private static class ExceptionTypeAdapter
implements JsonSerializer, JsonDeserializer {
public JsonElement serialize(
AtomicLong src, Type typeOfSrc, JsonSerializationContext context) {
throw new IllegalStateException();
}
public AtomicLong deserialize(
JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
throw new IllegalStateException();
}
}
private static class AtomicIntegerTypeAdapter
implements JsonSerializer, JsonDeserializer {
public JsonElement serialize(AtomicInteger src, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(src.incrementAndGet());
}
public AtomicInteger deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
int intValue = json.getAsInt();
return new AtomicInteger(--intValue);
}
}
static abstract class Abstract {
String a;
}
static class Concrete extends Abstract {
String b;
}
// https://groups.google.com/d/topic/google-gson/EBmOCa8kJPE/discussion
public void testDeserializerForAbstractClass() {
Concrete instance = new Concrete();
instance.a = "android";
instance.b = "beep";
assertSerialized("{\"a\":\"android\"}", Abstract.class, true, true, instance);
assertSerialized("{\"a\":\"android\"}", Abstract.class, true, false, instance);
assertSerialized("{\"a\":\"android\"}", Abstract.class, false, true, instance);
assertSerialized("{\"a\":\"android\"}", Abstract.class, false, false, instance);
assertSerialized("{\"b\":\"beep\",\"a\":\"android\"}", Concrete.class, true, true, instance);
assertSerialized("{\"b\":\"beep\",\"a\":\"android\"}", Concrete.class, true, false, instance);
assertSerialized("{\"b\":\"beep\",\"a\":\"android\"}", Concrete.class, false, true, instance);
assertSerialized("{\"b\":\"beep\",\"a\":\"android\"}", Concrete.class, false, false, instance);
}
private void assertSerialized(String expected, Class> instanceType, boolean registerAbstractDeserializer,
boolean registerAbstractHierarchyDeserializer, Object instance) {
JsonDeserializer deserializer = new JsonDeserializer() {
public Abstract deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
throw new AssertionError();
}
};
GsonBuilder builder = new GsonBuilder();
if (registerAbstractDeserializer) {
builder.registerTypeAdapter(Abstract.class, deserializer);
}
if (registerAbstractHierarchyDeserializer) {
builder.registerTypeHierarchyAdapter(Abstract.class, deserializer);
}
Gson gson = builder.create();
assertEquals(expected, gson.toJson(instance, instanceType));
}
}
google-gson/src/test/java/com/google/gson/metrics/ 0000775 0001750 0001750 00000000000 12207114635 021766 5 ustar ebourg ebourg google-gson/src/test/java/com/google/gson/metrics/PerformanceTest.java 0000664 0001750 0001750 00000024776 11433073202 025744 0 ustar ebourg ebourg /*
* Copyright (C) 2008 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.metrics;
import com.google.gson.Gson;
import com.google.gson.JsonParseException;
import com.google.gson.annotations.Expose;
import com.google.gson.reflect.TypeToken;
import junit.framework.TestCase;
import java.io.StringWriter;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Tests to measure performance for Gson. All tests in this file will be disabled in code. To run
* them remove disabled_ prefix from the tests and run them.
*
* @author Inderjeet Singh
* @author Joel Leitch
*/
public class PerformanceTest extends TestCase {
private static final int COLLECTION_SIZE = 5000;
private static final int NUM_ITERATIONS = 100;
private Gson gson;
@Override
protected void setUp() throws Exception {
super.setUp();
gson = new Gson();
}
public void testDummy() {
// This is here to prevent Junit for complaining when we disable all tests.
}
public void disabled_testStringDeserialization() {
StringBuilder sb = new StringBuilder(8096);
sb.append("Error Yippie");
while (true) {
try {
String stackTrace = sb.toString();
sb.append(stackTrace);
String json = "{\"message\":\"Error message.\"," + "\"stackTrace\":\"" + stackTrace + "\"}";
parseLongJson(json);
System.out.println("Gson could handle a string of size: " + stackTrace.length());
} catch (JsonParseException expected) {
break;
}
}
}
private void parseLongJson(String json) throws JsonParseException {
ExceptionHolder target = gson.fromJson(json, ExceptionHolder.class);
assertTrue(target.message.contains("Error"));
assertTrue(target.stackTrace.contains("Yippie"));
}
private static class ExceptionHolder {
public final String message;
public final String stackTrace;
// For use by Gson
@SuppressWarnings("unused")
private ExceptionHolder() {
this("", "");
}
public ExceptionHolder(String message, String stackTrace) {
this.message = message;
this.stackTrace = stackTrace;
}
}
@SuppressWarnings("unused")
private static class CollectionEntry {
final String name;
final String value;
// For use by Gson
private CollectionEntry() {
this(null, null);
}
CollectionEntry(String name, String value) {
this.name = name;
this.value = value;
}
}
/**
* Created in response to http://code.google.com/p/google-gson/issues/detail?id=96
*/
public void disabled_testLargeCollectionSerialization() {
int count = 1400000;
List list = new ArrayList(count);
for (int i = 0; i < count; ++i) {
list.add(new CollectionEntry("name"+i,"value"+i));
}
gson.toJson(list);
}
/**
* Created in response to http://code.google.com/p/google-gson/issues/detail?id=96
*/
public void disabled_testLargeCollectionDeserialization() {
StringBuilder sb = new StringBuilder();
int count = 87000;
boolean first = true;
sb.append('[');
for (int i = 0; i < count; ++i) {
if (first) {
first = false;
} else {
sb.append(',');
}
sb.append("{name:'name").append(i).append("',value:'value").append(i).append("'}");
}
sb.append(']');
String json = sb.toString();
Type collectionType = new TypeToken>(){}.getType();
List list = gson.fromJson(json, collectionType);
assertEquals(count, list.size());
}
/**
* Created in response to http://code.google.com/p/google-gson/issues/detail?id=96
*/
// Last I tested, Gson was able to serialize upto 14MB byte array
public void disabled_testByteArraySerialization() {
for (int size = 4145152; true; size += 1036288) {
byte[] ba = new byte[size];
for (int i = 0; i < size; ++i) {
ba[i] = 0x05;
}
gson.toJson(ba);
System.out.printf("Gson could serialize a byte array of size: %d\n", size);
}
}
/**
* Created in response to http://code.google.com/p/google-gson/issues/detail?id=96
*/
// Last I tested, Gson was able to deserialize a byte array of 11MB
public void disable_testByteArrayDeserialization() {
for (int numElements = 10639296; true; numElements += 16384) {
StringBuilder sb = new StringBuilder(numElements*2);
sb.append("[");
boolean first = true;
for (int i = 0; i < numElements; ++i) {
if (first) {
first = false;
} else {
sb.append(",");
}
sb.append("5");
}
sb.append("]");
String json = sb.toString();
byte[] ba = gson.fromJson(json, byte[].class);
System.out.printf("Gson could deserialize a byte array of size: %d\n", ba.length);
}
}
// The tests to measure serialization and deserialization performance of Gson
// Based on the discussion at
// http://groups.google.com/group/google-gson/browse_thread/thread/7a50b17a390dfaeb
// Test results: 10/19/2009
// Serialize classes avg time: 60 ms
// Deserialized classes avg time: 70 ms
// Serialize exposed classes avg time: 159 ms
// Deserialized exposed classes avg time: 173 ms
public void disabled_testSerializeClasses() {
ClassWithList c = new ClassWithList("str");
for (int i = 0; i < COLLECTION_SIZE; ++i) {
c.list.add(new ClassWithField("element-" + i));
}
StringWriter w = new StringWriter();
long t1 = System.currentTimeMillis();
for (int i = 0; i < NUM_ITERATIONS; ++i) {
gson.toJson(c, w);
}
long t2 = System.currentTimeMillis();
long avg = (t2 - t1) / NUM_ITERATIONS;
System.out.printf("Serialize classes avg time: %d ms\n", avg);
}
public void disabled_testDeserializeClasses() {
String json = buildJsonForClassWithList();
ClassWithList[] target = new ClassWithList[NUM_ITERATIONS];
long t1 = System.currentTimeMillis();
for (int i = 0; i < NUM_ITERATIONS; ++i) {
target[i] = gson.fromJson(json, ClassWithList.class);
}
long t2 = System.currentTimeMillis();
long avg = (t2 - t1) / NUM_ITERATIONS;
System.out.printf("Deserialize classes avg time: %d ms\n", avg);
}
public void disable_testLargeObjectSerializationAndDeserialization() {
Map largeObject = new HashMap();
for (long l = 0; l < 100000; l++) {
largeObject.put("field" + l, l);
}
long t1 = System.currentTimeMillis();
String json = gson.toJson(largeObject);
long t2 = System.currentTimeMillis();
System.out.printf("Large object serialized in: %d ms\n", (t2 - t1));
t1 = System.currentTimeMillis();
gson.fromJson(json, new TypeToken