Example usage for javax.websocket Session addMessageHandler

List of usage examples for javax.websocket Session addMessageHandler

Introduction

In this page you can find the example usage for javax.websocket Session addMessageHandler.

Prototype

void addMessageHandler(MessageHandler handler) throws IllegalStateException;

Source Link

Document

Registers a MessageHandler for incoming messages.

Usage

From source file:co.paralleluniverse.comsat.webactors.AbstractWebActorTest.java

private static Endpoint sendAndGetTextEndPoint(final String sendText, final SettableFuture<String> res) {
    return new Endpoint() {
        @Override//from  w w  w. j  ava  2  s .c  o  m
        public void onOpen(final Session session, EndpointConfig config) {
            session.addMessageHandler(new MessageHandler.Whole<String>() {
                @Override
                public void onMessage(String text) {
                    res.set(text);
                }
            });
            try {
                session.getBasicRemote().sendText(sendText);
            } catch (IOException ignored) {
            }
        }
    };
}

From source file:org.sample.client.MyClient.java

@Override
public void onOpen(final Session session, EndpointConfig ec) {
    session.addMessageHandler(new MessageHandler.Whole<String>() {

        @Override/* www  . j a  v a2 s.  co m*/
        public void onMessage(String text) {
            System.out.println("Received response in client from endpoint: " + text);
        }
    });
    System.out.println("Connected to endpoint: " + session.getBasicRemote());
    try {
        String name = "Duke";
        System.out.println("Sending message from client -> endpoint: " + name);
        session.getBasicRemote().sendText(name);
    } catch (IOException ex) {
        Logger.getLogger(MyClient.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.rotty3000.websocket.demo.WebsocketEndpoint.java

@Override
public void onOpen(Session session, EndpointConfig config) {
    Async remote = session.getAsyncRemote();

    session.addMessageHandler(new MessageHandler.Whole<String>() {

        public void onMessage(String text) {
            try {
                JSONObject jsonObject = new JSONObject(text);

                if (!jsonObject.has("file")) {
                    remote.sendText("[ERROR] No log file specified!");

                    return;
                }//from w w w . ja  v a 2  s  . c  o  m

                String fileName = jsonObject.getString("file");

                Path filePath = Paths.get(fileName);
                File file = filePath.toFile();

                if (!file.exists() || !file.canRead()) {
                    remote.sendText("[ERROR] The file [" + fileName + "] cannot be found!");

                    return;
                }

                int lines = 0;
                if (jsonObject.has("lines")) {
                    lines = jsonObject.getInt("lines");
                }

                remote.sendText(
                        "[CON] Here come the logs for [" + fileName + "] with [" + lines + "] of history.");

                logReader = new LogReader(remote, file, lines);

                logReader.start();
            } catch (Exception e) {
                remote.sendText("[ERROR] " + e.getMessage());
            }
        }

    });
}

From source file:org.chtijbug.drools.platform.backend.wsclient.WebSocketClient.java

@Override
public void onOpen(final Session session, EndpointConfig endpointConfig) {
    this.session = session;

    session.addMessageHandler(new MessageHandler.Whole<PlatformManagementKnowledgeBean>() {
        @Override/*  w  ww  .j  a  v  a2  s.c om*/
        public void onMessage(PlatformManagementKnowledgeBean bean) {

            switch (bean.getRequestRuntimePlarform()) {
            case jmxInfos:
                RealTimeParameters realTimeParameters = new RealTimeParameters();
                PlatformRuntimeInstance targetplatformRuntimeInstance = platformRuntimeInstanceRepository
                        .findByRuleBaseID(platformRuntimeInstance.getRuleBaseID());
                realTimeParameters.setPlatformRuntimeInstance(targetplatformRuntimeInstance);
                JMXInfo jmxInfo = bean.getJmxInfo();
                realTimeParameters.setAverageTimeExecution(jmxInfo.getAverageTimeExecution());
                realTimeParameters.setMinTimeExecution(jmxInfo.getMinTimeExecution());
                realTimeParameters.setMaxTimeExecution(jmxInfo.getMaxTimeExecution());
                realTimeParameters.setTotalTimeExecution(jmxInfo.getTotalTimeExecution());
                realTimeParameters.setTotalNumberRulesExecuted(jmxInfo.getTotalNumberRulesExecuted());
                realTimeParameters.setAverageRulesExecuted(jmxInfo.getAverageRulesExecuted());
                realTimeParameters.setMinRulesExecuted(jmxInfo.getMinRulesExecuted());
                realTimeParameters.setMaxRulesExecuted(jmxInfo.getMaxRulesExecuted());
                realTimeParameters.setNumberFireAllRulesExecuted(jmxInfo.getNumberFireAllRulesExecuted());
                realTimeParameters.setAverageRuleThroughout(jmxInfo.getAverageRuleThroughout());
                realTimeParameters.setMinRuleThroughout(jmxInfo.getMinRuleThroughout());
                realTimeParameters.setMaxRuleThroughout(jmxInfo.getMaxRuleThroughout());
                realTimeParametersRepository.save(realTimeParameters);
                jmxInfosListeners.messageReceived(platformRuntimeInstance.getRuleBaseID(), realTimeParameters);
                break;
            case versionInfos:
                versionInfosListener.messageReceived(platformRuntimeInstance.getRuleBaseID(),
                        bean.getResourceFileList());
                break;
            case isAlive:
                isAliveListener.messageReceived(platformRuntimeInstance.getRuleBaseID());

                heartBeatListner.messageReceived(platformRuntimeInstance.getRuleBaseID(),
                        bean.getHeartbeat().getLastAlive());
                heartbeat.setLastAlive(bean.getHeartbeat().getLastAlive());
                break;

            case loadNewRuleVersion:
                PlatformRuntimeDefinition platformRuntimeDefinitionloadNewRuleVersion = platformRuntimeDefinitionRepository
                        .findByRuleBaseID(platformRuntimeInstance.getRuleBaseID());
                platformRuntimeDefinitionloadNewRuleVersion
                        .setCouldInstanceStartWithNewRuleVersion(bean.getRequestStatus().toString());
                platformRuntimeDefinitionRepository.save(platformRuntimeDefinitionloadNewRuleVersion);
                loadNewRuleVersionListener.messageReceived(platformRuntimeInstance.getRuleBaseID(),
                        bean.getRequestStatus(), bean.getResourceFileList());
                break;
            }
        }
    });

}

From source file:com.github.mrstampy.gameboot.otp.websocket.WebSocketEndpoint.java

@Override
public void onOpen(Session session, EndpointConfig config) {
    log.debug("Session {} open on channel", session.getId());

    session.addMessageHandler(new MessageHandler.Whole<byte[]>() {

        @Override//w  w  w  . j a  va 2 s  .  co m
        public void onMessage(byte[] message) {
            try {
                WebSocketEndpoint.this.onMessage(message, session);
            } catch (Exception e) {
                log.error("Unexpected exception", e);
            }
        }
    });
}

From source file:edu.rit.chrisbitler.ritcraft.slackintegration.rtm.RTMClient.java

/**
 * Method for when the websocket opens. We set up the message listener here too
 * @param session The websocket session that just opened for this method
 * @param endpointConfig The endpoint configuration - not used
 */// www.  ja  v  a2s .  c  om
@Override
public void onOpen(Session session, EndpointConfig endpointConfig) {
    RTMClient.this.session = session;
    System.out.println("Websocket connection open");

    //Register the message handler - This has to be a MessageHandler.Partial. If it is a MessageHandler.Whole it won't work.
    session.addMessageHandler(new MessageHandler.Partial<String>() {
        @Override
        public void onMessage(String s, boolean b) {
            JSONObject obj = (JSONObject) JSONValue.parse(s);
            if (obj.get("type") != null) {
                String type = String.valueOf(obj.get("type"));

                //Give the message off to the handler based on the event type
                switch (type) {
                case "hello":
                    HelloMessage.handle();
                    break;
                case "message":
                    MsgMessage.handle(obj);
                    break;
                }
            } else {
                System.out.println("[Slack] Recieved malformed JSON message from slack - no type");
            }
        }
    });
}

From source file:io.kodokojo.bdd.stage.AccessRestWhen.java

private void connectToWebSocket(UserInfo requesterUserInfo, boolean expectSuccess) {

    try {/*w w w  .j a  v  a  2s .  c om*/

        final ClientEndpointConfig cec = ClientEndpointConfig.Builder.create().build();

        ClientManager client = ClientManager.createClient();
        if (requesterUserInfo != null) {
            client.getProperties().put(ClientProperties.CREDENTIALS,
                    new Credentials(requesterUserInfo.getUsername(), requesterUserInfo.getPassword()));

        }

        String uriStr = "ws://" + restEntryPointHost + ":" + restEntryPointPort + "/api/v1/event";
        CountDownLatch messageLatch = new CountDownLatch(1);
        Session session = client.connectToServer(new Endpoint() {
            @Override
            public void onOpen(Session session, EndpointConfig config) {

                session.addMessageHandler(new MessageHandler.Whole<String>() {
                    @Override
                    public void onMessage(String messsage) {
                        GsonBuilder builder = new GsonBuilder();
                        builder.registerTypeAdapter(WebSocketMessage.class, new WebSocketMessageGsonAdapter());
                        Gson gson = builder.create();
                        WebSocketMessage response = gson.fromJson(messsage, WebSocketMessage.class);
                        LOGGER.info("Receive WebSocket mesage : {}", response);
                        if ("user".equals(response.getEntity()) && "authentication".equals(response.getAction())
                                && response.getData().has("message") && ((JsonObject) response.getData())
                                        .getAsJsonPrimitive("message").getAsString().equals("success")) {
                            receiveWebSocketWelcome = true;
                            messageLatch.countDown();
                        } else {
                            receiveWebSocketWelcome = false;
                        }
                    }

                });
                if (requesterUserInfo != null) {
                    try {
                        String aggregateCredentials = String.format("%s:%s", requesterUserInfo.getUsername(),
                                requesterUserInfo.getPassword());
                        String encodedCredentials = Base64.getEncoder()
                                .encodeToString(aggregateCredentials.getBytes());
                        session.getBasicRemote()
                                .sendText("{\n" + "  \"entity\": \"user\",\n"
                                        + "  \"action\": \"authentication\",\n" + "  \"data\": {\n"
                                        + "    \"authorization\": \"Basic " + encodedCredentials + "\"\n"
                                        + "  }\n" + "}");
                    } catch (IOException e) {
                        fail(e.getMessage());
                    }
                }
            }

        }, cec, new URI(uriStr));
        messageLatch.await(10, TimeUnit.SECONDS);
        session.close();
    } catch (Exception e) {
        if (expectSuccess) {
            fail(e.getMessage());
        } else {
            receiveWebSocketWelcome = false;
        }
    }
}

From source file:org.brutusin.rpc.websocket.WebsocketEndpoint.java

/**
 *
 * @param session/*from   w ww . j a  va  2 s.c  o m*/
 * @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);
                }
            } finally {
                WebsocketActionSupportImpl.clear();
            }
        }
    });
}

