javax.websocket.MessageHandler Java Examples

The following examples show how to use javax.websocket.MessageHandler. 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: WsFrameBase.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
protected void sendMessageBinary(ByteBuffer msg, boolean last) throws WsIOException {
    if (binaryMsgHandler instanceof WrappedMessageHandler) {
        long maxMessageSize = ((WrappedMessageHandler) binaryMsgHandler).getMaxMessageSize();
        if (maxMessageSize > -1 && msg.remaining() > maxMessageSize) {
            throw new WsIOException(new CloseReason(CloseCodes.TOO_BIG,
                    sm.getString("wsFrame.messageTooBig",
                            Long.valueOf(msg.remaining()),
                            Long.valueOf(maxMessageSize))));
        }
    }
    try {
        if (binaryMsgHandler instanceof MessageHandler.Partial<?>) {
            ((MessageHandler.Partial<ByteBuffer>) binaryMsgHandler).onMessage(msg, last);
        } else {
            // Caller ensures last == true if this branch is used
            ((MessageHandler.Whole<ByteBuffer>) binaryMsgHandler).onMessage(msg);
        }
    } catch (Throwable t) {
        handleThrowableOnSend(t);
    }
}
 
Example #4
Source File: AdminEndpoind.java    From opencps-v2 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * @Override onOpen websocket connect
 * 
 * @param Session
 * @param EndpointConfig
 */
@Override
public void onOpen(Session session, EndpointConfig config) {

	session.setMaxBinaryMessageBufferSize(8388608);
	session.setMaxTextMessageBufferSize(8388608);
	
	MessageHandler handler = new MessageHandler.Whole<String>() {

		@Override
		public void onMessage(String text) {
			try {
				onMessageHandler(text, session);
			} catch (Exception e) {
				_log.error(e);
			}
		}

	};

	session.addMessageHandler(handler);

}
 
Example #5
Source File: PojoEndpointBase.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
@Override
public final void onClose(Session session, CloseReason closeReason) {

    if (methodMapping.getOnClose() != null) {
        try {
            methodMapping.getOnClose().invoke(pojo,
                    methodMapping.getOnCloseArgs(pathParameters, session, closeReason));
        } catch (Throwable t) {
            ExceptionUtils.handleThrowable(t);
            log.error(sm.getString("pojoEndpointBase.onCloseFail",
                    pojo.getClass().getName()), t);
        }
    }

    // Trigger the destroy method for any associated decoders
    Set<MessageHandler> messageHandlers = session.getMessageHandlers();
    for (MessageHandler messageHandler : messageHandlers) {
        if (messageHandler instanceof PojoMessageHandlerWholeBase<?>) {
            ((PojoMessageHandlerWholeBase<?>) messageHandler).onClose();
        }
    }
}
 
Example #6
Source File: PojoEndpointBase.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Override
public final void onClose(Session session, CloseReason closeReason) {

    if (methodMapping.getOnClose() != null) {
        try {
            methodMapping.getOnClose().invoke(pojo,
                    methodMapping.getOnCloseArgs(pathParameters, session, closeReason));
        } catch (Throwable t) {
            log.error(sm.getString("pojoEndpointBase.onCloseFail",
                    pojo.getClass().getName()), t);
            handleOnOpenOrCloseError(session, t);
        }
    }

    // Trigger the destroy method for any associated decoders
    Set<MessageHandler> messageHandlers = session.getMessageHandlers();
    for (MessageHandler messageHandler : messageHandlers) {
        if (messageHandler instanceof PojoMessageHandlerWholeBase<?>) {
            ((PojoMessageHandlerWholeBase<?>) messageHandler).onClose();
        }
    }
}
 
Example #7
Source File: WebSocketServiceImpl.java    From chrome-devtools-java-client with Apache License 2.0 6 votes vote down vote up
@Override
public void addMessageHandler(Consumer<String> consumer) throws WebSocketServiceException {
  if (session == null) {
    throw new WebSocketServiceException(
        "You first must connect to ws server in order to receive messages.");
  }

  if (!session.getMessageHandlers().isEmpty()) {
    throw new WebSocketServiceException("You are already subscribed to this web socket service.");
  }

  session.addMessageHandler(
      new MessageHandler.Whole<String>() {
        @Override
        public void onMessage(String message) {
          LOGGER.debug("Received message {} on {}", message, session.getRequestURI());
          consumer.accept(message);
        }
      });
}
 
Example #8
Source File: PojoEndpointBase.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
@Override
public final void onClose(Session session, CloseReason closeReason) {

    if (methodMapping.getOnClose() != null) {
        try {
            methodMapping.getOnClose().invoke(pojo,
                    methodMapping.getOnCloseArgs(pathParameters, session, closeReason));
        } catch (Throwable t) {
            ExceptionUtils.handleThrowable(t);
            log.error(sm.getString("pojoEndpointBase.onCloseFail",
                    pojo.getClass().getName()), t);
        }
    }

    // Trigger the destroy method for any associated decoders
    Set<MessageHandler> messageHandlers = session.getMessageHandlers();
    for (MessageHandler messageHandler : messageHandlers) {
        if (messageHandler instanceof PojoMessageHandlerWholeBase<?>) {
            ((PojoMessageHandlerWholeBase<?>) messageHandler).onClose();
        }
    }
}
 
