gson-comments/gson/src/main/java/com/google/gson/internal/bind/TreeTypeAdapter.java

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

203 lines
7.1 KiB
Java
Raw Normal View History

/*
* 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.internal.bind;
import com.google.gson.Gson;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.internal.$Gson$Preconditions;
import com.google.gson.internal.Streams;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.lang.reflect.Type;
/**
* Adapts a Gson 1.x tree-style adapter as a streaming TypeAdapter. Since the tree adapter may be
* serialization-only or deserialization-only, this class has a facility to look up a delegate type
* adapter on demand.
*/
public final class TreeTypeAdapter<T> extends SerializationDelegatingTypeAdapter<T> {
private final JsonSerializer<T> serializer;
private final JsonDeserializer<T> deserializer;
final Gson gson;
private final TypeToken<T> typeToken;
/**
* Only intended as {@code skipPast} for {@link Gson#getDelegateAdapter(TypeAdapterFactory,
* TypeToken)}, must not be used in any other way.
*/
private final TypeAdapterFactory skipPastForGetDelegateAdapter;
private final GsonContextImpl context = new GsonContextImpl();
private final boolean nullSafe;
/**
* The delegate is lazily created because it may not be needed, and creating it may fail. Field
* has to be {@code volatile} because {@link Gson} guarantees to be thread-safe.
*/
private volatile TypeAdapter<T> delegate;
public TreeTypeAdapter(
JsonSerializer<T> serializer,
JsonDeserializer<T> deserializer,
Gson gson,
TypeToken<T> typeToken,
TypeAdapterFactory skipPast,
boolean nullSafe) {
this.serializer = serializer;
this.deserializer = deserializer;
this.gson = gson;
this.typeToken = typeToken;
this.skipPastForGetDelegateAdapter = skipPast;
this.nullSafe = nullSafe;
}
public TreeTypeAdapter(
JsonSerializer<T> serializer,
JsonDeserializer<T> deserializer,
Gson gson,
TypeToken<T> typeToken,
TypeAdapterFactory skipPast) {
this(serializer, deserializer, gson, typeToken, skipPast, true);
}
2011-12-03 20:46:25 +01:00
@Override
public T read(JsonReader in) throws IOException {
if (deserializer == null) {
2011-12-03 20:46:25 +01:00
return delegate().read(in);
}
2011-12-03 20:46:25 +01:00
JsonElement value = Streams.parse(in);
if (nullSafe && value.isJsonNull()) {
return null;
}
return deserializer.deserialize(value, typeToken.getType(), context);
}
2011-12-03 20:46:25 +01:00
@Override
public void write(JsonWriter out, T value) throws IOException {
if (serializer == null) {
2011-12-03 20:46:25 +01:00
delegate().write(out, value);
return;
}
if (nullSafe && value == null) {
2011-12-03 20:46:25 +01:00
out.nullValue();
return;
}
JsonElement tree = serializer.serialize(value, typeToken.getType(), context);
2011-12-03 20:46:25 +01:00
Streams.write(tree, out);
}
private TypeAdapter<T> delegate() {
// A race might lead to `delegate` being assigned by multiple threads but the last assignment
// will stick
TypeAdapter<T> d = delegate;
return d != null
? d
: (delegate = gson.getDelegateAdapter(skipPastForGetDelegateAdapter, typeToken));
}
/**
* Returns the type adapter which is used for serialization. Returns {@code this} if this {@code
* TreeTypeAdapter} has a {@link #serializer}; otherwise returns the delegate.
*/
@Override
public TypeAdapter<T> getSerializationDelegate() {
return serializer != null ? this : delegate();
}
/** Returns a new factory that will match each type against {@code exactType}. */
public static TypeAdapterFactory newFactory(TypeToken<?> exactType, Object typeAdapter) {
return new SingleTypeFactory(typeAdapter, exactType, false, null);
}
/** Returns a new factory that will match each type and its raw type against {@code exactType}. */
public static TypeAdapterFactory newFactoryWithMatchRawType(
TypeToken<?> exactType, Object typeAdapter) {
// only bother matching raw types if exact type is a raw type
boolean matchRawType = exactType.getType() == exactType.getRawType();
return new SingleTypeFactory(typeAdapter, exactType, matchRawType, null);
}
/**
* Returns a new factory that will match each type's raw type for assignability to {@code
* hierarchyType}.
*/
public static TypeAdapterFactory newTypeHierarchyFactory(
Class<?> hierarchyType, Object typeAdapter) {
return new SingleTypeFactory(typeAdapter, null, false, hierarchyType);
}
private static final class SingleTypeFactory implements TypeAdapterFactory {
private final TypeToken<?> exactType;
private final boolean matchRawType;
private final Class<?> hierarchyType;
private final JsonSerializer<?> serializer;
private final JsonDeserializer<?> deserializer;
SingleTypeFactory(
Object typeAdapter, TypeToken<?> exactType, boolean matchRawType, Class<?> hierarchyType) {
serializer = typeAdapter instanceof JsonSerializer ? (JsonSerializer<?>) typeAdapter : null;
2011-12-04 11:24:07 +01:00
deserializer =
typeAdapter instanceof JsonDeserializer ? (JsonDeserializer<?>) typeAdapter : null;
$Gson$Preconditions.checkArgument(serializer != null || deserializer != null);
this.exactType = exactType;
this.matchRawType = matchRawType;
this.hierarchyType = hierarchyType;
}
@SuppressWarnings("unchecked") // guarded by typeToken.equals() call
@Override
2011-12-02 23:57:30 +01:00
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
boolean matches =
exactType != null
Fix error prone warnings (#2316) * Fix `OperatorPrecedence` warn in `JsonWriter#close` * Fix `ReferenceEquality` warn in `LinkedTreeMap#replaceInParent` * Fix `UnnecessaryParentheses` warn in `LinkedTreeMap#replaceInParent` * Fix `ReferenceEquality` warn in `LinkedTreeMap#hasNext` * Fix `ReferenceEquality` warn in `LinkedTreeMap#nextNode` * Adds `error_prone_annotations` to the `pom.xml` of `gson` * Fix `InlineMeSuggester` warns in `JsonParser` * Fix `UnnecessaryParentheses` warns in `ConstructorConstructor#newDefaultImplementationConstructor` * Fix `ThreadLocalUsage` warn in `Gson` * Fix `JdkObsolete` warn in `GsonBuilder` * Fix `ReferenceEquality` warn in `LazilyParsedNumber#equals` * Fix `OperatorPrecedence` warn in `TreeTypeAdapter#create` * Fix `OperatorPrecedence` warn in `ArrayTypeAdapter` * Fix `UnnecessaryParentheses` warn in `TypeAdapters` * Adds `-XepExcludedPaths` flag to ErrorProne plugin to exclude tests and proto path * Fix `ClassNewInstance` warn in `InterceptorAdapter` * Fix `ThreadLocalUsage` warn in `GraphAdapterBuilder` * Fix `JdkObsolete` warn in `GraphAdapterBuilder` * Revert "Adds `error_prone_annotations` to the `pom.xml` of `gson`" This reverts commit 14af14dfa23b46a54f4855a70ccf2b0a2cdc3e3f. * Revert "Fix `InlineMeSuggester` warns in `JsonParser`" This reverts commit 095bfd517e06510e4cc9cc6b1aac58ad9bf3038a. * Adds `@SuppressWarnings("ThreadLocalUsage")` * Fix `OperatorPrecedence` in `JsonWriter` * Revert "Fix `ReferenceEquality` warn in `LinkedTreeMap#nextNode`" This reverts commit 387746c7f7e3d0943c8f80501f5d9c3710f4862e. * Adds `@SuppressWarnings("ReferenceEquality")` * Adds `guava-testlib` to the gson `pom.xml` * `@SuppressWarnings("TruthSelfEquals")` removed to use `EqualsTester()`
2023-02-15 14:18:43 +01:00
? exactType.equals(type) || (matchRawType && exactType.getType() == type.getRawType())
: hierarchyType.isAssignableFrom(type.getRawType());
return matches
? new TreeTypeAdapter<>(
2011-12-02 23:57:30 +01:00
(JsonSerializer<T>) serializer, (JsonDeserializer<T>) deserializer, gson, type, this)
: null;
}
}
private final class GsonContextImpl
implements JsonSerializationContext, JsonDeserializationContext {
@Override
public JsonElement serialize(Object src) {
return gson.toJsonTree(src);
}
@Override
public JsonElement serialize(Object src, Type typeOfSrc) {
return gson.toJsonTree(src, typeOfSrc);
}
Fix error prone warns (#2320) * Adds `@SuppressWarnings("NarrowingCompoundAssignment")` * Adds `@SuppressWarnings("TypeParameterUnusedInFormals")` * Adds `@SuppressWarnings("JavaUtilDate")` * Adds a limit to `String.split()` * Add `error_prone_annotations` to the `pom.xml` * Adds `@InlineMe(...)` to deprecated methods * Adds `@SuppressWarnings("ImmutableEnumChecker")` * Adds `@SuppressWarnings("ModifiedButNotUsed")` * Adds `@SuppressWarnings("MixedMutabilityReturnType")` * Removes an unused import * Adds `requires` to `module-info.java` * Adds ErrorProne `link` into `pom.xml` * Remove unused imports Removed from: - ParseBenchmark * Adds `@SuppressWarnings("EqualsGetClass")` * Excludes from `proto` just the generated code. Replaces `.*proto.*` with `.*/generated-test-sources/protobuf/.*` in such way will be excluded just the generated code and not the whole `proto` directory * Removes an unused variable Removes the `descriptor` variable because is unused. * Fixes the `BadImport` warn into `ProtosWithAnnotationsTest` * Fixes the `BadImport` warns into `ProtosWithAnnotationsTest` * Enables ErrorProne in `gson/src/test.*` Removes the `gson/src/test.*` path from the `-XepExcludedPaths` parameter of the ErrorProne plugin * Fixes `UnusedVariable` warns This commit fix all `UnusedVariable` warns given by ErrorProne in the `gson/src/test.*` path. Some field is annotated with `@Keep` that means is used by reflection. In some other case the record is annotated with `@SuppressWarnings("unused")` * Fixes `JavaUtilDate` warns This commit fix all `JavaUtilDate` warns given by ErrorProne in the `gson/src/test.*` path. Classes/Methods are annotated with `@SuppressWarnings("JavaUtilDate")` because it's not possible use differente Date API. * Fixes `EqualsGetClass` warns This commit fix all `EqualsGetClass` warns given by ErrorProne in the `gson/src/test.*` path. I have rewrite the `equals()` methods to use `instanceof` * Replaces pattern matching for instanceof with casts * Fixes `JdkObsolete` warns This commit fix all `JdkObsolete` warns given by ErrorProne in the `gson/src/test.*` path. In some cases I have replaced the obsolete JDK classes with the newest alternatives. In other cases, I have added the `@SuppressWarnings("JdkObsolete")` * Fixes `ClassCanBeStatic` warns This commit fix all `ClassCanBeStatic` warns given by ErrorProne in the `gson/src/test.*` path. I have added the `static` keyword, or I have added `@SuppressWarnings("ClassCanBeStatic")` * Fixes `UndefinedEquals` warns This commit fix all `UndefinedEquals` warns given by ErrorProne in the `gson/src/test.*` path. I have added `@SuppressWarnings("UndefinedEquals")` or fixed the asserts Note: In this commit I have also renamed a test from `testRawCollectionDeserializationNotAlllowed` to `testRawCollectionDeserializationNotAllowed` * Fixes `GetClassOnEnum` warns This commit fix all `GetClassOnEnum` warns given by ErrorProne in the `gson/src/test.*` path. I have replaced the `.getClass()` with `.getDeclaringClass()` * Fixes `ImmutableEnumChecker` warns This commit fix all `ImmutableEnumChecker` warns given by ErrorProne in the `gson/src/test.*` path. I have added the `final` keyword, or I have added the `@SuppressWarnings("ImmutableEnumChecker")` annotation * Fixes `StaticAssignmentOfThrowable` warns This commit fix all `StaticAssignmentOfThrowable` warns given by ErrorProne in the `gson/src/test.*` path. * Fixes `AssertionFailureIgnored` warns This commit fix all `AssertionFailureIgnored` warns given by ErrorProne in the `gson/src/test.*` path. I have added the `@SuppressWarnings("AssertionFailureIgnored")` annotation * Fixes `ModifiedButNotUsed` warns This commit fix all `ModifiedButNotUsed` warns given by ErrorProne in the `gson/src/test.*` path. I have added the `@SuppressWarnings("ModifiedButNotUsed")` annotation * Fixes `MissingSummary` warns This commit fix all `MissingSummary` warns given by ErrorProne in the `gson/src/test.*` path. I have remove the Javadoc `@author` * Fixes `FloatingPointLiteralPrecision` warns This commit fix all `FloatingPointLiteralPrecision` warns given by ErrorProne in the `gson/src/test.*` path. I have added the `@SuppressWarnings("FloatingPointLiteralPrecision")` annotation * Fixes `StringSplitter` warns This commit fix all `StringSplitter` warns given by ErrorProne in the `gson/src/test.*` path. I have replaced the `String.split(...)` with `Splitter` * Fixes `EmptyCatch` warns This commit fix all `EmptyCatch` warns given by ErrorProne in the `gson/src/test.*` path. * Fixes `UnicodeEscape` warns This commit fix all `UnicodeEscape` warns given by ErrorProne in the `gson/src/test.*` path. * Fixes `EmptyBlockTag` warns This commit fix all `EmptyBlockTag` warns given by ErrorProne in the `gson/src/test.*` path. * Fixes `LongFloatConversion` warns This commit fix all `LongFloatConversion` warns given by ErrorProne in the `gson/src/test.*` path. * Fixes `LongDoubleConversion` warns This commit fix all `LongDoubleConversion` warns given by ErrorProne in the `gson/src/test.*` path. * Fixes `TruthAssertExpected` warns This commit fix all `TruthAssertExpected` warns given by ErrorProne in the `gson/src/test.*` path. * Fixes `UnusedMethod` warns This commit fix all `UnusedMethod` warns given by ErrorProne in the `gson/src/test.*` path. * Fixes `UnusedTypeParameter` warns This commit fix all `UnusedTypeParameter` warns given by ErrorProne in the `gson/src/test.*` path. * Fixes `CatchFail` warns This commit fix all `CatchFail` warns given by ErrorProne in the `gson/src/test.*` path. * Fixes `MathAbsoluteNegative` warns This commit fix all `MathAbsoluteNegative` warns given by ErrorProne in the `gson/src/test.*` path. * Fixes `LoopOverCharArray` warns This commit fix all `LoopOverCharArray` warns given by ErrorProne in the `gson/src/test.*` path. `toCharArray` allocates a new array, using `charAt` is more efficient * Fixes `HidingField` warns This commit fix all `HidingField` warns given by ErrorProne in the `gson/src/test.*` path. * Implements code review feedback * Implements code review feedback This commit implements some other code review feedback * Enable ErrorProne in `extra` Thi commit removes the `.*extras/src/test.*` path from the `-XepExcludedPaths` parameter of ErrorProne. * Fix the `JavaUtilDate` warns This commit fix all `JavaUtilDate` warns given by ErrorProne in the `extras/src/test.*` path. * Implements code review feedback * Removes redundant new-line * Implements code review feedback * Adds `JDK11` to run test with `--release 11` * Revert "Adds `JDK11` to run test with `--release 11`" This reverts commit a7cca386098ae847a10a31c09c3ab9b11eee5920.
2023-03-01 23:23:27 +01:00
@Override
@SuppressWarnings({"unchecked", "TypeParameterUnusedInFormals"})
public <R> R deserialize(JsonElement json, Type typeOfT) throws JsonParseException {
return gson.fromJson(json, typeOfT);
}
}
}