Search in sources :

Example 41 with CloseReason

use of javax.websocket.CloseReason in project meecrowave by apache.

the class ChatWS method message.

@OnMessage
public void message(Session session, JsonObject msg) {
    try {
        if (!"ping".equals(msg.getString("chat"))) {
            session.close(new CloseReason(CloseCodes.UNEXPECTED_CONDITION, String.format("unexpected chat value %s", msg.getString("chat"))));
        }
        JsonObject pong = Json.createObjectBuilder().add("chat", "pong " + chatCounter.incrementAndGet()).build();
        session.getBasicRemote().sendObject(pong);
    } catch (IOException | EncodeException e) {
        e.printStackTrace();
    }
}
Also used : CloseReason(javax.websocket.CloseReason) JsonObject(javax.json.JsonObject) EncodeException(javax.websocket.EncodeException) IOException(java.io.IOException) OnMessage(javax.websocket.OnMessage)

Example 42 with CloseReason

use of javax.websocket.CloseReason in project muikku by otavanopisto.

the class CoOpsDocumentWebSocket method onOpen.

@OnOpen
public void onOpen(final Session client, EndpointConfig endpointConfig, @PathParam("HTMLMATERIALID") String htmlMaterialId, @PathParam("SESSIONID") String sessionId) throws IOException {
    synchronized (this) {
        // 
        // TODO: RequestScope is not available on the websockets, switch to ticket system
        // 
        // if (!sessionController.isLoggedIn()) {
        // client.close(new CloseReason(CloseReason.CloseCodes.NORMAL_CLOSURE, "Permission denied"));
        // }
        // 
        // UserEntity userEntity = sessionController.getLoggedUserEntity();
        // 
        // EnvironmentUser environmentUser = environmentUserController.findEnvironmentUserByUserEntity(userEntity);
        // 
        // if (environmentUser.getRole() == null || environmentUser.getRole().getArchetype() == EnvironmentRoleArchetype.STUDENT) {
        // client.close(new CloseReason(CloseReason.CloseCodes.NORMAL_CLOSURE, "Permission denied"));
        // }
        CoOpsSession session = coOpsSessionController.findSessionBySessionId(sessionId);
        if (session == null) {
            client.close(new CloseReason(CloseReason.CloseCodes.NORMAL_CLOSURE, "Not Found"));
            return;
        }
        if (!session.getHtmlMaterial().getId().equals(NumberUtils.createLong(htmlMaterialId))) {
            client.close(new CloseReason(CloseReason.CloseCodes.VIOLATED_POLICY, "Session is associated with another fileId"));
            return;
        }
        Map<String, Session> sessions = fileClients.get(htmlMaterialId);
        if (sessions == null) {
            fileClients.put(htmlMaterialId, new HashMap<String, Session>());
        }
        fileClients.get(htmlMaterialId).put(client.getId(), client);
        coOpsSessionController.updateSessionType(session, CoOpsSessionType.WS);
        HtmlMaterial htmlMaterial = session.getHtmlMaterial();
        Long currentRevisionNumber = htmlMaterial.getRevisionNumber();
        if (session.getJoinRevision() < currentRevisionNumber) {
            ObjectMapper objectMapper = new ObjectMapper();
            List<Patch> patches;
            try {
                patches = coOpsApi.fileUpdate(session.getHtmlMaterial().getId().toString(), session.getSessionId(), session.getJoinRevision());
                for (Patch patch : patches) {
                    sendPatch(client, patch);
                }
            } catch (CoOpsInternalErrorException e) {
                client.close(new CloseReason(CloseReason.CloseCodes.UNEXPECTED_CONDITION, "Internal Error"));
            } catch (CoOpsUsageException e) {
                client.getAsyncRemote().sendText(objectMapper.writeValueAsString(new ErrorMessage("patchError", 400, e.getMessage())));
            } catch (CoOpsNotFoundException e) {
                client.getAsyncRemote().sendText(objectMapper.writeValueAsString(new ErrorMessage("patchError", 404, e.getMessage())));
            } catch (CoOpsForbiddenException e) {
                client.getAsyncRemote().sendText(objectMapper.writeValueAsString(new ErrorMessage("patchError", 500, e.getMessage())));
            }
        }
    }
}
Also used : CoOpsUsageException(fi.foyt.coops.CoOpsUsageException) CoOpsSession(fi.otavanopisto.muikku.plugins.material.coops.model.CoOpsSession) CoOpsForbiddenException(fi.foyt.coops.CoOpsForbiddenException) CloseReason(javax.websocket.CloseReason) CoOpsInternalErrorException(fi.foyt.coops.CoOpsInternalErrorException) CoOpsNotFoundException(fi.foyt.coops.CoOpsNotFoundException) HtmlMaterial(fi.otavanopisto.muikku.plugins.material.model.HtmlMaterial) ErrorMessage(fi.foyt.coops.extensions.websocket.ErrorMessage) Patch(fi.foyt.coops.model.Patch) ObjectMapper(org.codehaus.jackson.map.ObjectMapper) CoOpsSession(fi.otavanopisto.muikku.plugins.material.coops.model.CoOpsSession) Session(javax.websocket.Session) OnOpen(javax.websocket.OnOpen)