From source file:org.ocelotds.integration.AbstractOcelotTest.java

/**
 * Test reception of 0 msg triggered by call Runnable
 *
 * @param wssession//from   ww  w  .  j a v  a 2 s  .c o  m
 * @param topic
 * @param trigger
 */
protected void testWait0MessageToTopic(Session wssession, String topic, Runnable trigger) {
    try {
        long t0 = System.currentTimeMillis();
        CountDownLatch lock = new CountDownLatch(1);
        CountDownMessageHandler messageHandler = new CountDownMessageHandler(topic, lock);
        wssession.addMessageHandler(messageHandler);
        trigger.run();
        boolean await = lock.await(TIMEOUT, TimeUnit.MILLISECONDS);
        long t1 = System.currentTimeMillis();
        assertThat(await).as("Timeout. waiting %d ms. Remain %d/%d msgs", t1 - t0, lock.getCount(), 1)
                .isFalse();
        wssession.removeMessageHandler(messageHandler);
    } catch (IllegalStateException | InterruptedException ex) {
        fail(ex.getMessage());
    }
}

From source file:org.ocelotds.integration.AbstractOcelotTest.java

/**
 * Test reception of X msg triggered by call Runnable
 *
 * @param wssession/*w w w. ja  va2 s  .c o m*/
 * @param nbMsg
 * @param topic
 * @param trigger
 */
protected void testWaitXMessageToTopic(Session wssession, int nbMsg, String topic, Runnable trigger) {
    try {
        long t0 = System.currentTimeMillis();
        CountDownLatch lock = new CountDownLatch(nbMsg);
        CountDownMessageHandler messageHandler = new CountDownMessageHandler(topic, lock);
        wssession.addMessageHandler(messageHandler);
        trigger.run();
        boolean await = lock.await(TIMEOUT * nbMsg, TimeUnit.MILLISECONDS);
        long t1 = System.currentTimeMillis();
        assertThat(await).as("Timeout. waiting %d ms. Remain %d/%d msgs", t1 - t0, lock.getCount(), nbMsg)
                .isTrue();
        wssession.removeMessageHandler(messageHandler);
    } catch (IllegalStateException | InterruptedException ex) {
        fail(ex.getMessage());
    }
}