Как использовать Tapestry IoC-Services в событиях Websocket-Endpoints, таких как @OnOpen - PullRequest
0 голосов
/ 23 октября 2019

Короче говоря, я хочу знать, как я могу получить сообщение «У нас есть немного магии!», Когда я открываю соединение со следующей конечной точкой веб-сокета. Очевидно, мне все еще не хватает понимания.

Первое: соединение успешно установлено.

У меня есть ServerEndpointConfig, подобный этому:

...

import org.apache.tapestry5.TapestryFilter;
import org.apache.tapestry5.ioc.Registry;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;

public class MyEndpointConfig extends ServerEndpointConfig.Configurator {

    private MyService1 myService1;

    @Override
    public void modifyHandshake(ServerEndpointConfig config, HandshakeRequest request, HandshakeResponse response) {
        HttpSession httpSession = (HttpSession) request.getHttpSession();
        ServletContext servletContext = httpSession.getServletContext();
        Registry registry = (Registry)servletContext.getAttribute( TapestryFilter.REGISTRY_CONTEXT_NAME );
        myService1 = registry.getService(MyService1.class);
        config.getUserProperties().put("myService1", myService1);
    }

}

И естьотличная конечная точка:

...
import org.apache.tapestry5.ioc.annotations.Inject;
import javax.websocket.OnOpen;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint(value="/myendpoint/", configurator=MyEndpointConfig.class)
public class MyEndpoint {

    private MyService1 myService1;

    @Inject
    private MyService1 myService1_injected;

    @OnOpen
    public void onOpen( Session session, EndpointConfig config )  throws URISyntaxException {
        Map<String, Object> userProperties = config.getUserProperties();
        myService1 = (MyService1) userProperties.get("myService1");

        Object someMagic = null;
        if(myService1 != null) {
            if(!"<Proxy for myService1(my.package.MyService1)>".equals(myService1.toString())) {
                someMagic = myService1.getSomeMagic();
            } else {
                System.out.println("Thats the problem!");
            }
        } else {
            if(myService1_injected != null) {
                someMagic = myService1_injected.getSomeMagic();
            } else {
                System.out.println("Thats the problem!");
            }
        }

        if(someMagic != null) System.out.println("We have some magic!");
    }
...