Example 43 with CloseReason

use of javax.websocket.CloseReason in project nimbus by nimbus-org.

the class DefaultEndpointService method closeClientSessionFromIp.

@Override
public void closeClientSessionFromIp(String ip) {
    if (ip != null) {
        synchronized (sessionSet) {
            Iterator it = sessionSet.iterator();
            while (it.hasNext()) {
                Session session = (Session) it.next();
                SessionProperties prop = SessionProperties.getSessionProperty(session);
                if (ip.equals(prop.getIp())) {
                    CloseReason reason = new CustomCloseReason(CustomCloseReason.CloseCodes.SYSTEM_FORCED_DISCONNECTION, "Forced disconnection");
                    try {
                        session.close(reason);
                    } catch (Exception e) {
                    }
                }
            }
        }
    }
}
Also used : CloseReason(javax.websocket.CloseReason) Iterator(java.util.Iterator) IOException(java.io.IOException) Session(javax.websocket.Session)

Example 44 with CloseReason

use of javax.websocket.CloseReason in project component-runtime by Talend.

the class WebsocketClient method read.

public <T> T read(final Class<T> response, final String method, final String uri, final String body, final String type) {
    final WebSocketContainer container = ContainerProvider.getWebSocketContainer();
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<String> indexHolder = new AtomicReference<>();
    final ClientEndpointConfig clientEndpointConfig = ClientEndpointConfig.Builder.create().build();
    clientEndpointConfig.getUserProperties().put("org.apache.tomcat.websocket.IO_TIMEOUT_MS", "60000");
    final Session session;
    try {
        session = container.connectToServer(new Endpoint() {

            @Override
            public void onOpen(final Session session, final EndpointConfig endpointConfig) {
                final StringBuilder builder = new StringBuilder();
                session.addMessageHandler(ByteBuffer.class, new MessageHandler.Partial<ByteBuffer>() {

                    @Override
                    public synchronized void onMessage(final ByteBuffer part, final boolean last) {
                        try {
                            builder.append(new String(part.array()));
                        } finally {
                            if (builder.toString().endsWith("^@")) {
                                indexHolder.set(builder.toString());
                                doClose(session);
                            }
                        }
                    }
                });
            }

            @Override
            public void onClose(final Session session, final CloseReason closeReason) {
                latch.countDown();
            }

            @Override
            public void onError(final Session session, final Throwable throwable) {
                latch.countDown();
                if (session.isOpen()) {
                    doClose(session);
                }
                fail(throwable.getMessage());
            }

            private void doClose(final Session session) {
                try {
                    session.close(new CloseReason(CloseReason.CloseCodes.GOING_AWAY, "bye bye"));
                } catch (final IOException e) {
                    fail(e.getMessage());
                }
            }
        }, clientEndpointConfig, URI.create("ws://localhost:" + config.getHttpPort() + "/websocket/v1/bus"));
    } catch (final DeploymentException | IOException e) {
        fail(e.getMessage());
        throw new IllegalStateException(e);
    }
    try {
        final RemoteEndpoint.Async asyncRemote = session.getAsyncRemote();
        final String payload = "SEND\r\ndestination:" + uri + "\r\ndestinationMethod:" + method + "\r\nAccept: " + type + "\r\nContent-Type: " + "application/json\r\n\r\n" + body + "^@";
        asyncRemote.sendBinary(ByteBuffer.wrap(payload.getBytes(StandardCharsets.UTF_8)));
        latch.await(1, MINUTES);
    } catch (final InterruptedException e) {
        Thread.interrupted();
        fail(e.getMessage());
    }
    try {
        final String index = indexHolder.get();
        assertTrue(index.startsWith("MESSAGE\r\n"), index);
        assertTrue(index.contains("Content-Type: " + type + "\r\n"), index);
        final int startJson = index.indexOf('{');
        final int endJson = index.indexOf("^@");
        assertTrue(startJson > 0, index);
        assertTrue(endJson > startJson, index);
        if (String.class == response) {
            return response.cast(index.substring(startJson, endJson));
        }
        try (final Jsonb jsonb = JsonbProvider.provider().create().build()) {
            final T ci = jsonb.fromJson(index.substring(startJson, endJson), response);
            assertNotNull(ci);
            return ci;
        } catch (final Exception e) {
            fail(e.getMessage());
            throw new IllegalStateException(e);
        }
    } finally {
        if (session.isOpen()) {
            try {
                session.close(new CloseReason(CloseReason.CloseCodes.GOING_AWAY, "bye bye"));
            } catch (IOException e) {
                fail(e.getMessage());
            }
        }
    }
}
Also used : MessageHandler(javax.websocket.MessageHandler) Jsonb(javax.json.bind.Jsonb) Endpoint(javax.websocket.Endpoint) RemoteEndpoint(javax.websocket.RemoteEndpoint) CloseReason(javax.websocket.CloseReason) ClientEndpointConfig(javax.websocket.ClientEndpointConfig) WebSocketContainer(javax.websocket.WebSocketContainer) AtomicReference(java.util.concurrent.atomic.AtomicReference) RemoteEndpoint(javax.websocket.RemoteEndpoint) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuffer(java.nio.ByteBuffer) Endpoint(javax.websocket.Endpoint) RemoteEndpoint(javax.websocket.RemoteEndpoint) DeploymentException(javax.websocket.DeploymentException) IOException(java.io.IOException) DeploymentException(javax.websocket.DeploymentException) ClientEndpointConfig(javax.websocket.ClientEndpointConfig) EndpointConfig(javax.websocket.EndpointConfig) Session(javax.websocket.Session)

