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();
}
}
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())));
}
}
}
}
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) {
}
}
}
}
}
}
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());
}
}
}
}
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);
}
Aggregations