package com.github.wreulicke.spring;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Component;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

@Component
@Scope(proxyMode = ScopedProxyMode.TARGET_CLASS)
public class EchoHandler extends TextWebSocketHandler {

  private Map<String, WebSocketSession> sessions = new ConcurrentHashMap<>();

  @Override
  public void afterConnectionEstablished(WebSocketSession session) throws Exception {
    sessions.put(session.getId(), session);
  }

  @Override
  public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
    sessions.remove(session.getId());
    SocketSessionHolder.removeSession(session);
  }

  @Override
  protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
    SocketSessionHolder.setSession(session);
    try {
      WebApplicationContext context = ContextLoader.getCurrentWebApplicationContext();
      System.out.println(context.getBean(TestService.class)
        .serve());
      System.out.println(context.getBean(TestService.class)
        .serve());
      sessions.forEach((__, other) -> {
        try {
          other.sendMessage(new TextMessage("catch " + message.getPayload()));
        } catch (Exception e) {
          e.printStackTrace();
        }
      });
    } catch (Exception e2) {
      e2.printStackTrace();
    } finally {
      SocketSessionHolder.removeContext();
    }
  }
}

@@ -1314,16 +1314,49 @@
 ssion);%0A
+    System.out.println(%22start%22);%0A
     try 
@@ -1828,74 +1828,50 @@
   %7D 
-catch (Exception e2) %7B%0A      e2.printStackTrace();%0A    %7D finally %7B
+finally %7B%0A      System.out.println(%22end%22);
 %0A   

add log