Example 45 with CloseReason

use of javax.websocket.CloseReason in project knox by apache.

the class ProxyInboundClientTest method testClientInstance.

// @Test(timeout = 3000)
@Test
public void testClientInstance() throws IOException, DeploymentException {
    final String textMessage = "Echo";
    final AtomicBoolean isTestComplete = new AtomicBoolean(false);
    final WebSocketContainer container = ContainerProvider.getWebSocketContainer();
    final ProxyInboundClient client = new ProxyInboundClient(new MessageEventCallback() {

        @Override
        public void doCallback(String message) {
        }

        @Override
        public void onConnectionOpen(Object session) {
        }

        @Override
        public void onConnectionClose(CloseReason reason) {
            isTestComplete.set(true);
        }

        @Override
        public void onError(Throwable cause) {
            isTestComplete.set(true);
        }

        @Override
        public void onMessageText(String message, Object session) {
            receivedMessage = message;
            isTestComplete.set(true);
        }

        @Override
        public void onMessageBinary(byte[] message, boolean last, Object session) {
        }

        @Override
        public void onMessagePong(PongMessage message, Object session) {
        }
    });
    Assert.assertThat(client, instanceOf(javax.websocket.Endpoint.class));
    Session session = container.connectToServer(client, serverUri);
    session.getBasicRemote().sendText(textMessage);
    while (!isTestComplete.get()) {
    // NOPMD
    /* just wait for the test to finish */
    }
    Assert.assertEquals("The received text message is not the same as the sent", textMessage, receivedMessage);
}
Also used : WebSocketContainer(javax.websocket.WebSocketContainer) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CloseReason(javax.websocket.CloseReason) PongMessage(javax.websocket.PongMessage) Session(javax.websocket.Session) Test(org.junit.Test)

Aggregations

CloseReason (javax.websocket.CloseReason)47 IOException (java.io.IOException)26 Session (javax.websocket.Session)21 URI (java.net.URI)9 Test (org.junit.Test)8 Endpoint (javax.websocket.Endpoint)7 EndpointConfig (javax.websocket.EndpointConfig)7 ByteBuffer (java.nio.ByteBuffer)6 CountDownLatch (java.util.concurrent.CountDownLatch)6 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)6 AtomicReference (java.util.concurrent.atomic.AtomicReference)5 WebSocketContainer (javax.websocket.WebSocketContainer)4 ServerWebSocketContainer (io.undertow.websockets.jsr.ServerWebSocketContainer)3 UndertowSession (io.undertow.websockets.jsr.UndertowSession)3 Iterator (java.util.Iterator)3 ClientEndpointConfig (javax.websocket.ClientEndpointConfig)3 UserPass (com.disney.groovity.tags.Credentials.UserPass)2 ScriptHelper (com.disney.groovity.util.ScriptHelper)2 AuthorizationRequest (com.disney.http.auth.AuthorizationRequest)2 DigestAuthorization (com.disney.http.auth.DigestAuthorization)2