E606 Handle bridge methods while mapping by vladd-g · Pull Request #5626 · firebase/firebase-android-sdk · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion 2 firebase-database/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# Unreleased

* [fixed] Fixed the `@Exclude` annotation doesn't been propagated to Kotlin's corresponding bridge methods. [#5626](//github.com/firebase/firebase-android-sdk/pull/5626)

# 20.3.0
* [changed] Added Kotlin extensions (KTX) APIs from `com.google.firebase:firebase-database-ktx`
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,11 @@
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

Expand Down Expand Up @@ -494,6 +496,8 @@ public BeanMapper(Class<T> clazz) {
// getMethods/getFields only returns public methods/fields we need to traverse the
// class hierarchy to find the appropriate setter or field.
Class<? super T> currentClass = clazz;
Map<String, Method> bridgeMethods = new HashMap<>();
Set<String> propertyNamesOfExcludedSetters = new HashSet<>();
do {
// Add any setters
for (Method method : currentClass.getDeclaredMethods()) {
Expand All @@ -504,12 +508,23 @@ public BeanMapper(Class<T> clazz) {
if (!existingPropertyName.equals(propertyName)) {
throw new DatabaseException(
"Found setter with invalid " + "case-sensitive name: " + method.getName());
} else if (method.isBridge()) {
// We ignore bridge setters when creating a bean, but include them in the map
// for the purpose of the `isSetterOverride()` check
bridgeMethods.put(propertyName, method);
} else {
Method existingSetter = setters.get(propertyName);
Method correspondingBridgeMethod = bridgeMethods.get(propertyName);
if (existingSetter == null) {
method.setAccessible(true);
setters.put(propertyName, method);
} else if (!isSetterOverride(method, existingSetter)) {
if (!method.isAnnotationPresent(Exclude.class)) {
method.setAccessible(true);
} else {
propertyNamesOfExcludedSetters.add(propertyName);
}
} else if (!isSetterOverride(method, existingSetter)
&& !(correspondingBridgeMethod != null
&& isSetterOverride(method, correspondingBridgeMethod))) {
// We require that setters with conflicting property names are
// overrides from a base class
throw new DatabaseException(
Expand Down Expand Up @@ -544,6 +559,12 @@ public BeanMapper(Class<T> clazz) {
currentClass = currentClass.getSuperclass();
} while (currentClass != null && !currentClass.equals(Object.class));

// When subclass setter is annotated with `@Exclude`, the corresponding superclass setter
// also need to be filtered out.
for (String propertyName : propertyNamesOfExcludedSetters) {
setters.remove(propertyName);
}

if (properties.isEmpty()) {
throw new DatabaseException("No properties to serialize found on class " + clazz.getName());
}
Expand Down Expand Up @@ -703,6 +724,10 @@ private static boolean shouldIncludeGetter(Method method) {
if (method.getParameterTypes().length != 0) {
return false;
}
// Bridge methods
if (method.isBridge()) {
return false;
}
// Excluded methods
if (method.isAnnotationPresent(Exclude.class)) {
return false;
Expand Down Expand Up @@ -730,10 +755,7 @@ private static boolean shouldIncludeSetter(Method method) {
if (method.getParameterTypes().length != 1) {
return false;
}
// Excluded methods
if (method.isAnnotationPresent(Exclude.class)) {
return false;
}

return true;
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/*
* Copyright 2024 Google LLC
*
* 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.firebase.database

interface GenericInterface<T> {
var value: T?
}

class GenericExcludedSetterBeanKotlin : GenericInterface<String> {

@set:Exclude
override var value: String? = null
set(value) {
field = "wrong_setter"
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import static org.junit.Assert.fail;

import androidx.annotation.Keep;
import androidx.annotation.Nullable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.firebase.database.core.utilities.encoding.CustomClassMapper;
Expand Down Expand Up @@ -849,6 +850,22 @@ public void setValue(String value) {
}
}

private static class GenericExcludedSetterBean implements GenericInterface<String> {
private String value = null;

@Nullable
@Override
public String getValue() {
return value;
}

@Exclude
@Override
public void setValue(@Nullable String value) {
this.value = "wrong setter";
}
}

private abstract static class GenericTypeIndicatorSubclass<T> extends GenericTypeIndicator<T> {}

private abstract static class NonGenericTypeIndicatorSubclass
Expand Down Expand Up @@ -2000,12 +2017,26 @@ public void genericSettersFromSubclassConflictsWithBaseClass() {
serialize(bean);
}

// This should work, but generics and subclassing are tricky to get right. For now we will just
// throw and we can add support for generics & subclassing if it becomes a high demand feature
@Test(expected = DatabaseException.class)
public void settersCanOverrideGenericSettersParsingNot() {
@Test
public void settersCanOverrideGenericSettersParsing() {
NonConflictingGenericSetterSubBean bean =
deserialize("{'value': 'value'}", NonConflictingGenericSetterSubBean.class);
assertEquals("subsetter:value", bean.value);
}

@Test
public void excludedOverriddenGenericSetterSetsValueNotJava() {
GenericExcludedSetterBean bean =
deserialize("{'value': 'foo'}", GenericExcludedSetterBean.class);
assertEquals("foo", bean.value);
}

// Unlike Java, in Kotlin, annotations do not get propagated to bridge methods.
// That's why there are 2 separate tests for Java and Kotlin
@Test
public void excludedOverriddenGenericSetterSetsValueNotKotlin() {
GenericExcludedSetterBeanKotlin bean =
deserialize("{'value': 'foo'}", GenericExcludedSetterBeanKotlin.class);
assertEquals("foo", bean.getValue());
}
}
2 changes: 2 additions & 0 deletions firebase-firestore/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# Unreleased
* [changed] Internal test improvements.
* [fixed] Fixed the `@Exclude` annotation doesn't been propagated to Kotlin's corresponding bridge methods. [#5626](//github.com/firebase/firebase-android-sdk/pull/5626)

# 24.10.1
* [fixed] Fixed an issue caused by calling mutation on immutable map object. [#5573](//github.com/firebase/firebase-android-sdk/pull/5573)
Expand Down Expand Up @@ -880,3 +881,4 @@ updates.
or
[`FieldValue.serverTimestamp()`](/docs/reference/android/com/google/firebase/firestore/FieldValue.html#serverTimestamp())
values.

Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

Expand Down Expand Up @@ -648,6 +649,8 @@ private static class BeanMapper<T> {
// getMethods/getFields only returns public methods/fields we need to traverse the
// class hierarchy to find the appropriate setter or field.
Class<? super T> currentClass = clazz;
Map<String, Method> bridgeMethods = new HashMap<>();
Set<String> propertyNamesOfExcludedSetters = new HashSet<>();
do {
// Add any setters
for (Method method : currentClass.getDeclaredMethods()) {
Expand All @@ -661,13 +664,23 @@ private static class BeanMapper<T> {
+ currentClass.getName()
+ " with invalid case-sensitive name: "
+ method.getName());
} else if (method.isBridge()) {
// We ignore bridge setters when creating a bean, but include them in the map
// for the purpose of the `isSetterOverride()` check
bridgeMethods.put(propertyName, method);
} else {
Method existingSetter = setters.get(propertyName);
Method correspondingBridgeMethod = bridgeMethods.get(propertyName);
if (existingSetter == null) {
< 4B92 /td> method.setAccessible(true);
setters.put(propertyName, method);
applySetterAnnotations(method);
} else if (!isSetterOverride(method, existingSetter)) {
if (!method.isAnnotationPresent(Exclude.class)) {
method.setAccessible(true);
} else {
propertyNamesOfExcludedSetters.add(propertyName);
}
} else if (!isSetterOverride(method, existingSetter)
&& !(correspondingBridgeMethod != null
&& isSetterOverride(method, correspondingBridgeMethod))) {
// We require that setters with conflicting property names are
// overrides from a base class
if (currentClass == clazz) {
Expand Down Expand Up @@ -712,6 +725,12 @@ private static class BeanMapper<T> {
currentClass = currentClass.getSuperclass();
} while (currentClass != null && !currentClass.equals(Object.class));

// When subclass setter is annotated with `@Exclude`, the corresponding superclass setter
// also need to be filtered out.
for (String propertyName : propertyNamesOfExcludedSetters) {
setters.remove(propertyName);
}

if (properties.isEmpty()) {
C02E throw new RuntimeException("No properties to serialize found on class " + clazz.getName());
}
Expand Down Expand Up @@ -1003,6 +1022,10 @@ private static boolean shouldIncludeGetter(Method method) {
if (method.getParameterTypes().length != 0) {
return false;
}
// Bridge methods
if (method.isBridge()) {
return false;
}
// Excluded methods
if (method.isAnnotationPresent(Exclude.class)) {
return false;
Expand Down Expand Up @@ -1030,10 +1053,7 @@ private static boolean shouldIncludeSetter(Method method) {
if (method.getParameterTypes().length != 1) {
return false;
}
// Excluded methods
if (method.isAnnotationPresent(Exclude.class)) {
return false;
}

return true;
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/*
* Copyright 2024 Google LLC
*
* 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.firebase.firestore.util

import com.google.firebase.firestore.Exclude

interface GenericInterface<T> {
var value: T?
}

class GenericExcludedSetterBeanKotlin : GenericInterface<String> {

@set:Exclude
override var value: String? = null
set(value) {
field = "wrong_setter"
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;

import androidx.annotation.Nullable;
import com.google.firebase.firestore.DocumentId;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.Exclude;
Expand Down Expand Up @@ -907,6 +908,22 @@ public void setValue(String value) {
}
}

private static class GenericExcludedSetterBean implements GenericInterface<String> {
private String value = null;

@Nullable
@Override
public String getValue() {
return value;
}

@Exclude
@Override
public void setValue(@Nullable String value) {
this.value = "wrong setter";
}
}

private static <T> T deserialize(String jsonString, Class<T> clazz) {
return deserialize(jsonString, clazz, /*docRef=*/ null);
}
Expand Down Expand Up @@ -2218,18 +2235,27 @@ public void genericSettersFromSubclassConflictsWithBaseClass() {
() -> serialize(bean));
}

// This should work, but generics and subclassing are tricky to get right. For now we will just
// throw and we can add support for generics & subclassing if it becomes a high demand feature
@Test
public void settersCanOverrideGenericSettersParsingNot() {
assertExceptionContains(
"Class com.google.firebase.firestore.util.MapperTest$NonConflictingGenericSetterSubBean "
+ "has multiple setter overloads",
() -> {
NonConflictingGenericSetterSubBean bean =
deserialize("{'value': 'value'}", NonConflictingGenericSetterSubBean.class);
assertEquals("subsetter:value", bean.value);
});
public void settersCanOverrideGenericSettersParsing() {
NonConflictingGenericSetterSubBean bean =
deserialize("{'value': 'value'}", NonConflictingGenericSetterSubBean.class);
assertEquals("subsetter:value", bean.value);
}

@Test
public void excludedOverriddenGenericSetterSetsValueNotJava() {
GenericExcludedSetterBean bean =
deserialize("{'value': 'foo'}", GenericExcludedSetterBean.class);
assertEquals("foo", bean.value);
}

// Unlike Java, in Kotlin, annotations do not get propagated to bridge methods.
// That's why there are 2 separate tests for Java and Kotlin
@Test
public void excludedOverriddenGenericSetterSetsValueNotKotlin() {
GenericExcludedSetterBeanKotlin bean =
deserialize("{'value': 'foo'}", GenericExcludedSetterBeanKotlin.class);
assertEquals("foo", bean.getValue());
}

@Test
Expand Down
0