Example #9
Source File: FrameHandler.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
private void onPongMessage(final PongWebSocketFrame frame) {
    if (session.isSessionClosed()) {
        //to bad, the channel has already been closed
        //we just ignore messages that are received after we have closed, as the endpoint is no longer in a valid state to deal with them
        //this this should only happen if a message was on the wire when we called close()
        return;
    }
    final HandlerWrapper handler = getHandler(FrameType.PONG);
    if (handler != null) {
        final PongMessage message = DefaultPongMessage.create(Unpooled.copiedBuffer(frame.content()).nioBuffer());

        session.getContainer().invokeEndpointMethod(executor, new Runnable() {
            @Override
            public void run() {
                try {
                    ((MessageHandler.Whole) handler.getHandler()).onMessage(message);
                } catch (Exception e) {
                    invokeOnError(e);
                }
            }
        });
    }
}
 
Example #10
Source File: FrameHandler.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
public final void addHandler(MessageHandler handler) {
    Map<Class<?>, Boolean> types = ClassUtils.getHandlerTypes(handler.getClass());
    for (Entry<Class<?>, Boolean> e : types.entrySet()) {
        Class<?> type = e.getKey();
        boolean partial = e.getValue();
        addHandlerInternal(handler, type, partial);
    }
}
 
Example #11
Source File: FrameHandler.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
private void addHandlerInternal(MessageHandler handler, Class<?> type, boolean partial) {
    verify(type, handler);

    List<HandlerWrapper> handlerWrappers = createHandlerWrappers(type, handler, partial);
    for (HandlerWrapper handlerWrapper : handlerWrappers) {
        if (handlers.containsKey(handlerWrapper.getFrameType())) {
            throw JsrWebSocketMessages.MESSAGES.handlerAlreadyRegistered(handlerWrapper.getFrameType());
        } else {
            if (handlers.putIfAbsent(handlerWrapper.getFrameType(), handlerWrapper) != null) {
                throw JsrWebSocketMessages.MESSAGES.handlerAlreadyRegistered(handlerWrapper.getFrameType());
            }
        }
    }
}
 
Example #12
Source File: WsFrameBase.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
private boolean usePartial() {
    if (Util.isControl(opCode)) {
        return false;
    } else if (textMessage) {
        return textMsgHandler instanceof MessageHandler.Partial<?>;
    } else {
        // Must be binary
        return binaryMsgHandler instanceof MessageHandler.Partial<?>;
    }
}
 
Example #13
Source File: WsSession.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Override
public Set<MessageHandler> getMessageHandlers() {
    checkState();
    Set<MessageHandler> result = new HashSet<MessageHandler>();
    if (binaryMessageHandler != null) {
        result.add(binaryMessageHandler);
    }
    if (textMessageHandler != null) {
        result.add(textMessageHandler);
    }
    if (pongMessageHandler != null) {
        result.add(pongMessageHandler);
    }
    return result;
}
 
Example #14
Source File: WebsocketReceiver.java    From AngularBeans with GNU Lesser General Public License v3.0 5 votes vote down vote up
public WebsocketReceiver(Session ws) {
	protocol = "websocket";
	this.ws = ws;
	this.ws.addMessageHandler(new MessageHandler.Whole<String>() {

		@Override
		public void onMessage(String message) {
			didMessage(message);
		}
	});
}
 
Example #15
Source File: FrameHandler.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
public final void removeHandler(MessageHandler handler) {
    Map<Class<?>, Boolean> types = ClassUtils.getHandlerTypes(handler.getClass());
    for (Entry<Class<?>, Boolean> e : types.entrySet()) {
        Class<?> type = e.getKey();
        List<HandlerWrapper> handlerWrappers = createHandlerWrappers(type, handler, e.getValue());
        for (HandlerWrapper handlerWrapper : handlerWrappers) {
            FrameType frameType = handlerWrapper.getFrameType();
            HandlerWrapper wrapper = handlers.get(frameType);
            if (wrapper != null && wrapper.getMessageType() == type) {
                handlers.remove(frameType, wrapper);
            }
        }
    }
}
 
Example #16
Source File: FrameHandler.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
/**
 * Return a safe copy of all registered {@link MessageHandler}s.
 */
public final Set<MessageHandler> getHandlers() {
    Set<MessageHandler> msgHandlers = new HashSet<>();
    for (HandlerWrapper handler : handlers.values()) {
        msgHandlers.add(handler.getHandler());
    }
    return msgHandlers;
}
 
