Hi Team,
Using UiEventPublisher to send event from Spring service to UI for logged in user is OK. But if the view is for anonymous, it’s not working. Please suggest if there is any solution to do the same for anonymous?
The scenario is, some page was embedded in other application with anonymous access, and when some new data comes, Spring service need to send the data to UI.
Jmix version: v2
Hi,
UiEventPublisher addresses recipients by username: it looks up Vaadin sessions by the
security context stored in the HTTP session. Spring Security never stores an anonymous
context there, so anonymous sessions are simply skipped. That part is not going to work.
What does work is publishEventForCurrentUI(), which publishes through the current
VaadinSession and does not care about authentication. So keep a registry of the UIs
yourself and push into each of them:
@Component
public class AnonymousUiRegistry {
private final Set<UI> uis = ConcurrentHashMap.newKeySet();
private final UiEventPublisher uiEventPublisher;
public AnonymousUiRegistry(UiEventPublisher uiEventPublisher) {
this.uiEventPublisher = uiEventPublisher;
}
public Registration register(UI ui) {
uis.add(ui);
return () -> uis.remove(ui);
}
public void broadcast(ApplicationEvent event) {
for (UI ui : uis) {
try {
ui.access(() -> uiEventPublisher.publishEventForCurrentUI(event));
} catch (UIDetachedException e) {
uis.remove(ui);
}
}
}
}
In the view, register on attach and unregister on detach:
@Autowired
private AnonymousUiRegistry uiRegistry;
private Registration registration;
@Override
protected void onAttach(AttachEvent attachEvent) {
super.onAttach(attachEvent);
registration = uiRegistry.register(attachEvent.getUI());
}
@Override
protected void onDetach(DetachEvent detachEvent) {
if (registration != null) {
registration.remove();
}
super.onDetach(detachEvent);
}
The @EventListener methods in the view keep working as usual, because they are registered
on attach regardless of authentication. Your service just calls
uiRegistry.broadcast(new MyDataEvent(this, ...)).
One thing to watch out for: anonymous visitors have no identity, so this reaches all
anonymous tabs. If the data is meant for one visitor, store your own key next to the UI
and filter on it before pushing.