public String encode(UserVisitBean userDiagramData) throws EncodeException { StringWriter writer = new StringWriter(); //Makes use of the JSON Streaming API to build the JSON string. Json.createGenerator(writer) .writeStartObject() .write("time", String.valueOf(userDiagramData.getTime())) .write("totalFlow", userDiagramData.getTotalFlow()) .write("checkInFlow", userDiagramData.getCheckInFlow()) .write("checkInRatio", userDiagramData.getCheckInRate()) .write("deepVisitRatio", userDiagramData.getDeepVisitRate()) .write("jumpRatio", userDiagramData.getShallowVisitRate()) .writeEnd() .flush(); //System.out.println(writer.toString()); return writer.toString(); }
protected final void processResult(Object result) { if (result == null) { return; } RemoteEndpoint.Basic remoteEndpoint = session.getBasicRemote(); try { if (result instanceof String) { remoteEndpoint.sendText((String) result); } else if (result instanceof ByteBuffer) { remoteEndpoint.sendBinary((ByteBuffer) result); } else if (result instanceof byte[]) { remoteEndpoint.sendBinary(ByteBuffer.wrap((byte[]) result)); } else { remoteEndpoint.sendObject(result); } } catch (IOException ioe) { throw new IllegalStateException(ioe); } catch (EncodeException ee) { throw new IllegalStateException(ee); } }
private void handleSendFailureWithEncode(Throwable t) throws IOException, EncodeException { // First, unwrap any execution exception if (t instanceof ExecutionException) { t = t.getCause(); } // Close the session wsSession.doClose(new CloseReason(CloseCodes.GOING_AWAY, t.getMessage()), new CloseReason(CloseCodes.CLOSED_ABNORMALLY, t.getMessage())); // Rethrow the exception if (t instanceof EncodeException) { throw (EncodeException) t; } if (t instanceof IOException) { throw (IOException) t; } throw new IOException(t); }
public void connect(long timeout, TimeUnit unit) throws DeploymentException, IOException, EncodeException, InterruptedException, ExecutionException, TimeoutException { if (getState() != State.DISCONNECTED) { throw new IllegalStateException("Connection open, or in progress!"); } this.session = ContainerProvider.getWebSocketContainer().connectToServer(this, this.uri); this.state = State.CONNECTING; final Frame connectFrame = Frame.connect(this.uri.getHost(), "1.2").heartbeat(5_000, 5_000).build(); sendToClient(connectFrame); this.connectFuture = new CompletableFuture<>(); final Frame connectedFrame = this.connectFuture.get(timeout, unit); this.connectFuture = null; final long readDelay = Math.max(connectedFrame.heartBeat().get().x, connectFrame.heartBeat().get().y); final long writeDelay = Math.max(connectFrame.heartBeat().get().x, connectedFrame.heartBeat().get().y); this.heartBeatMonitor.start(readDelay, writeDelay); }
/** * * @param msg */ public void fromBroker(@Observes @FromBroker Message msg) { final String sessionId = msg.sessionId(); final Frame frame = msg.frame(); this.log.debug("Sending message to client. [sessionId={},command={}]", sessionId, frame.command() != null ? frame.command() : "HEARTBEAT"); Optional<Session> session = getSession(sessionId); if (!session.isPresent()) { // Java 9 has #ifPresentOrElse(...) this.log.error("Unable to find session! [{}]", sessionId); } getSession(sessionId).ifPresent(s -> { try { s.getBasicRemote().sendObject(frame); } catch (IOException | EncodeException e) { this.log.error("Unable to send message! [sessionid={},command={}]", sessionId, frame.command(), e); } }); }
@Test public void onError() throws IOException, EncodeException { final Session session = mock(Session.class); when(session.getId()).thenReturn("sessionId"); final Throwable cause = new Throwable(); when(this.errorEvent.select(OnError.Literal.onError())).thenReturn(this.errorEvent); final Basic basic = mock(Basic.class); when(session.getBasicRemote()).thenReturn(basic); this.endpoint.onError(session, cause); verify(session).getId(); verify(session).getUserPrincipal(); verify(this.log).warn(eq("WebSocket error. [id={},principle={},errorId={}]"), eq("sessionId"), isNull(), anyString(), eq(cause)); verify(this.errorEvent).select(OnError.Literal.onError()); verify(this.errorEvent).fire(cause); verify(session).getBasicRemote(); verify(basic).sendObject(any(Frame.class)); verify(session).close(any(CloseReason.class)); verifyNoMoreInteractions(session, basic); }
@Test public void fromBroker() throws IOException, EncodeException { final Message msg = mock(Message.class); when(msg.sessionId()).thenReturn("sessionId"); final Frame frame = mock(Frame.class); when(msg.frame()).thenReturn(frame); when(frame.command()).thenReturn(Command.MESSAGE); final Session session = Mockito.mock(Session.class); getSessionMap().put("sessionId", session); getPrincipalSessionMap().put(NULL_PRINCIPLE, new HashSet<>(singleton(session))); final Basic basic = mock(Basic.class); when(session.getBasicRemote()).thenReturn(basic); this.registry.fromBroker(msg); verify(msg).sessionId(); verify(msg).frame(); verify(frame, times(2)).command(); verify(this.log).debug("Sending message to client. [sessionId={},command={}]", "sessionId", Command.MESSAGE); verify(session).getBasicRemote(); verify(basic).sendObject(frame); verifyNoMoreInteractions(msg, frame, session, basic); }
@Test public void fromBroker_ioe() throws IOException, EncodeException { final Message msg = mock(Message.class); when(msg.sessionId()).thenReturn("sessionId"); final Frame frame = mock(Frame.class); when(msg.frame()).thenReturn(frame); when(frame.command()).thenReturn(Command.MESSAGE); final Session session = Mockito.mock(Session.class); getSessionMap().put("sessionId", session); getPrincipalSessionMap().put(NULL_PRINCIPLE, new HashSet<>(singleton(session))); final Basic basic = mock(Basic.class); when(session.getBasicRemote()).thenReturn(basic); final IOException ioe = new IOException(); doThrow(ioe).when(basic).sendObject(frame); this.registry.fromBroker(msg); verify(msg).sessionId(); verify(msg).frame(); verify(frame, times(3)).command(); verify(this.log).debug("Sending message to client. [sessionId={},command={}]", "sessionId", Command.MESSAGE); verify(session).getBasicRemote(); verify(basic).sendObject(frame); verify(this.log).error("Unable to send message! [sessionid={},command={}]", "sessionId", Command.MESSAGE, ioe); verifyNoMoreInteractions(msg, frame, session, basic); }
@OnMessage public void onWebSocketText(final Session sess, final JSONRPC2Message msg) throws IOException, EncodeException { this.latestMessage = msg; if (msg instanceof JSONRPC2Request) { //All operations that are invokable on ContextManager that does not return void System.out.println("The message is a Request " + msg.toJSONString()); final JSONRPC2Response data = new JSONRPC2Response(((JSONRPC2Request) msg).getID()); final Map<String,String> result = Maps.newHashMap(); result.put("decision", "valid"); result.put("reason", ""); data.setResult(result); sess.getBasicRemote().sendObject(data); } else if (msg instanceof JSONRPC2Notification) { //All operations that are invokable on ContextManager that does return void System.out.println("The message is a Notification " + msg.toJSONString()); } else if (msg instanceof JSONRPC2Response) { //Can only be ContextChangesPending System.out.println("The message is a Response " + msg.toJSONString()); } }
/** * Try sending the {@link Message} using * {@link Session#getBasicRemote()}, {@link Basic#sendObject(Object)}. * * @param session Session to send the message on * @param message Message to send * @return true if send was successful, or false if it failed */ private boolean sendMessageToSession(Session session, Message message) { if (session.isOpen()) { try { session.getBasicRemote().sendObject(message); return true; } catch (EncodeException e) { // Something was wrong encoding this message, but the connection // is likely just fine. Log.log(Level.FINE, this, "Unexpected condition writing message", e); } catch (IOException ioe) { // An IOException, on the other hand, suggests the connection is // in a bad state. Log.log(Level.FINE, this, "Unexpected condition writing message", ioe); tryToClose(session, new CloseReason(CloseCodes.UNEXPECTED_CONDITION, trimReason(ioe.toString()))); } } return false; }
@Override public String encode(AsciidocMessage m) throws EncodeException { StringWriter swriter = new StringWriter(); try (JsonWriter jsonWrite = Json.createWriter(swriter)) { JsonObjectBuilder builder = Json.createObjectBuilder(); builder.add("type", m.getType().toString()) .add("adocId", m.getAdocId()) .add("data", Json.createObjectBuilder() .add("format", m.getFormat().toString()) .add("source", m.getAdocSource()) .add("sourceToMerge", m.getAdocSourceToMerge()!=null?m.getAdocSourceToMerge():"")); jsonWrite.writeObject(builder.build()); } return swriter.toString(); }
@Override public String encode(NotificationMessage m) throws EncodeException { StringWriter swriter = new StringWriter(); try (JsonWriter jsonWrite = Json.createWriter(swriter)) { JsonObjectBuilder builder = Json.createObjectBuilder(); builder.add("type", m.getType().toString()). add("adocId", m.getAdocId()). add( "data", Json.createObjectBuilder() .add("nbConnected", m.getNbConnected()) .add("nbWriters", m.getWriters().size()) .add("writers", toJSON(m.getWriters()))); jsonWrite.writeObject(builder.build()); } return swriter.toString(); }
/** * Called when a message is received. The WebSocket container will take * data from the socket, and will transform it into the parameter EchoObject * using the {@link EchoDecoder}. * @param o Parameters converted into an EchoObject via the <code>EchoDecoder</code> * @param session The session associated with this message * @throws IOException * @throws EncodeException */ @OnMessage public void receiveMessage(EchoObject o, Session session) throws IOException, EncodeException { // Called when a message is received. // Single endpoint per connection by default --> @OnMessage methods are single threaded! // Endpoint/per-connection instances can see each other through sessions. if (o.stopRequest()) { session.close(); } else { // Simple broadcast for (Session s : session.getOpenSessions()) { s.getBasicRemote().sendObject(o); } } }
/** * WebSocket session opened event handler. * * @param session - Session that has been opened */ @OnOpen public void open(Session session) { this.session = session; System.out.println("Session opened with ID: " + session.getId()); BallotBox ballotBox = BallotBox.getInstance(); ballotBox.addObserver(this); session.getUserProperties().put("ballotbox", ballotBox); try { notify(ballotBox); } catch (IOException | EncodeException e) { e.printStackTrace(); } }
/** * Try sending the {@link RoutedMessage} using * {@link Session#getBasicRemote()}, {@link Basic#sendObject(Object)}. * * @param session * Session to send the message on * @param message * {@link RoutedMessage} to send * @return true if send was successful, or false if it failed */ public static boolean sendMessage(Session session, RoutedMessage message) { if (session.isOpen()) { try { session.getBasicRemote().sendObject(message); return true; } catch (EncodeException e) { Log.log(Level.FINEST, session, "Unexpected condition writing message", e); // Something was wrong encoding this message, but the connection // is likely just fine. } catch (IOException ioe) { // An IOException, on the other hand, suggests the connection is // in a bad state. Log.log(Level.FINEST, session, "Unexpected condition writing message", ioe); tryToClose(session, new CloseReason(CloseCodes.UNEXPECTED_CONDITION, trimReason(ioe.toString()))); } } return false; }
@Override public ByteBuffer encode(WebSocketMessage msg) throws EncodeException { Builder msgBuilder = MessageProtos.Message.newBuilder(); if (msg.getEvent() != null && !"".equals(msg.getEvent())) msgBuilder.setEvent(msg.getEvent().toString()); if (msg.getChannel() != null && !"".equals(msg.getChannel())) msgBuilder.setChannel(msg.getChannel()); if (msg.getFrom() != null && !"".equals(msg.getFrom())) msgBuilder.setFrom(msg.getFrom()); if (msg.getId() != null && !"".equals(msg.getId())) msgBuilder.setId(msg.getId()); if (msg.getPayload() != null) msgBuilder.setData(ByteString.copyFrom(msg.getPayload())); return ByteBuffer.wrap(msgBuilder.build().toByteArray()); }
@Test public void shouldEncodeObject() throws EncodeException { // given Message message = create()// .from("A")// .to("B")// .content("con")// .signal("sig")// .build(); // when String result = encoder.encode(message); // then assertNotNull(result); assertThat(result, containsString(replaceQuotes("'content':'con'"))); assertThat(result, containsString(replaceQuotes("'from':'A'"))); assertThat(result, containsString(replaceQuotes("'to':'B'"))); assertThat(result, containsString(replaceQuotes("'signal':'sig'"))); }
@Test public void shouldEncodeObjectWithNullValues() throws EncodeException { // given Message message = create()// .from(null)// .to(null)// .build(); // when String result = encoder.encode(message); // then assertNotNull(result); assertThat(result, not(containsString(replaceQuotes("'from'")))); assertThat(result, not(containsString(replaceQuotes("'to'")))); }
/** * Send Live Match message for all peers connected to this match * @param msg * @param matchId */ public static void send(MatchMessage msg, String matchId) { try { /* Send updates to all open WebSocket sessions for this match */ for (Session session : peers) { if (Boolean.TRUE.equals(session.getUserProperties().get(matchId))){ if (session.isOpen()){ session.getBasicRemote().sendObject(msg); logger.log(Level.INFO, " Score Sent: {0}", msg); } } } } catch (IOException | EncodeException e) { logger.log(Level.INFO, e.toString()); } }
@Override public Future<MatlabResult> exec(MatlabRequest request) throws MatlabException, IOException { Preconditions.checkState(session != null && session.isOpen()); try { SettableFuture<MatlabResult> future = SettableFuture.create(); SettableFuture<MatlabResult> oldFuture = this.responses.putIfAbsent(request.getId(), future); if (oldFuture != null) { // we already executed that request... return oldFuture; } session.getBasicRemote().sendObject(request); return future; } catch (EncodeException ex) { throw new RuntimeException(ex); } }
public void sendMessage(Message message) throws IOException, EncodeException { if (session == null) { System.out.println("debuger_delf: session is null"); } session.getBasicRemote().sendObject(message); Log.d("delf", "[CLIENT] send message to server: " + message.toString()); }
private void handleSendFailure(Throwable t) throws IOException { try { handleSendFailureWithEncode(t); } catch (EncodeException e) { // Should never happen. But in case it does... throw new IOException(e); } }
@Override public ByteBuffer encode(MsgByte msg) throws EncodeException { byte[] data = msg.getData(); ByteBuffer reply = ByteBuffer.allocate(2 + data.length); reply.put((byte) 0x12); reply.put((byte) 0x34); reply.put(data); reply.flip(); return reply; }
@Override public String encode(List<String> str) throws EncodeException { StringBuffer sbuf = new StringBuffer(); sbuf.append("["); for (String s: str){ sbuf.append(s).append(","); } sbuf.deleteCharAt(sbuf.lastIndexOf(",")).append("]"); return sbuf.toString(); }
@Test public void testUnsupportedObject() throws Exception{ Tomcat tomcat = getTomcatInstance(); // No file system docBase required Context ctx = tomcat.addContext("", null); ctx.addApplicationListener(ProgramaticServerEndpointConfig.class.getName()); Tomcat.addServlet(ctx, "default", new DefaultServlet()); ctx.addServletMapping("/", "default"); WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer(); tomcat.start(); Client client = new Client(); URI uri = new URI("ws://localhost:" + getPort() + PATH_PROGRAMMATIC_EP); Session session = wsContainer.connectToServer(client, uri); // This should fail Object msg1 = new Object(); try { session.getBasicRemote().sendObject(msg1); Assert.fail("No exception thrown "); } catch (EncodeException e) { // Expected } catch (Throwable t) { Assert.fail("Wrong exception type"); } finally { session.close(); } }
public void notify(TodoChangedEvent e) throws EncodeException { ToDo todo = e.getTodo(); String time = new SimpleDateFormat("HH:mm").format(new Date()); Class<? extends TodoChangedEvent> aClass = e.getClass(); ChangeEvent annotation = aClass.getAnnotation(ChangeEvent.class); ChangeEvent.Type value = annotation.value(); SocketOutputMessage socketOutputMessage = new SocketOutputMessage(todo, value.toString(), time); template.convertAndSend("/topic/todos", socketOutputMessage); }
/** Send change name message and name to server */ public void sendNicknameChangeMessage(String nickname) { Message changeNicknameMsg = new Message().setType(Message.REQUEST_CHANGE_NAME); changeNicknameMsg.add(Message.CHANGE_NAME, nickname); try { endpoint.sendMessage(changeNicknameMsg); } catch (IOException | EncodeException e) { e.printStackTrace(); } }
/** Send join group messgae and group key to server */ public void sendGroupJoinMessage() { if (groupKeyTF.getText().length() != 0) { Message signUpMsg = new Message().setType(Message.REQUEST_JOIN_GROUP); signUpMsg.add(Message.GROUP_PK, groupKeyTF.getText()); try { endpoint.sendMessage(signUpMsg); } catch (IOException | EncodeException e) { e.printStackTrace(); } } }
public void sendWithout(String user, Message message) throws IOException, EncodeException { System.out.println("[Group] send message to all users of group except \"" + user + "\" : " + message.toString()); for (String key : users.keySet()) { if (key.equals(user)) // except continue; users.get(key).getSession().getBasicRemote().sendObject(message); } }
public boolean sendAll(Message message) throws IOException, EncodeException { if (users.size() == 0) { return true; } for (String key : users.keySet()) { users.get(key).getSession().getBasicRemote().sendObject(message); } return false; }