Example #17
Source File: StandardWebSocketHandlerAdapterTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void onOpen() throws Throwable {
	given(this.session.getId()).willReturn("123");
	this.adapter.onOpen(this.session, null);

	verify(this.webSocketHandler).afterConnectionEstablished(this.webSocketSession);
	verify(this.session, atLeast(2)).addMessageHandler(any(MessageHandler.Whole.class));

	given(this.session.getId()).willReturn("123");
	assertEquals("123", this.webSocketSession.getId());
}
 
Example #18
Source File: FrameHandler.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
private HandlerWrapper(final FrameType frameType, MessageHandler handler, final Class<?> msgType, final boolean decodingNeeded, final boolean partialHandler) {
    this.frameType = frameType;
    this.handler = handler;

    this.msgType = msgType;
    this.decodingNeeded = decodingNeeded;
    this.partialHandler = partialHandler;
}
 
Example #19
Source File: WebsocketTtyTestBase.java    From aesh-readline 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 #20
Source File: Client.java    From termd with Apache License 2.0 5 votes vote down vote up
@Override
public void onOpen(Session session, EndpointConfig config) {
  log.debug("Client received open.");
  this.session = session;

  session.addMessageHandler(new MessageHandler.Whole<String>() {
    @Override
    public void onMessage(String message) {
      log.trace("Client received text MESSAGE: {}", message);
      if (onStringMessageConsumer != null) {
        onStringMessageConsumer.accept(message);
      }
    }
  });
  session.addMessageHandler(new MessageHandler.Whole<byte[]>() {
    @Override
    public void onMessage(byte[] bytes) {
      log.trace("Client received binary MESSAGE: {}", new String(bytes));
      if (onBinaryMessageConsumer != null) {
        onBinaryMessageConsumer.accept(bytes);
      }
    }
  });
  if (onOpenConsumer != null) {
    onOpenConsumer.accept(session);
  }
}
 
Example #21
Source File: ClassUtils.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a map of all supported message types by the given handler class.
 * The key of the map is the supported message type; the value indicates
 * whether it is a partial message handler or not.
 *
 * @return a map of all supported message types by the given handler class.
 */
public static Map<Class<?>, Boolean> getHandlerTypes(Class<? extends MessageHandler> clazz) {
    Map<Class<?>, Boolean> types = new IdentityHashMap<>(2);
    for (Class<?> c = clazz; c != Object.class; c = c.getSuperclass()) {
        exampleGenericInterfaces(types, c, clazz);
    }
    if (types.isEmpty()) {
        throw JsrWebSocketMessages.MESSAGES.unknownHandlerType(clazz);
    }
    return types;
}
 
Example #22
Source File: BinaryEndpointTest.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;
    // Copy, because masking will modify this data
    byte[] mutableBytes = new byte[bytes.length];
    System.arraycopy(bytes,0,mutableBytes,0,bytes.length);
    session.getAsyncRemote().sendBinary(ByteBuffer.wrap(mutableBytes));
    session.addMessageHandler(new MessageHandler.Whole<byte[]>() {

        @Override
        public void onMessage(byte[] message) {
            responses.add(message);
        }
    });
}
 
Example #23
Source File: EchoProgramaticEndpoint.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Override
public void onOpen(final Session session, EndpointConfig config) {
    final String foo = session.getPathParameters().get("foo");
    session.addMessageHandler(String.class, new MessageHandler.Whole<String>() {
        @Override
        public void onMessage(String message) {
            session.getAsyncRemote().sendText(foo + " " + message);
        }
    });
}
 
Example #24
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 #25
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 #26
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 #27
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 #28
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 #29
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 #30
Source File: WebsocketEndpoint.java    From Brutusin-RPC with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param session
 * @param config
 */
@Override
public void onOpen(Session session, EndpointConfig config) {
    final WebsocketContext websocketContext = contextMap.get(session.getRequestParameterMap().get("requestId").get(0));
    if (!allowAccess(session, websocketContext)) {
        try {
            session.close(new CloseReason(CloseReason.CloseCodes.CANNOT_ACCEPT, "Authentication required"));
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
        return;
    }
    final SessionImpl sessionImpl = new SessionImpl(session, websocketContext);
    sessionImpl.init();
    wrapperMap.put(session.getId(), sessionImpl);

    session.addMessageHandler(new MessageHandler.Whole<String>() {
        public void onMessage(String message) {
            WebsocketActionSupportImpl.setInstance(new WebsocketActionSupportImpl(sessionImpl));
            try {
                String response = process(message, sessionImpl);
                if (response != null) {
                    sessionImpl.sendToPeerRaw(response);
                }
            } catch (Throwable th) {
                LOGGER.log(Level.SEVERE, "Error processing request: " + message, th);
            } finally {
                WebsocketActionSupportImpl.clear();
            }
        }
    });
}