Skip to content

Commit 68a1ead

Browse files
authored
fix: unwrap router target class in getRouteTarget (#19151)
AbstractNavigationStateRenderer.getRouteTarget filters the active router targets chain comparing collection items class with the route target type. The filter may fail if routes instances are proxy objects created by frameworks like spring, since the class will not match the required one. This cahnge ensures that synthetic and proxy classes are discarded, allowing for more accurate comparison when filtering objects based on their real application class. Fixes #19100
1 parent b3ddbdc commit 68a1ead

11 files changed

Lines changed: 293 additions & 4 deletions

File tree

‎flow-server/src/main/java/com/vaadin/flow/di/Instantiator.java‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
package com.vaadin.flow.di;
1717

1818
import java.io.Serializable;
19+
import java.util.Objects;
1920
import java.util.ServiceLoader;
2021
import java.util.stream.Stream;
2122

@@ -116,6 +117,38 @@ default Stream<DependencyFilter> getDependencyFilters(
116117
*/
117118
<T> T getOrCreate(Class<T> type);
118119

120+
/**
121+
* Return the application-defined class for the given instance: usually
122+
* simply the class of the given instance, but the original class in case of
123+
* a runtime generated subclass.
124+
*
125+
* @param instance
126+
* the instance to check
127+
* @return the user-defined class
128+
*/
129+
default Class<?> getApplicationClass(Object instance) {
130+
Objects.requireNonNull(instance, "Instance cannot be null");
131+
return getApplicationClass(instance.getClass());
132+
}
133+
134+
/**
135+
* Return the application-defined class for the given class: usually simply
136+
* the given class, but the original class in case of a runtime generated
137+
* subclass.
138+
*
139+
* @param clazz
140+
* the class to check
141+
* @return the user-defined class
142+
*/
143+
default Class<?> getApplicationClass(Class<?> clazz) {
144+
Class<?> appClass = clazz;
145+
while (appClass != null && appClass != Object.class
146+
&& appClass.isSynthetic()) {
147+
appClass = appClass.getSuperclass();
148+
}
149+
return appClass;
150+
}
151+
119152
/**
120153
* Creates an instance of a navigation target or router layout. This method
121154
* is not called in cases when a component instance is reused when

‎flow-server/src/main/java/com/vaadin/flow/router/internal/AbstractNavigationStateRenderer.java‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -123,13 +123,14 @@ public NavigationState getNavigationState() {
123123
static <T extends HasElement> T getRouteTarget(Class<T> routeTargetType,
124124
NavigationEvent event) {
125125
UI ui = event.getUI();
126+
Instantiator instantiator = Instantiator.get(ui);
126127
Optional<HasElement> currentInstance = ui.getInternals()
127128
.getActiveRouterTargetsChain().stream()
128-
.filter(component -> component.getClass()
129+
.filter(component -> instantiator.getApplicationClass(component)
129130
.equals(routeTargetType))
130131
.findAny();
131-
return (T) currentInstance.orElseGet(() -> Instantiator.get(ui)
132-
.createRouteTarget(routeTargetType, event));
132+
return (T) currentInstance.orElseGet(
133+
() -> instantiator.createRouteTarget(routeTargetType, event));
133134
}
134135

135136
@Override

‎flow-server/src/test/java/com/vaadin/flow/di/DefaultInstantiatorTest.java‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,10 @@
1818
import java.util.ArrayList;
1919
import java.util.List;
2020

21+
import net.bytebuddy.ByteBuddy;
22+
import net.bytebuddy.description.modifier.SyntheticState;
23+
import net.bytebuddy.description.modifier.Visibility;
24+
import net.bytebuddy.dynamic.loading.ClassLoadingStrategy;
2125
import org.junit.Assert;
2226
import org.junit.Test;
2327
import org.mockito.Mockito;
@@ -75,6 +79,43 @@ public void getOrCreate_lookupHasNoObject_createNewObject() {
7579
Assert.assertNotNull(component);
7680
}
7781

82+
@Test
83+
public void getApplicationClass_regularClass_getsSameClass() {
84+
VaadinService service = Mockito.mock(VaadinService.class);
85+
mockLookup(service);
86+
87+
DefaultInstantiator instantiator = new DefaultInstantiator(service);
88+
89+
TestComponent instance = instantiator.getOrCreate(TestComponent.class);
90+
Assert.assertSame(TestComponent.class,
91+
instantiator.getApplicationClass(instance));
92+
Assert.assertSame(TestComponent.class,
93+
instantiator.getApplicationClass(instance.getClass()));
94+
}
95+
96+
@Test
97+
public void getApplicationClass_syntheticClass_getsApplicationClass()
98+
throws Exception {
99+
VaadinService service = Mockito.mock(VaadinService.class);
100+
mockLookup(service);
101+
DefaultInstantiator instantiator = new DefaultInstantiator(service);
102+
103+
Class<? extends TestComponent> syntheticClass = new ByteBuddy()
104+
.subclass(TestComponent.class)
105+
.modifiers(Visibility.PUBLIC, SyntheticState.SYNTHETIC).make()
106+
.load(getClass().getClassLoader(),
107+
ClassLoadingStrategy.Default.WRAPPER)
108+
.getLoaded();
109+
TestComponent instance = syntheticClass.getDeclaredConstructor()
110+
.newInstance();
111+
112+
Assert.assertNotSame(TestComponent.class, instance.getClass());
113+
Assert.assertSame(TestComponent.class,
114+
instantiator.getApplicationClass(instance));
115+
Assert.assertSame(TestComponent.class,
116+
instantiator.getApplicationClass(instance.getClass()));
117+
}
118+
78119
private Lookup mockLookup(VaadinService service) {
79120
VaadinContext context = Mockito.mock(VaadinContext.class);
80121
Mockito.when(service.getContext()).thenReturn(context);

‎flow-server/src/test/java/com/vaadin/flow/router/internal/NavigationStateRendererTest.java‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,10 @@
2525
import java.util.concurrent.atomic.AtomicInteger;
2626
import java.util.stream.Collectors;
2727

28+
import net.bytebuddy.ByteBuddy;
29+
import net.bytebuddy.description.modifier.SyntheticState;
30+
import net.bytebuddy.description.modifier.Visibility;
31+
import net.bytebuddy.dynamic.loading.ClassLoadingStrategy;
2832
import net.jcip.annotations.NotThreadSafe;
2933
import org.junit.Assert;
3034
import org.junit.Before;
@@ -43,6 +47,7 @@
4347
import com.vaadin.flow.component.page.Page;
4448
import com.vaadin.flow.component.page.PendingJavaScriptResult;
4549
import com.vaadin.flow.dom.Element;
50+
import com.vaadin.flow.internal.ReflectTools;
4651
import com.vaadin.flow.router.AfterNavigationEvent;
4752
import com.vaadin.flow.router.AfterNavigationObserver;
4853
import com.vaadin.flow.router.BeforeEnterEvent;
@@ -131,6 +136,13 @@ private static class PreservedNestedView extends Text {
131136
}
132137
}
133138

139+
@Route(value = "proxyable")
140+
public static class ProxyableView extends Text {
141+
public ProxyableView() {
142+
super("");
143+
}
144+
}
145+
134146
private Router router;
135147

136148
@Rule
@@ -217,6 +229,51 @@ public <T extends HasElement> T createRouteTarget(
217229
UI.setCurrent(null);
218230
}
219231

232+
@Test
233+
public void getRouteTarget_supportsProxyClasses() {
234+
try {
235+
Class<? extends ProxyableView> routeProxyClass = new ByteBuddy()
236+
.subclass(ProxyableView.class)
237+
.modifiers(Visibility.PUBLIC, SyntheticState.SYNTHETIC)
238+
.make().load(ProxyableView.class.getClassLoader(),
239+
ClassLoadingStrategy.Default.WRAPPER)
240+
.getLoaded();
241+
242+
AtomicInteger routeCreationCounter = new AtomicInteger(0);
243+
MockVaadinServletService service = new MockVaadinServletService();
244+
service.init(new MockInstantiator() {
245+
@Override
246+
public <T extends HasElement> T createRouteTarget(
247+
Class<T> routeTargetType, NavigationEvent event) {
248+
Assert.assertEquals(ProxyableView.class, routeTargetType);
249+
routeCreationCounter.incrementAndGet();
250+
return (T) ReflectTools.createInstance(routeProxyClass);
251+
}
252+
});
253+
MockUI ui = new MockUI(new AlwaysLockedVaadinSession(service));
254+
255+
NavigationEvent event = new NavigationEvent(
256+
new Router(new TestRouteRegistry()), new Location("child"),
257+
ui, NavigationTrigger.UI_NAVIGATE);
258+
NavigationStateRenderer renderer = new NavigationStateRenderer(
259+
navigationStateFromTarget(ProxyableView.class));
260+
renderer.handle(event);
261+
HasElement view = ui.getInternals().getActiveRouterTargetsChain()
262+
.get(0);
263+
264+
Component routeTarget = renderer.getRouteTarget(ProxyableView.class,
265+
event);
266+
267+
// Getting route target should not create a new instance
268+
Assert.assertEquals(
269+
"Only one view instance should have been created", 1,
270+
routeCreationCounter.get());
271+
Assert.assertSame(view, routeTarget);
272+
} finally {
273+
UI.setCurrent(null);
274+
}
275+
}
276+
220277
@Route("parent")
221278
private static class RouteParentLayout extends Component
222279
implements RouterLayout {

‎flow-tests/vaadin-spring-tests/test-spring-boot/pom.xml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,7 @@
135135
<artifactId>vaadin-test-spring-common</artifactId>
136136
<version>${project.version}</version>
137137
<type>test-jar</type>
138+
<classifier>tests</classifier>
138139
<outputDirectory>${project.build.directory}/test-classes</outputDirectory>
139140
</artifactItem>
140141
</artifactItems>

‎flow-tests/vaadin-spring-tests/test-spring-boot/src/main/java/com/vaadin/flow/spring/test/TestServletInitializer.java‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,11 +19,13 @@
1919
import org.springframework.boot.autoconfigure.SpringBootApplication;
2020
import org.springframework.context.annotation.Configuration;
2121
import org.springframework.context.annotation.Import;
22+
import org.springframework.scheduling.annotation.EnableAsync;
2223
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
2324

2425
@SpringBootApplication
2526
@Configuration
2627
@EnableWebSecurity
28+
@EnableAsync(proxyTargetClass = true)
2729
@Import(DummyOAuth2Server.class)
2830
public class TestServletInitializer {
2931

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
/*
2+
* Copyright 2000-2024 Vaadin Ltd.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
5+
* use this file except in compliance with the License. You may obtain a copy of
6+
* the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12+
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13+
* License for the specific language governing permissions and limitations under
14+
* the License.
15+
*/
16+
package com.vaadin.flow.spring.test;
17+
18+
import java.util.UUID;
19+
import java.util.concurrent.atomic.AtomicInteger;
20+
21+
import org.springframework.context.annotation.Scope;
22+
import org.springframework.context.annotation.ScopedProxyMode;
23+
import org.springframework.scheduling.annotation.Async;
24+
import org.springframework.stereotype.Component;
25+
26+
import com.vaadin.flow.component.html.Div;
27+
import com.vaadin.flow.router.BeforeEvent;
28+
import com.vaadin.flow.router.HasUrlParameter;
29+
import com.vaadin.flow.router.OptionalParameter;
30+
import com.vaadin.flow.router.Route;
31+
import com.vaadin.flow.router.RouterLink;
32+
33+
import static com.vaadin.flow.spring.scopes.VaadinUIScope.VAADIN_UI_SCOPE_NAME;
34+
35+
@Route("proxied")
36+
public class ProxiedNavigationTarget extends Div
37+
implements HasUrlParameter<Integer> {
38+
39+
private final String uuid = UUID.randomUUID().toString();
40+
private final AtomicInteger counter = new AtomicInteger();
41+
private final RouterLink routerLink;
42+
private final Div clickCounter;
43+
44+
public ProxiedNavigationTarget() {
45+
Div uuid = new Div(this.uuid);
46+
uuid.setId("COMPONENT_ID");
47+
add(uuid);
48+
49+
clickCounter = new Div("P:0, C:0");
50+
clickCounter.setId("CLICK_COUNTER");
51+
add(clickCounter);
52+
53+
// Self navigation should use the same view instance
54+
routerLink = new RouterLink("Self Link", ProxiedNavigationTarget.class,
55+
counter.incrementAndGet());
56+
add(routerLink);
57+
}
58+
59+
// @Async annotation should cause Spring to create a proxy for the
60+
// bean instance
61+
@Async
62+
public void asyncMethod() {
63+
64+
}
65+
66+
@Override
67+
public void setParameter(BeforeEvent event,
68+
@OptionalParameter Integer parameter) {
69+
if (parameter != null) {
70+
clickCounter.setText("P:" + parameter + ", C:" + counter.get());
71+
routerLink.setRoute(ProxiedNavigationTarget.class,
72+
counter.incrementAndGet());
73+
}
74+
}
75+
}

‎flow-tests/vaadin-spring-tests/test-spring-common/src/test/java/com/vaadin/flow/spring/test/RouteBasicIT.java‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,12 @@
1616

1717
package com.vaadin.flow.spring.test;
1818

19+
import java.util.concurrent.atomic.AtomicReference;
20+
1921
import org.junit.Assert;
2022
import org.junit.Test;
2123
import org.openqa.selenium.By;
24+
import org.slf4j.LoggerFactory;
2225

2326
public class RouteBasicIT extends AbstractSpringTest {
2427

@@ -37,4 +40,36 @@ public void testServletDeployed() throws Exception {
3740

3841
waitUntil(driver -> isElementPresent(By.id("singleton-in-ui")));
3942
}
43+
44+
@Test
45+
public void uiScopedProxiedTargetView_shouldUseSameViewInstance()
46+
throws Exception {
47+
getDriver().get(getTestURL() + "proxied");
48+
waitForDevServer();
49+
50+
String prevUuid = null;
51+
AtomicReference<String> prevCounter = new AtomicReference<>("");
52+
for (int i = 0; i < 5; i++) {
53+
String uuid = waitUntil(d -> d.findElement(By.id("COMPONENT_ID")))
54+
.getText();
55+
56+
waitUntil(d -> !prevCounter.get()
57+
.equals(d.findElement(By.id("CLICK_COUNTER")).getText()));
58+
59+
if (prevUuid != null) {
60+
Assert.assertEquals("UUID should not have been changed",
61+
prevUuid, uuid);
62+
}
63+
String counter = findElement(By.id("CLICK_COUNTER")).getText();
64+
Assert.assertEquals(
65+
"Parameter and counter should have the same value",
66+
"P:" + i + ", C:" + i, counter);
67+
68+
prevUuid = uuid;
69+
prevCounter.set(counter);
70+
71+
$("a").first().click();
72+
}
73+
74+
}
4075
}

‎flow-tests/vaadin-spring-tests/test-spring/pom.xml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,7 @@
9393
<artifactId>vaadin-test-spring-common</artifactId>
9494
<version>${project.version}</version>
9595
<type>test-jar</type>
96+
<classifier>tests</classifier>
9697
<outputDirectory>${project.build.directory}/test-classes</outputDirectory>
9798
</artifactItem>
9899
</artifactItems>

‎vaadin-spring/src/main/java/com/vaadin/flow/spring/SpringInstantiator.java‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
import org.springframework.boot.SpringBootVersion;
2525
import org.springframework.context.ApplicationContext;
2626
import org.springframework.core.SpringVersion;
27+
import org.springframework.util.ClassUtils;
2728

2829
import com.vaadin.flow.component.Component;
2930
import com.vaadin.flow.di.DefaultInstantiator;
@@ -135,4 +136,9 @@ public <T> T getOrCreate(Class<T> type) {
135136
return context.getAutowireCapableBeanFactory().createBean(type);
136137
}
137138
}
139+
140+
@Override
141+
public Class<?> getApplicationClass(Class<?> clazz) {
142+
return ClassUtils.getUserClass(clazz);
143+
}
138144
}

0 commit comments

Comments
 (0)