Created
February 28, 2024 18:28
-
-
Save arleighdickerson/203a099152270daa70fbefd460f1c3bc to your computer and use it in GitHub Desktop.
A WebSocketSessionDecorator to listen for attribute changes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.aopalliance.intercept.MethodInterceptor; | |
import org.aopalliance.intercept.MethodInvocation; | |
import org.springframework.aop.framework.ProxyFactory; | |
import org.springframework.lang.NonNull; | |
import org.springframework.lang.Nullable; | |
import org.springframework.web.socket.WebSocketSession; | |
import org.springframework.web.socket.handler.WebSocketSessionDecorator; | |
import java.util.Map; | |
import java.util.Objects; | |
public class AttributeChangeEmitter extends WebSocketSessionDecorator implements MethodInterceptor { | |
@FunctionalInterface | |
public interface ChangeListener { | |
void onChange(String key, Object value); | |
} | |
@SuppressWarnings("unchecked") | |
private final Map<String, Object> attributes = ProxyFactory.getProxy(Map.class, this); | |
private final ChangeListener changeListener; | |
public AttributeChangeEmitter(WebSocketSession session, ChangeListener changeListener) { | |
super(session); | |
this.changeListener = Objects.requireNonNull(changeListener); | |
} | |
@Override | |
public Map<String, Object> getAttributes() { | |
return attributes; | |
} | |
@Nullable | |
@Override | |
public Object invoke(@NonNull MethodInvocation invocation) throws Throwable { | |
String name = invocation.getMethod().getName(); | |
if (name.equals("put") && invocation.getArguments().length == 2) { | |
String key = (String) invocation.getArguments()[0]; | |
Object value = invocation.getArguments()[1]; | |
Object previous = super.getAttributes().get(key); | |
if (!Objects.equals(previous, value)) { | |
changeListener.onChange(key, value); | |
} | |
} | |
return invocation.getMethod().invoke(super.getAttributes(), invocation.getArguments()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment