javax.websocket.EndpointConfig Java Examples

The following examples show how to use javax.websocket.EndpointConfig. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: WebsocketBasicAuthTestCase.java    From quarkus-http with Apache License 2.0 7 votes vote down vote up
@Override
public void onOpen(Session session, EndpointConfig config) {
    this.session = session;
    try {
        Thread.sleep(100);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    session.addMessageHandler(new MessageHandler.Whole<String>() {

        @Override
        public void onMessage(String message) {
            responses.add(message);
        }
    });
}
 
Example #2
Source File: ProgramaticErrorEndpoint.java    From quarkus-http with Apache License 2.0 7 votes vote down vote up
@Override
public void onOpen(Session session, EndpointConfig config) {
    session.addMessageHandler(new MessageHandler.Whole<String>() {

        @Override
        public void onMessage(String message) {

            QUEUE.add(message);
            if (message.equals("app-error")) {
                throw new RuntimeException("an error");
            } else if (message.equals("io-error")) {
                throw new RuntimeException(new IOException());
            }
        }
    });
}
 
Example #3
Source File: SuspendResumeTestCase.java    From quarkus-http with Apache License 2.0 7 votes vote down vote up
@Test
public void testRejectWhenSuspended() throws Exception {
    try {
        serverContainer.pause(null);
        ContainerProvider.getWebSocketContainer().connectToServer(new Endpoint() {
            @Override
            public void onOpen(Session session, EndpointConfig config) {

            }
        }, new URI(DefaultServer.getDefaultServerURL() + "/"));
    } catch (IOException e) {
        //expected
    } finally {
        serverContainer.resume();
    }

}
 
Example #4
Source File: Notification.java    From uyuni with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Callback executed when the WebSocket is opened.
 * @param session the WebSocket session
 * @param config the EndPoint config
 */
@OnOpen
public void onOpen(Session session, EndpointConfig config) {
    if (session != null) {
        Optional.ofNullable(session.getUserProperties().get("webUserID"))
                .map(webUserID -> (Long) webUserID)
                .ifPresentOrElse(userId -> {
                    LOG.debug(String.format("Hooked a new websocket session [id:%s]", session.getId()));
                    handshakeSession(userId, session);

                    // update the notification counter to the unread messages
                    try {
                        sendMessage(session,
                                String.valueOf(UserNotificationFactory.unreadUserNotificationsSize(userId)));
                    }
                    finally {
                        HibernateFactory.closeSession();
                    }
                },
                ()-> LOG.debug("no authenticated user."));
    }
    else {
        LOG.debug("No web sessionId available. Closing the web socket.");
    }
}
 
Example #5
Source File: JsrWebSocketServerTest.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
@org.junit.Test
@Ignore("UT3 - P4")
public void testPingPong() throws Exception {
    final byte[] payload = "payload".getBytes();
    final AtomicReference<Throwable> cause = new AtomicReference<>();
    final AtomicBoolean connected = new AtomicBoolean(false);
    final CompletableFuture<?> latch = new CompletableFuture<>();

    class TestEndPoint extends Endpoint {
        @Override
        public void onOpen(final Session session, EndpointConfig config) {
            connected.set(true);
        }
    }
    ServerWebSocketContainer builder = new ServerWebSocketContainer(TestClassIntrospector.INSTANCE, DefaultServer.getEventLoopSupplier(), Collections.EMPTY_LIST, false, false);

    builder.addEndpoint(ServerEndpointConfig.Builder.create(TestEndPoint.class, "/").configurator(new InstanceConfigurator(new TestEndPoint())).build());
    deployServlet(builder);

    WebSocketTestClient client = new WebSocketTestClient(new URI("ws://" + DefaultServer.getHostAddress("default") + ":" + DefaultServer.getHostPort("default") + "/"));
    client.connect();
    client.send(new PingWebSocketFrame(Unpooled.wrappedBuffer(payload)), new FrameChecker(PongWebSocketFrame.class, payload, latch));
    latch.get(10, TimeUnit.SECONDS);
    Assert.assertNull(cause.get());
    client.destroy();
}
 
Example #6
Source File: OnlineNoticeServer.java    From belling-admin with Apache License 2.0 6 votes vote down vote up
/**
 * 连接建立成功调用的方法-与前端JS代码对应
 * 
 * @param session 可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据
 */
@OnOpen
public void onOpen(Session session, EndpointConfig config) {
	// 单个会话对象保存
	this.session = session;
	webSocketSet.add(this); // 加入set中
	this.httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
	String uId = (String) httpSession.getAttribute("userid"); // 获取当前用户
	String sessionId = httpSession.getId();
	this.userid = uId + "|" + sessionId;
	if (!OnlineUserlist.contains(this.userid)) {
		OnlineUserlist.add(userid); // 将用户名加入在线列表
	}
	routetabMap.put(userid, session); // 将用户名和session绑定到路由表
	System.out.println(userid + " -> 已上线");
	String message = getMessage(userid + " -> 已上线", "notice", OnlineUserlist);
	broadcast(message); // 广播
}
 
Example #7
Source File: LibertyClientEndpoint.java    From rogue-cloud with Apache License 2.0 6 votes vote down vote up
@Override
	public void onOpen(Session session, EndpointConfig ec) {
		
		// If the client instance is disposed, then immediately close all opened Sessions 
		if(LibertyClientInstance.getInstance().isDisposed()) {
			log.interesting("Ignoring onOpen on an endpoint with a closed LibertyClientInstance", clientState.getLogContext());
			try { session.close(); } catch (IOException e) {  /*ignore*/ }
			return;
		}
		
		log.interesting("Websocket session "+session.getId()+" opened with client instance "+LibertyClientInstance.getInstance().getUuid(),
				clientState.getLogContext());
		
		session.setMaxBinaryMessageBufferSize(128 * 1024);
		session.addMessageHandler(new BinaryMessageHandler(this, session, sessionWrapper));
		
//		session.addMessageHandler(new StringMessageHandler(this, session));
		
		sessionWrapper.newSession(session);
		
		ResourceLifecycleUtil.getInstance().addNewSession(ClientUtil.convertSessionToManagedResource(session));

		LibertyClientInstance.getInstance().add(session);
	}
 
Example #8
Source File: RestrictedGuacamoleWebSocketTunnelEndpoint.java    From guacamole-client with Apache License 2.0 6 votes vote down vote up
@Override
protected GuacamoleTunnel createTunnel(Session session,
        EndpointConfig config) throws GuacamoleException {

    Map<String, Object> userProperties = config.getUserProperties();

    // Get original tunnel request
    TunnelRequest tunnelRequest = (TunnelRequest) userProperties.get(TUNNEL_REQUEST_PROPERTY);
    if (tunnelRequest == null)
        return null;

    // Get tunnel request service
    TunnelRequestService tunnelRequestService = (TunnelRequestService) userProperties.get(TUNNEL_REQUEST_SERVICE_PROPERTY);
    if (tunnelRequestService == null)
        return null;

    // Create and return tunnel
    return tunnelRequestService.createTunnel(tunnelRequest);

}
 
Example #9
Source File: WebSocketJSR356Test.java    From camel-quarkus with Apache License 2.0 6 votes vote down vote up
@Test
public void testWebsocketChat() throws Exception {
    LinkedBlockingDeque<String> message = new LinkedBlockingDeque<>();
    Endpoint endpoint = new Endpoint() {
        @Override
        public void onOpen(Session session, EndpointConfig endpointConfig) {
            session.addMessageHandler(new MessageHandler.Whole<String>() {
                @Override
                public void onMessage(String s) {
                    message.add(s);
                }
            });
            session.getAsyncRemote().sendText("Camel Quarkus WebSocket");
        }
    };

    ClientEndpointConfig config = ClientEndpointConfig.Builder.create().build();
    try (Session session = ContainerProvider.getWebSocketContainer().connectToServer(endpoint, config, uri)) {
        Assertions.assertEquals("Hello Camel Quarkus WebSocket", message.poll(5, TimeUnit.SECONDS));
    }
}
 
Example #10
Source File: TestPojoEndpointBase.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@OnOpen
public void onOpen(@SuppressWarnings("unused") Session session,
        EndpointConfig config) {
    if (config == null) {
        throw new RuntimeException();
    }
}
 
Example #11
Source File: JsrWebSocketServerTest.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testTextAsync() throws Exception {
    final byte[] payload = "payload".getBytes();
    final AtomicReference<Throwable> cause = new AtomicReference<>();
    final AtomicBoolean connected = new AtomicBoolean(false);
    final CompletableFuture<?> latch = new CompletableFuture<>();
    class TestEndPoint extends Endpoint {
        @Override
        public void onOpen(final Session session, EndpointConfig config) {
            connected.set(true);
            session.addMessageHandler(new MessageHandler.Partial<String>() {

                StringBuilder sb = new StringBuilder();

                @Override
                public void onMessage(String message, boolean last) {
                    sb.append(message);
                    if (!last) {
                        return;
                    }
                    session.getAsyncRemote().sendText(sb.toString());
                }
            });
        }
    }
    ServerWebSocketContainer builder = new ServerWebSocketContainer(TestClassIntrospector.INSTANCE, DefaultServer.getEventLoopSupplier(), Collections.EMPTY_LIST, false, false);

    builder.addEndpoint(ServerEndpointConfig.Builder.create(TestEndPoint.class, "/").configurator(new InstanceConfigurator(new TestEndPoint())).build());
    deployServlet(builder);

    WebSocketTestClient client = new WebSocketTestClient(new URI("ws://" + DefaultServer.getHostAddress("default") + ":" + DefaultServer.getHostPort("default") + "/"));
    client.connect();
    client.send(new TextWebSocketFrame(Unpooled.wrappedBuffer(payload)), new FrameChecker(TextWebSocketFrame.class, payload, latch));
    latch.get();
    Assert.assertNull(cause.get());
    client.destroy();
}
 
Example #12
Source File: JsrWebSocketServerTest.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testBinaryWithByteArray() throws Exception {
    final byte[] payload = "payload".getBytes();
    final AtomicReference<Throwable> cause = new AtomicReference<>();
    final AtomicBoolean connected = new AtomicBoolean(false);
    final CompletableFuture<?> latch = new CompletableFuture<>();
    class TestEndPoint extends Endpoint {
        @Override
        public void onOpen(final Session session, EndpointConfig config) {
            connected.set(true);
            session.addMessageHandler(new MessageHandler.Whole<byte[]>() {
                @Override
                public void onMessage(byte[] message) {
                    session.getAsyncRemote().sendBinary(ByteBuffer.wrap(message.clone()));
                }
            });
        }
    }
    ServerWebSocketContainer builder = new ServerWebSocketContainer(TestClassIntrospector.INSTANCE, DefaultServer.getEventLoopSupplier(), Collections.EMPTY_LIST, false, false);
    builder.addEndpoint(ServerEndpointConfig.Builder.create(TestEndPoint.class, "/").configurator(new InstanceConfigurator(new TestEndPoint())).build());

    deployServlet(builder);

    WebSocketTestClient client = new WebSocketTestClient(new URI("ws://" + DefaultServer.getHostAddress("default") + ":" + DefaultServer.getHostPort("default") + "/"));
    client.connect();
    client.send(new BinaryWebSocketFrame(Unpooled.wrappedBuffer(payload)), new FrameChecker(BinaryWebSocketFrame.class, payload, latch));
    latch.get();
    Assert.assertNull(cause.get());
    client.destroy();
}
 
Example #13
Source File: TestPojoEndpointBase.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@OnOpen
public void onOpen(@SuppressWarnings("unused") Session session,
        EndpointConfig config) {
    if (config == null) {
        throw new RuntimeException();
    }
}
 
Example #14
Source File: MyProgrammaticEndpoint.java    From wildfly-samples with MIT License 5 votes vote down vote up
@Override
public void onOpen(final Session session, EndpointConfig ec) {
    session.addMessageHandler(new MessageHandler.Whole<String>() {

        @Override
        public void onMessage(String text) {
            try {
                session.getBasicRemote().sendText(text);
            } catch (IOException ex) {
                Logger.getLogger(MyProgrammaticEndpoint.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    });
}
 
Example #15
Source File: WebsocketTtyTestBase.java    From termd with Apache License 2.0 5 votes vote down vote up
@Override
protected void assertConnect(String term) throws Exception {
  if (endpoint != null) {
    throw failure("Already a session");
  }
  final CountDownLatch latch = new CountDownLatch(1);
  final PipedWriter out = new PipedWriter();
  in = new PipedReader(out);
  endpoint = new Endpoint() {
    @Override
    public void onOpen(Session session, EndpointConfig endpointConfig) {
      session.addMessageHandler(new MessageHandler.Whole<String>() {
        @Override
        public void onMessage(String message) {
          try {
            out.write(message);
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
      });
      latch.countDown();
    }
    @Override
    public void onClose(Session sess, CloseReason closeReason) {
      session = null;
      endpoint = null;
      in = null;
    }
    @Override
    public void onError(Session session, Throwable thr) {
    }
  };
  ClientEndpointConfig clientEndpointConfig = ClientEndpointConfig.Builder.create().build();
  WebSocketContainer webSocketContainer = ContainerProvider.getWebSocketContainer();
  session = webSocketContainer.connectToServer(endpoint, clientEndpointConfig, new URI("http://localhost:8080/ws"));
  latch.await();
}
 
Example #16
Source File: WebsocketTtyTestBase.java    From termd with Apache License 2.0 5 votes vote down vote up
@Override
protected void assertConnect(String term) throws Exception {
  if (endpoint != null) {
    throw failure("Already a session");
  }
  CountDownLatch latch = new CountDownLatch(1);
  PipedWriter out = new PipedWriter();
  in = new PipedReader(out);
  endpoint = new Endpoint() {
    @Override
    public void onOpen(Session session, EndpointConfig endpointConfig) {
      session.addMessageHandler(new MessageHandler.Whole<String>() {
        @Override
        public void onMessage(String message) {
          try {
            out.write(message);
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
      });
      latch.countDown();
    }
    @Override
    public void onClose(Session sess, CloseReason closeReason) {
      session = null;
      endpoint = null;
      in = null;
    }
    @Override
    public void onError(Session session, Throwable thr) {
    }
  };
  ClientEndpointConfig clientEndpointConfig = ClientEndpointConfig.Builder.create().build();
  WebSocketContainer webSocketContainer = ContainerProvider.getWebSocketContainer();
  session = webSocketContainer.connectToServer(endpoint, clientEndpointConfig, new URI("http://localhost:8080/ws"));
  latch.await();
}
 
Example #17
Source File: ConnectionRequestEndpoint.java    From jReto with MIT License 5 votes vote down vote up
/**
 * Called when a new RemotePeer opens a connection to the server
 * @param session WebSocket session of the RemotePeer
 * @param conf Contains all the information needed during the handshake process.
 * @param sourcePeer
 * @param targetPeer
 * @throws java.io.IOException
 */
@OnOpen
public void onOpen(Session session, EndpointConfig conf, @PathParam("sourcePeer") String sourcePeer, @PathParam("targetPeer") String targetPeer) throws IOException {
    LOGGER.log(Level.INFO, "onOpen called on data connection {0}", conf);
    this.requestingSession = session;
    ConnectionManager
            .getInstance()
            .requestConnection(
                    UUID.fromString(sourcePeer), 
                    UUID.fromString(targetPeer), 
                    this
            );
}
 
Example #18
Source File: Client.java    From aesh-readline with Apache License 2.0 5 votes vote down vote up
@Override
public void onOpen(Session session, EndpointConfig config) {
    LOGGER.log(Level.FINE, "Client received open.");
    this.session = session;

    session.addMessageHandler(new MessageHandler.Whole<String>() {
        @Override
        public void onMessage(String message) {
            LOGGER.log(Level.FINEST, "Client received text MESSAGE: {}", message);
            if (onStringMessageConsumer != null) {
                onStringMessageConsumer.accept(message);
            }
        }
    });
    session.addMessageHandler(new MessageHandler.Whole<byte[]>() {
        @Override
        public void onMessage(byte[] bytes) {
            LOGGER.log(Level.FINEST, "Client received binary MESSAGE: {}", new String(bytes));
            if (onBinaryMessageConsumer != null) {
                onBinaryMessageConsumer.accept(bytes);
            }
        }
    });
    if (onOpenConsumer != null) {
        onOpenConsumer.accept(session);
    }
}
 
Example #19
Source File: ProgramaticEndpoint.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Override
public void onOpen(final Session session, EndpointConfig config) {
    session.addMessageHandler(new MessageHandler.Whole<String>() {
        @Override
        public void onMessage(String message) {
            session.getAsyncRemote().sendText("Hello " + message);
        }
    });

}
 
Example #20
Source File: ProgramaticLazyEndpointTest.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Override
public void onOpen(Session session, EndpointConfig config) {
    this.session = session;
    session.getAsyncRemote().sendText("Stuart");
    session.addMessageHandler(new MessageHandler.Whole<String>() {

        @Override
        public void onMessage(String message) {
            responses.add(message);
        }
    });
}
 
Example #21
Source File: Util.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
private static List<Class<? extends Decoder>> matchDecoders(Class<?> target,
        EndpointConfig endpointConfig, boolean binary) {
    DecoderMatch decoderMatch = matchDecoders(target, endpointConfig);
    if (binary) {
        if (decoderMatch.getBinaryDecoders().size() > 0) {
            return decoderMatch.getBinaryDecoders();
        }
    } else if (decoderMatch.getTextDecoders().size() > 0) {
        return decoderMatch.getTextDecoders();
    }
    return null;
}
 
Example #22
Source File: PojoEndpointServer.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Override
public void onOpen(Session session, EndpointConfig endpointConfig) {

    ServerEndpointConfig sec = (ServerEndpointConfig) endpointConfig;

    Object pojo;
    try {
        pojo = sec.getConfigurator().getEndpointInstance(
                sec.getEndpointClass());
    } catch (InstantiationException e) {
        throw new IllegalArgumentException(sm.getString(
                "pojoEndpointServer.getPojoInstanceFail",
                sec.getEndpointClass().getName()), e);
    }
    setPojo(pojo);

    @SuppressWarnings("unchecked")
    Map<String,String> pathParameters =
            (Map<String, String>) sec.getUserProperties().get(
                    POJO_PATH_PARAM_KEY);
    setPathParameters(pathParameters);

    PojoMethodMapping methodMapping =
            (PojoMethodMapping) sec.getUserProperties().get(
                    POJO_METHOD_MAPPING_KEY);
    setMethodMapping(methodMapping);

    doOnOpen(session, endpointConfig);
}
 
Example #23
Source File: FHIRNotificationServiceEndpoint.java    From FHIR with Apache License 2.0 5 votes vote down vote up
/**
 * To process new end point client
 * 
 * @param session
 */
@Override
public void onOpen(Session session, EndpointConfig config) {
    log.entering(this.getClass().getName(), "onOpen");
    try {
        FHIRNotificationSubscriber subscriber = new FHIRNotificationSubscriberImpl(session);
        notificationService.subscribe(subscriber);
        subscribers.put(session, subscriber);
        log.info(String.format("Notification client [sessionId=%s] has registered.", session.getId()));
    } finally {
        log.exiting(this.getClass().getName(), "onOpen");
    }
}
 
Example #24
Source File: WSEndpoint.java    From diirt with MIT License 5 votes vote down vote up
@OnOpen
public void onOpen(Session session, EndpointConfig config) {
    // Read the maxRate parameter
    String maxRate = session.getPathParameters().get("maxRate");
    if (maxRate != null) {
        try {
            defaultMaxRate = Integer.parseInt(maxRate);
            if (defaultMaxRate < 20) {
                sendError(session, -1, "maxRate must be greater than 20");
                defaultMaxRate = 1000;
            }
        } catch (NumberFormatException ex) {
            sendError(session, -1, "maxRate must be an integer");
        }
    } else {
        defaultMaxRate = 1000;
    }

    // Retrive user and remote host for security purposes
    HttpSession httpSession = (HttpSession) config.getUserProperties().get("session");
    remoteAddress = (String) httpSession.getAttribute("remoteHost");
    if (session.getUserPrincipal() != null) {
        currentUser = session.getUserPrincipal().getName();
    } else {
        currentUser = null;
    }
}
 
Example #25
Source File: ConvertingEncoderDecoderSupport.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * @see javax.websocket.Encoder#init(EndpointConfig)
 * @see javax.websocket.Decoder#init(EndpointConfig)
 */
public void init(EndpointConfig config) {
	ApplicationContext applicationContext = getApplicationContext();
	if (applicationContext != null && applicationContext instanceof ConfigurableApplicationContext) {
		ConfigurableListableBeanFactory beanFactory =
				((ConfigurableApplicationContext) applicationContext).getBeanFactory();
		beanFactory.autowireBean(this);
	}
}
 
Example #26
Source File: Util.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
private static List<Class<? extends Decoder>> matchDecoders(Class<?> target,
        EndpointConfig endpointConfig, boolean binary) {
    DecoderMatch decoderMatch = matchDecoders(target, endpointConfig);
    if (binary) {
        if (decoderMatch.getBinaryDecoders().size() > 0) {
            return decoderMatch.getBinaryDecoders();
        }
    } else if (decoderMatch.getTextDecoders().size() > 0) {
        return decoderMatch.getTextDecoders();
    }
    return null;
}
 
Example #27
Source File: ConvertingEncoderDecoderSupport.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Called to initialize the encoder/decoder.
 * @see javax.websocket.Encoder#init(EndpointConfig)
 * @see javax.websocket.Decoder#init(EndpointConfig)
 */
public void init(EndpointConfig config) {
	ApplicationContext applicationContext = getApplicationContext();
	if (applicationContext != null && applicationContext instanceof ConfigurableApplicationContext) {
		ConfigurableListableBeanFactory beanFactory =
				((ConfigurableApplicationContext) applicationContext).getBeanFactory();
		beanFactory.autowireBean(this);
	}
}
 
Example #28
Source File: UndertowSession.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
public UndertowSession(Channel channel, URI requestUri, Map<String, String> pathParameters,
                       Map<String, List<String>> requestParameterMap, EndpointSessionHandler handler, Principal user,
                       InstanceHandle<Endpoint> endpoint, EndpointConfig config, final String queryString,
                       final Encoding encoding, final SessionContainer openSessions, final String subProtocol,
                       final List<Extension> extensions, WebsocketConnectionBuilder clientConnectionBuilder,
                       Executor executor) {
    channel.closeFuture().addListener(new GenericFutureListener<Future<? super Void>>() {
        @Override
        public void operationComplete(Future<? super Void> future) throws Exception {
            closeInternal(new CloseReason(CloseReason.CloseCodes.GOING_AWAY, null));
        }
    });
    this.clientConnectionBuilder = clientConnectionBuilder;
    assert openSessions != null;
    this.channel = channel;
    this.queryString = queryString;
    this.encoding = encoding;
    this.openSessions = openSessions;
    container = handler.getContainer();
    this.user = user;
    this.requestUri = requestUri;
    this.requestParameterMap = Collections.unmodifiableMap(requestParameterMap);
    this.pathParameters = Collections.unmodifiableMap(pathParameters);
    this.config = config;
    remote = new WebSocketSessionRemoteEndpoint(this, encoding);
    this.endpoint = endpoint;
    this.sessionId = new SecureRandomSessionIdGenerator().createSessionId();
    this.attrs = Collections.synchronizedMap(new HashMap<>(config.getUserProperties()));
    this.extensions = extensions;
    this.subProtocol = subProtocol;
    this.executor = executor;
    setupWebSocketChannel(channel);
}
 
Example #29
Source File: WebsocketClient.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
   public void onOpen(Session session, EndpointConfig endpointConfig) {
this.session = session;
if (messageHandler != null) {
    session.addMessageHandler(messageHandler);
}
   }
 
Example #30
Source File: PojoEndpointServer.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@Override
public void onOpen(Session session, EndpointConfig endpointConfig) {

    ServerEndpointConfig sec = (ServerEndpointConfig) endpointConfig;

    Object pojo;
    try {
        pojo = sec.getConfigurator().getEndpointInstance(
                sec.getEndpointClass());
    } catch (InstantiationException e) {
        throw new IllegalArgumentException(sm.getString(
                "pojoEndpointServer.getPojoInstanceFail",
                sec.getEndpointClass().getName()), e);
    }
    setPojo(pojo);

    @SuppressWarnings("unchecked")
    Map<String,String> pathParameters =
            (Map<String, String>) sec.getUserProperties().get(
                    POJO_PATH_PARAM_KEY);
    setPathParameters(pathParameters);

    PojoMethodMapping methodMapping =
            (PojoMethodMapping) sec.getUserProperties().get(
                    POJO_METHOD_MAPPING_KEY);
    setMethodMapping(methodMapping);

    doOnOpen(session, endpointConfig);
}