public RedisSocket(final NetSocket socket) { this.socket = socket; this.output = new RedisOutputStream(socket); this.pendingCommands = new ConcurrentLinkedQueue<>(); this.input = new RedisInputStream(pendingCommands); socket.handler(new Handler<Buffer>() { public void handle(Buffer buff) { try { log.trace("handle", "beforeProcessBuffer"); input.processBuffer(buff); } catch (Exception ex) { log.error("handle", "exception", "unknown", ex); // Error processing the commands so close the socket. socket.close(); } } }); }
public void init(NetSocket netSocket) { // currently, socket always be NetSocketImpl this.initNetSocket((NetSocketImpl) netSocket); String remoteAddress = netSocket.remoteAddress().toString(); LOGGER.info("connect from {}, in thread {}", remoteAddress, Thread.currentThread().getName()); netSocket.exceptionHandler(e -> { LOGGER.error("disconected from {}, in thread {}, cause {}", remoteAddress, Thread.currentThread().getName(), e.getMessage()); }); netSocket.closeHandler(Void -> { LOGGER.error("disconected from {}, in thread {}", remoteAddress, Thread.currentThread().getName()); }); netSocket.handler(splitter); }
@Test public void connect_failed() { requestMap.put(10L, new TcpRequest(10, ar -> { })); FutureFactoryImpl futureFactory = new FutureFactoryImpl(); Error error = new Error(); new MockUp<NetClientWrapper>(netClientWrapper) { @Mock void connect(boolean ssl, int port, String host, Handler<AsyncResult<NetSocket>> connectHandler) { connectHandler.handle(futureFactory.failedFuture(error)); } }; tcpClientConnection.connect(); Assert.assertEquals(Status.DISCONNECTED, Deencapsulation.getField(tcpClientConnection, "status")); Assert.assertEquals(0, requestMap.size()); }
protected void initSocket (NetSocket socket) { //set connection close handler socket.closeHandler(res -> { System.err.println("Server connection was closed by server."); //reset flag this.connected.set(false); System.exit(0); }); //add message handler socket.handler(buffer -> { //convert to string and json object String str = buffer.toString(StandardCharsets.UTF_8); //System.out.println("message received: " + str); System.out.println("RECEIVE: " + str); this.messageReceiver.onReceive(str); }); }
private void handleConnectResult(AsyncResult<NetSocket> res) { if (res.failed()) { log.error(format("Connection to gpsd server %s:%d failed", serverHost, serverPort), res.cause()); this.startingLock.unlockWrite(this.startingLockStamp); this.stop(); return; } this.clientSocket = res.result() .closeHandler(__ -> handleClose()) .handler(buf -> { // Split new lines in case the buffer contains multiple JSON objects String[] split = buf.toString().split("(\\r\\n|\\r|\\n)+"); for (String s : split) handleJsonString(s); }); this.running = true; this.startingLock.unlockWrite(this.startingLockStamp); log.info("Successfully connected to gpsd server {}:{}", serverHost, serverPort); this.executeBlockingHandler(this.successfulConnectionHandler, this, false); }
@Override public void start(Handler<AsyncResult<Void>> startFuture) { if (port > 0) { // fail if port is already in use NetClientOptions options = new NetClientOptions().setConnectTimeout(200); NetClient c = vertx.createNetClient(options); c.connect(port, "localhost", res -> { if (res.succeeded()) { NetSocket socket = res.result(); socket.close(); startFuture.handle(Future.failedFuture("port " + port + " already in use")); } else { start2(startFuture); } }); } else { start2(startFuture); } }
private void waitPortToClose(Handler<AsyncResult<Void>> stopFuture, int iter) { if (port > 0) { // fail if port is already in use NetClientOptions options = new NetClientOptions().setConnectTimeout(50); NetClient c = vertx.createNetClient(options); c.connect(port, "localhost", res -> { if (res.succeeded()) { NetSocket socket = res.result(); socket.close(); if (iter > 0) { vertx.setTimer(100, x -> waitPortToClose(stopFuture, iter - 1)); } else { stopFuture.handle(Future.failedFuture("port " + port + " not shut down")); } } else { stopFuture.handle(Future.succeededFuture()); } }); } else { stopFuture.handle(Future.succeededFuture()); } }
@Override public void init(final NetSocket socket, final ProtonConnection protonConnection, final Transport transport) { LOG.debug("initializing SASL authenticator"); this.protonConnection = protonConnection; this.sasl = transport.sasl(); // TODO determine supported mechanisms dynamically based on registered AuthenticationService implementations sasl.server(); sasl.allowSkip(false); sasl.setMechanisms(MECHANISM_EXTERNAL, MECHANISM_PLAIN); if (socket.isSsl()) { LOG.debug("client connected using TLS, extracting client certificate chain"); try { peerCertificateChain = socket.peerCertificateChain(); LOG.debug("found valid client certificate DN [{}]", peerCertificateChain[0].getSubjectDN()); } catch (SSLPeerUnverifiedException e) { LOG.debug("could not extract client certificate chain, maybe TLS based client auth is not required"); } } }
private VertxReconnectableSocket doConnect() { if (!connectLock.tryAcquire ()) { LOGGER.info ("Connect attempt already in progress"); return this; } client.connect(uri.getPort (), uri.getHost (), res -> { if (res.succeeded()) { LOGGER.info("Connected to {}", uri); NetSocket socket = res.result(); socket.closeHandler (reconnectOnClose ()); socket.handler (responseHandler ()); socket.exceptionHandler (exceptionHandler()); this.socket.set (socket); connectLock.release (); } else { connectLock.release (); LOGGER.warn ("Failed to connect: " + res.cause().getMessage()); reconnect (); } }); return this; }
@Override public ProtonSaslAuthenticator create() { return new ProtonSaslAuthenticator() { @Override public void init(NetSocket socket, ProtonConnection protonConnection, Transport transport) { } @Override public void process(Handler<Boolean> completionHandler) { completionHandler.handle(true); } @Override public boolean succeeded() { return true; } }; }
/** * add client * * @param socket network socket */ protected void addClient (NetSocket socket) { //create new client instance ChatClient client = new ChatClient(socket, this.messageReceiver); //set close handler socket.closeHandler(v -> { //remove client from map clientMap.remove(client.getClientID()); //cleanUp client client.cleanUp(); }); //put client to map this.clientMap.put(client.getClientID(), client); }
public ChatClient (NetSocket socket, MessageListener messageListener) { this.socket = socket; this.messageListener = messageListener; //generate new clientID this.clientID = this.lastID.incrementAndGet(); //add message handler this.socket.handler(buffer -> { try { //call message received listener messageReceived(buffer); } catch (Exception e) { //print exception System.err.println("exception while reading message from client " + this.clientID + ":"); e.printStackTrace(); } }); //send welcome message this.sendWelcomeMessage(); }
/** * initialize socket * * @param socket network socket */ protected void initSocket (NetSocket socket) { //set connection close handler socket.closeHandler(res -> { System.err.println("Server connection was closed by server."); System.exit(0); }); //add message handler socket.handler(buffer -> { //convert to string and json object String str = buffer.toString(StandardCharsets.UTF_8); JSONObject json = new JSONObject(str); //System.out.println("message received: " + str); //convert to chat message ChatMessage msg = ChatMessage.create(json); //call message receiver messageReceiver.messageReceived(msg); }); }
@Test public void testSendMessageWithReplyBacktrack(TestContext context) { // Send a request and get a response NetClient client = vertx.createNetClient(); final Async async = context.async(); client.connect(7000, "localhost", conn -> { context.assertFalse(conn.failed()); NetSocket socket = conn.result(); final FrameParser parser = new FrameParser(parse -> { context.assertTrue(parse.succeeded()); JsonObject frame = parse.result(); context.assertNotEquals("err", frame.getString("type")); context.assertEquals("Hello vert.x", frame.getJsonObject("body").getString("value")); client.close(); async.complete(); }); socket.handler(parser); FrameHelper.sendFrame("send", "hello", "#backtrack", new JsonObject().put("value", "vert.x"), socket); }); }
@Test public void testSendMessageWithDuplicateReplyID(TestContext context) { // replies must always return to the same origin NetClient client = vertx.createNetClient(); final Async async = context.async(); client.connect(7000, "localhost", conn -> { context.assertFalse(conn.failed()); NetSocket socket = conn.result(); vertx.eventBus().consumer("third-party-receiver", msg -> context.fail()); final FrameParser parser = new FrameParser(parse -> { context.assertTrue(parse.succeeded()); client.close(); async.complete(); }); socket.handler(parser); FrameHelper.sendFrame("send", "hello", "third-party-receiver", new JsonObject().put("value", "vert.x"), socket); }); }
@Test public void testSendVoidMessage(TestContext context) { // Send a request and get a response NetClient client = vertx.createNetClient(); final Async async = context.async(); vertx.eventBus().consumer("test", (Message<JsonObject> msg) -> { client.close(); async.complete(); }); client.connect(7000, "localhost", conn -> { context.assertFalse(conn.failed()); NetSocket socket = conn.result(); FrameHelper.sendFrame("send", "test", new JsonObject().put("value", "vert.x"), socket); }); }
@Test public void testSendsFromOtherSideOfBridge(TestContext context) { NetClient client = vertx.createNetClient(); final Async async = context.async(); client.connect(7000, "localhost", conn -> { context.assertFalse(conn.failed()); NetSocket socket = conn.result(); final FrameParser parser = new FrameParser(parse -> { context.assertTrue(parse.succeeded()); JsonObject frame = parse.result(); context.assertNotEquals("err", frame.getString("type")); context.assertEquals(true, frame.getBoolean("send")); context.assertEquals("hi", frame.getJsonObject("body").getString("value")); client.close(); async.complete(); }); socket.handler(parser); FrameHelper.sendFrame("register", "ping", null, socket); }); }
@Test public void testSendMessageWithReplyBacktrack(TestContext context) { // Send a request and get a response NetClient client = vertx.createNetClient(); final Async async = context.async(); client.connect(7000, "localhost", conn -> { context.assertFalse(conn.failed()); NetSocket socket = conn.result(); final FrameParser parser = new FrameParser(parse -> { context.assertTrue(parse.succeeded()); JsonObject frame = parse.result(); context.assertNotEquals("err", frame.getString("type")); context.assertEquals(true, frame.getBoolean("send")); context.assertEquals("Hello vert.x", frame.getJsonObject("body").getString("value")); client.close(); async.complete(); }); socket.handler(parser); FrameHelper.sendFrame("send", "hello", "#backtrack", new JsonObject().put("value", "vert.x"), socket); }); }
/** * Creates a {@link StompClientConnectionImpl} instance * * @param vertx the vert.x instance * @param socket the underlying TCP socket * @param client the stomp client managing this connection * @param resultHandler the result handler to invoke then the connection has been established */ public StompClientConnectionImpl(Vertx vertx, NetSocket socket, StompClient client, Handler<AsyncResult<StompClientConnection>> resultHandler) { this.socket = socket; this.client = client; this.resultHandler = resultHandler; this.context = vertx.getOrCreateContext(); FrameParser parser = new FrameParser(); parser.handler(this); socket.handler(buffer -> { lastServerActivity = System.nanoTime(); parser.handle(buffer); }) .closeHandler(v -> { if (!closed && !client.isClosed()) { close(); if (droppedHandler != null) { droppedHandler.handle(this); } } }); }
@Test public void testFrameHandlerWithInvalidFramesReceivedByServer() throws InterruptedException { AtomicReference<StompClientConnection> reference = new AtomicReference<>(); client.connect(connection -> { reference.set(connection.result()); }); await().atMost(10, TimeUnit.SECONDS).until(() -> containsFrameWithCommand(receivedByServer, Frame.Command.CONNECT)); await().atMost(10, TimeUnit.SECONDS).until(() -> containsFrameWithCommand(receivedByClient, Frame.Command.CONNECTED)); StompClientConnectionImpl impl = (StompClientConnectionImpl) reference.get(); NetSocket socket = impl.socket(); socket.write(UNKNOWN_FRAME); await().atMost(10, TimeUnit.SECONDS).until(() -> containsFrameWithCommand(receivedByServer, Frame.Command.UNKNOWN)); Frame frame = getFrameWithCommand(receivedByServer, Frame.Command.UNKNOWN); assertThat(frame).isNotNull(); assertThat(frame.getHeader(Frame.STOMP_FRAME_COMMAND)).isEqualToIgnoringCase("YEAH"); }
@Test public void testConnection(TestContext context) { Async async = context.async(); client = vertx.createNetClient().connect(server.actualPort(), "0.0.0.0", result -> { if (result.failed()) { context.fail("Connection failed"); return; } NetSocket socket = result.result(); socket.handler(buffer -> { context.assertTrue(buffer.toString().contains("CONNECTED")); context.assertTrue(buffer.toString().contains("version:1.2")); // Optional headers: context.assertTrue(buffer.toString().contains("session:")); context.assertTrue(buffer.toString().contains("server:")); async.complete(); }); socket.write("CONNECT\n" + "accept-version:1.2\n" + "\n" + FrameParser.NULL); }); }
@Test public void testConnectionWithSeveralVersions(TestContext context) { Async async = context.async(); client = vertx.createNetClient().connect(server.actualPort(), "0.0.0.0", result -> { if (result.failed()) { context.fail("Connection failed"); return; } NetSocket socket = result.result(); socket.handler(buffer -> { context.assertTrue(buffer.toString().contains("CONNECTED")); context.assertTrue(buffer.toString().contains("version:1.1")); async.complete(); }); socket.write("CONNECT\n" + "accept-version:1.0,1.1\n" + "\n" + FrameParser.NULL); }); }
@Test public void testConnectionWithoutVersionHeader(TestContext context) { Async async = context.async(); client = vertx.createNetClient().connect(server.actualPort(), "0.0.0.0", result -> { if (result.failed()) { context.fail("Connection failed"); return; } NetSocket socket = result.result(); socket.handler(buffer -> { context.assertTrue(buffer.toString().contains("CONNECTED")); context.assertTrue(buffer.toString().contains("version:1.0")); async.complete(); }); socket.write("CONNECT\n" + "\n" + FrameParser.NULL); }); }
@Test public void testConnectionWithInvalidVersions(TestContext context) { Async async = context.async(); client = vertx.createNetClient().connect(server.actualPort(), "0.0.0.0", result -> { if (result.failed()) { context.fail("Connection failed"); return; } NetSocket socket = result.result(); socket.handler(buffer -> { context.assertTrue(buffer.toString().contains("ERROR")); context.assertTrue(buffer.toString().contains("version:1.2")); context.assertTrue(buffer.toString().contains("Supported protocol versions are 1.2")); async.complete(); }); socket.write("CONNECT\n" + "accept-version:0.0\n" + "\n" + FrameParser.NULL); }); }
@Test public void testConnectionWithInvalidVersionLists(TestContext context) { Async async = context.async(); client = vertx.createNetClient().connect(server.actualPort(), "0.0.0.0", result -> { if (result.failed()) { context.fail("Connection failed"); return; } NetSocket socket = result.result(); socket.handler(buffer -> { context.assertTrue(buffer.toString().contains("ERROR")); context.assertTrue(buffer.toString().contains("version:1.2")); context.assertTrue(buffer.toString().contains("Supported protocol versions are 1.2")); async.complete(); }); socket.write("CONNECT\n" + "accept-version:0.0,3.2\n" + "\n" + FrameParser.NULL); }); }
@Test public void testConnectionWithStompFrame(TestContext context) { Async async = context.async(); client = vertx.createNetClient().connect(server.actualPort(), "0.0.0.0", result -> { if (result.failed()) { context.fail("Connection failed"); return; } NetSocket socket = result.result(); socket.handler(buffer -> { context.assertTrue(buffer.toString().contains("CONNECTED")); context.assertTrue(buffer.toString().contains("version:1.2")); // Optional headers: context.assertTrue(buffer.toString().contains("session:")); context.assertTrue(buffer.toString().contains("server:")); async.complete(); }); socket.write("STOMP\n" + "accept-version:1.2\n" + "\n" + FrameParser.NULL); }); }
@Test public void testInvalidUnsubscribe(TestContext context) { List<Buffer> frames = new ArrayList<>(); AtomicReference<NetSocket> reference = new AtomicReference<>(); client = vertx.createNetClient().connect(server.actualPort(), "0.0.0.0", result -> { if (result.failed()) { context.fail("Connection failed"); return; } NetSocket socket = result.result(); reference.set(socket); socket.handler(buffer -> { if (buffer.toString().contains("CONNECTED")) { socket.write("UNSUBSCRIBE\n" + "id:0\n\n" + FrameParser.NULL); } else { frames.add(buffer); } }); socket.write("CONNECT\n" + "accept-version:1.2\n" + "\n" + FrameParser.NULL); }); Awaitility.await().atMost(10, TimeUnit.SECONDS).until(() -> frames.size() >= 1); assertThat(frames.get(0).toString()).startsWith("ERROR"); }
@Test public void testMalformedFrame(TestContext context) { List<Buffer> frames = new ArrayList<>(); client = vertx.createNetClient().connect(server.actualPort(), "0.0.0.0", result -> { if (result.failed()) { context.fail("Connection failed"); return; } NetSocket socket = result.result(); socket.handler(frames::add); socket.write("CONNECT\n" + "accept-version:1.2\n" + "\n" + "illegal body" + FrameParser.NULL); }); Awaitility.await().atMost(10, TimeUnit.SECONDS).until(() -> frames.size() >= 1); assertThat(frames.get(0).toString()).startsWith("ERROR"); }
@Test public void testAuthenticatedConnection(TestContext context) { Async async = context.async(); vertx.createNetClient().connect(server.actualPort(), "0.0.0.0", result -> { if (result.failed()) { context.fail("Connection failed"); return; } NetSocket socket = result.result(); socket.handler(buffer -> { validate(context, buffer); async.complete(); }); socket.write("CONNECT\n" + "accept-version:1.2\nlogin:admin\npasscode:admin\n" + "\n" + FrameParser.NULL); }); }
@Test public void testFailedAuthentication(TestContext context) { Async async = context.async(); vertx.createNetClient().connect(server.actualPort(), "0.0.0.0", result -> { if (result.failed()) { context.fail("Connection failed"); return; } NetSocket socket = result.result(); socket.handler(buffer -> { context.assertTrue(buffer.toString().contains("ERROR")); context.assertTrue(buffer.toString().contains("Authentication failed")); async.complete(); }); socket.write("CONNECT\n" + "accept-version:1.2\nlogin:admin\npasscode:nope\n" + "\n" + FrameParser.NULL); }); }
@Test(timeout = 5000) public void testFailedAuthenticationBecauseOfMissingHeaders(TestContext context) { Async async = context.async(); vertx.createNetClient().connect(server.actualPort(), "0.0.0.0", result -> { if (result.failed()) { context.fail("Connection failed"); return; } NetSocket socket = result.result(); socket.handler(buffer -> { context.assertTrue(buffer.toString().contains("ERROR")); context.assertTrue(buffer.toString().contains("Authentication failed")); async.complete(); }); socket.write("CONNECT\n" + "accept-version:1.2\nlogin:admin\n" + "\n" + FrameParser.NULL); }); }
@Test public void testAuthenticatedConnectionWithStompFrame(TestContext context) { Async async = context.async(); vertx.createNetClient().connect(server.actualPort(), "0.0.0.0", result -> { if (result.failed()) { context.fail("Connection failed"); return; } NetSocket socket = result.result(); socket.handler(buffer -> { validate(context, buffer); async.complete(); }); socket.write("STOMP\n" + "accept-version:1.2\nlogin:admin\npasscode:admin\n" + "\n" + FrameParser.NULL); }); }
ProtonTransport(Connection connection, Vertx vertx, NetClient netClient, NetSocket socket, ProtonSaslAuthenticator authenticator, ProtonTransportOptions options) { this.connection = connection; this.vertx = vertx; this.netClient = netClient; this.socket = socket; transport.setMaxFrameSize(options.getMaxFrameSize() == 0 ? DEFAULT_MAX_FRAME_SIZE : options.getMaxFrameSize()); transport.setEmitFlowEventOnSend(false); // TODO: make configurable transport.setIdleTimeout(2 * options.getHeartbeat()); if (authenticator != null) { authenticator.init(this.socket, (ProtonConnection) this.connection.getContext(), transport); } this.authenticator = authenticator; transport.bind(connection); connection.collect(collector); socket.endHandler(this::handleSocketEnd); socket.handler(this::handleSocketBuffer); }
@Test public void testConvertBufferStreamToMessages() { Event event = new Event("test", "test", "test", "test", null, null, 1, 1.0F, 1.0); byte[] bytes = event.toProtoBufMessage().toByteArray(); Riemann.convertBufferStreamToMessages(mock(NetSocket.class), Observable.just( Buffer.buffer().appendInt(bytes.length), Buffer.buffer().appendBytes(Arrays.copyOfRange(bytes, 0, 22)), Buffer.buffer().appendBytes(Arrays.copyOfRange(bytes, 22, 42)) )).forEach(t -> { Proto.Event e = t.getRight().getEventsList().get(0); assertEquals(Event.builder().fromProtoBufEvent(e).build(), event); testComplete(); }); await(); }
@Test public void testFilterCanEcho(TestContext context) { final DeploymentOptions options = buildDeploymentOptions("/config_filter_echo.json"); vertx.deployVerticle(Start.class.getName(), options, context.asyncAssertSuccess(deploymentID -> { final Async async = context.async(); vertx.createNetClient().connect(2500, "localhost", asyncResult -> { final NetSocket socket = asyncResult.result(); socket.write("Hello Filter"); socket.handler(buffer -> { context.assertEquals("Hello Filter", buffer.toString()); async.complete(); }); }); vertx.setTimer(5000, new Handler<Long>() { @Override public void handle(Long event) { context.fail("timed out"); } }); })); }
@Test public void testFilterWithExceptionShouldCloseSocket(TestContext context) { final DeploymentOptions options = buildDeploymentOptions("/config_filter_w_err.json"); vertx.deployVerticle(Start.class.getName(), options, context.asyncAssertSuccess(deploymentID -> { final Async async = context.async(); vertx.createNetClient().connect(2500, "localhost", asyncResult -> { final NetSocket socket = asyncResult.result(); final Buffer bogusPacket = Buffer.buffer("bogus"); socket.write(bogusPacket); // Expect the server to close the socket on us socket.closeHandler(v -> { async.complete(); }); }); vertx.setTimer(5000, event -> { context.fail("timed out"); }); })); }
@Test public void testCanInjectToEventBusFilter(TestContext context) { final String expectedMessage = "Hello"; final DeploymentOptions options = buildDeploymentOptions("/config_message_injector.json"); vertx.deployVerticle(Start.class.getName(), options, context.asyncAssertSuccess(deploymentID -> { final Async async = context.async(); vertx.createNetClient().connect(2500, "localhost", asyncResult -> { final NetSocket socket = asyncResult.result(); vertx.eventBus().<Integer>consumer(EventBusFilter.EVENT_BUS_ADDRESS, msg -> { final Integer hashCode = msg.body(); context.assertEquals(expectedMessage.hashCode(), hashCode); async.complete(); }); socket.write(expectedMessage); }); vertx.setTimer(5000, event -> context.fail("timed out")); })); }
@Test public void testCannotInjectToEventBusFilterIfMessageMatcherMatchesOnInjector(TestContext context) { final String expectedMessage = "MatchBoth"; final DeploymentOptions options = buildDeploymentOptions("/config_message_injector.json"); vertx.deployVerticle(Start.class.getName(), options, context.asyncAssertSuccess(deploymentID -> { final Async async = context.async(); vertx.createNetClient().connect(2500, "localhost", asyncResult -> { final NetSocket socket = asyncResult.result(); socket.closeHandler(v->{ async.complete(); }); socket.write(expectedMessage); }); vertx.setTimer(5000, event -> context.fail("timed out")); })); }
@Test public void testCanEcho(TestContext context) { final DeploymentOptions options = buildDeploymentOptions("/config_simple_echo.json"); vertx.deployVerticle(Start.class.getName(), options, context.asyncAssertSuccess(deploymentID -> { final Async async = context.async(); vertx.createNetClient().connect(2500, "localhost", asyncResult -> { final NetSocket socket = asyncResult.result(); socket.handler(buffer -> { context.assertEquals("Hello", buffer.toString()); async.complete(); }); socket.write("Hello"); }); vertx.setTimer(5000, new Handler<Long>() { @Override public void handle(Long event) { context.fail("timed out"); } }); })); }