io.vertx.core.net.NetSocket Java Examples

The following examples show how to use io.vertx.core.net.NetSocket. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FrameHandlerTest.java    From vertx-stomp with Apache License 2.0 6 votes vote down vote up
@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");
}
 
Example #2
Source File: ServerConnectionTest.java    From vertx-stomp with Apache License 2.0 6 votes vote down vote up
@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);
  });
}
 
Example #3
Source File: VertxRLPxService.java    From cava with Apache License 2.0 6 votes vote down vote up
private void receiveMessage(NetSocket netSocket) {
  netSocket.handler(new Handler<Buffer>() {

    private RLPxConnection conn;

    private DefaultWireConnection wireConnection;

    @Override
    public void handle(Buffer buffer) {
      if (conn == null) {
        conn = RLPxConnectionFactory.respondToHandshake(
            Bytes.wrapBuffer(buffer),
            keyPair,
            bytes -> netSocket.write(Buffer.buffer(bytes.toArrayUnsafe())));
        if (wireConnection == null) {
          this.wireConnection = createConnection(conn, netSocket);
          wireConnection.handleConnectionStart();
        }
      } else {
        conn.stream(Bytes.wrapBuffer(buffer), wireConnection::messageReceived);
      }
    }
  });
}
 
Example #4
Source File: SecureScuttlebuttVertxClient.java    From cava with Apache License 2.0 6 votes vote down vote up
/**
 * Connects the client to a remote host.
 *
 * @param port the port of the remote host
 * @param host the host string of the remote host
 * @param remotePublicKey the public key of the remote host
 * @param handlerFactory the factory of handlers for connections
 * @return a handle to a new stream handler with the remote host
 */
public <T extends ClientHandler> AsyncResult<T> connectTo(
    int port,
    String host,
    Signature.PublicKey remotePublicKey,
    ClientHandlerFactory<T> handlerFactory) {
  client = vertx.createNetClient(new NetClientOptions().setTcpKeepAlive(true));
  CompletableAsyncResult<T> completion = AsyncResult.incomplete();
  client.connect(port, host, res -> {
    if (res.failed()) {
      completion.completeExceptionally(res.cause());
    } else {
      NetSocket socket = res.result();
      new NetSocketClientHandler<T>(
          loggerProvider.getLogger(host + ":" + port),
          socket,
          remotePublicKey,
          handlerFactory,
          completion);
    }
  });

  return completion;
}
 
Example #5
Source File: VertxNetClient.java    From Lealone-Plugins with Apache License 2.0 6 votes vote down vote up
@Override
protected void createConnectionInternal(NetNode node, AsyncConnectionManager connectionManager,
        AsyncCallback<AsyncConnection> ac) {
    InetSocketAddress inetSocketAddress = node.getInetSocketAddress();
    vertxClient.connect(node.getPort(), node.getHost(), res -> {
        if (res.succeeded()) {
            NetSocket socket = res.result();
            VertxWritableChannel channel = new VertxWritableChannel(socket);
            AsyncConnection conn;
            if (connectionManager != null) {
                conn = connectionManager.createConnection(channel, false);
            } else {
                conn = new TcpClientConnection(channel, this);
            }
            conn.setInetSocketAddress(inetSocketAddress);
            AsyncConnection conn2 = addConnection(inetSocketAddress, conn);
            socket.handler(buffer -> {
                conn2.handle(new VertxBuffer(buffer));
            });
            ac.setAsyncResult(conn2);
        } else {
            ac.setAsyncResult(res.cause());
        }
    });
}
 
Example #6
Source File: NetControl.java    From vertx-in-action with MIT License 6 votes vote down vote up
private void handleBuffer(NetSocket socket, Buffer buffer) {
  String command = buffer.toString();
  switch (command) {
    case "/list":
      listCommand(socket);
      break;
    case "/play":
      vertx.eventBus().send("jukebox.play", "");
      break;
    case "/pause":
      vertx.eventBus().send("jukebox.pause", "");
      break;
    default:
      if (command.startsWith("/schedule ")) {
        schedule(command);
      } else {
        socket.write("Unknown command\n");
      }
  }
}
 
Example #7
Source File: SecuredServerConnectionTest.java    From vertx-stomp with Apache License 2.0 6 votes vote down vote up
@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);
  });
}
 
Example #8
Source File: VertxNetClientServerMetricsTest.java    From vertx-micrometer-metrics with Apache License 2.0 6 votes vote down vote up
private void request(NetClient client, TestContext ctx) {
  for (int i = 0; i < SENT_COUNT; i++) {
    Async async = ctx.async();
    client.connect(9194, "localhost", res -> {
      if (res.failed()) {
        async.complete();
        ctx.fail(res.cause());
        return;
      }
      NetSocket socket = res.result().exceptionHandler(t -> {
        async.complete();
        ctx.fail(t);
      });
      socket.handler(buf -> socket.close());
      socket.write(CLIENT_REQUEST);
      socket.closeHandler(v -> async.complete());
    });
    async.await();
  }
}
 
Example #9
Source File: TcpServerConnection.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #10
Source File: TestTcpClientConnection.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Test
public void connect_failed() {
  requestMap.put(10L, new TcpRequest(10, ar -> {
  }));

  FutureFactoryImpl futureFactory = new FutureFactoryImpl();
  RuntimeException error = new RuntimeExceptionWithoutStackTrace();
  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());
}
 
Example #11
Source File: TestRestClientInvocation.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void handleResponse_responseException() {
  HttpClientResponse httpClientResponse = mock(HttpClientResponse.class);

  NetSocket netSocket = mock(NetSocket.class);
  when(httpClientResponse.netSocket()).thenReturn(netSocket);
  when(netSocket.remoteAddress()).thenReturn(mock(SocketAddress.class));

  doAnswer(a -> {
    exceptionHandler = (Handler<Throwable>) a.getArguments()[0];
    return httpClientResponse;
  }).when(httpClientResponse).exceptionHandler(any());

  restClientInvocation.handleResponse(httpClientResponse);
  RuntimeException error = new RuntimeExceptionWithoutStackTrace();
  exceptionHandler.handle(error);

  Assert.assertThat(((InvocationException) response.getResult()).getCause(), Matchers.sameInstance(error));
}
 
Example #12
Source File: PgClientTestBase.java    From vertx-sql-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testDisconnectAbruptlyDuringStartup(TestContext ctx) {
  Async async = ctx.async();
  ProxyServer proxy = ProxyServer.create(vertx, options.getPort(), options.getHost());
  proxy.proxyHandler(conn -> {
    NetSocket clientSo = conn.clientSocket();
    clientSo.handler(buff -> {
      clientSo.close();
    });
    clientSo.resume();
  });
  proxy.listen(8080, "localhost", ctx.asyncAssertSuccess(v1 -> {
    options.setPort(8080).setHost("localhost");
    connector.accept(ctx.asyncAssertFailure(err -> async.complete()));
  }));
}
 
Example #13
Source File: ServerConnectionTest.java    From vertx-stomp with Apache License 2.0 6 votes vote down vote up
@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");
}
 
Example #14
Source File: EventBusNetBridge.java    From vertx-mqtt-broker with Apache License 2.0 6 votes vote down vote up
public RecordParser initialHandhakeProtocolParser() {
    NetSocket sock = netSocket;
    final RecordParser parser = RecordParser.newDelimited("\n", h -> {
        String cmd = h.toString();
        if("START SESSION".equalsIgnoreCase(cmd)) {
            sock.pause();
            start();
            logger.info("Bridge Server - start session with " +
                    "tenant: " + getTenant() +
                    ", ip: " + sock.remoteAddress() +
                    ", bridgeUUID: " + getBridgeUUID()
            );
            sock.resume();
        } else {
            String tenant = cmd;
            String tenantFromCert = new CertInfo(sock).getTenant();
            if(tenantFromCert != null)
                tenant = tenantFromCert;

            setTenant(tenant);
        }
    });
    return parser;
}
 
Example #15
Source File: ServerConnectionTest.java    From vertx-stomp with Apache License 2.0 6 votes vote down vote up
@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);
  });
}
 
Example #16
Source File: TcpEventBusBridgeInteropTest.java    From vertx-tcp-eventbus-bridge with Apache License 2.0 6 votes vote down vote up
@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);
  });
}
 
Example #17
Source File: ServerConnectionTest.java    From vertx-stomp with Apache License 2.0 6 votes vote down vote up
@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");
}
 
Example #18
Source File: ServerConnectionTest.java    From vertx-stomp with Apache License 2.0 6 votes vote down vote up
@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);
  });
}
 
Example #19
Source File: ProtocolGateway.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Subscribes to commands for a device.
 *
 * @param deviceId The device to subscribe for.
 * @param socket The socket to use for sending commands to the device.
 * @return A future indicating the outcome.
 */
private Future<?> subscribe(final String deviceId, final NetSocket socket) {

    final Consumer<Message> messageHandler = m -> {

        final String commandPayload = MessageHelper.getPayloadAsString(m);
        final boolean isOneWay = m.getReplyTo() == null;
        if (isOneWay) {
            LOG.debug("received one-way command [name: {}]: {}", m.getSubject(), commandPayload);
            socket.write(String.format("ONE-WAY COMMAND [name: %s]: %s\n", m.getSubject(), commandPayload));
        } else {
            LOG.debug("received command [name: {}]: {}", m.getSubject(), commandPayload);
            if ("tellTime".equals(m.getSubject())) {
                respondWithTime(m).onComplete(sendAttempt -> {
                    if (sendAttempt.succeeded()) {
                        LOG.debug("sent response to command [name: {}, outcome: {}]", m.getSubject(), sendAttempt.result().getRemoteState().getType());
                    } else {
                        LOG.info("failed to send response to command [name: {}]", m.getSubject(), sendAttempt.cause());
                    }
                });
            }
        }
    };
    return amqpAdapterClientFactory.createDeviceSpecificCommandConsumer(deviceId, messageHandler);
}
 
Example #20
Source File: ServerConnectionTest.java    From vertx-stomp with Apache License 2.0 6 votes vote down vote up
@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);
  });
}
 
Example #21
Source File: ProtocolGateway.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
private Future<Void> sendEvent(final String args, final NetSocket socket, final Map<String, Object> dictionary) {

        final Promise<Void> result = Promise.promise();
        LOG.debug("Command: send Event");
        Optional.ofNullable(dictionary.get(KEY_DEVICE_ID))
            .ifPresentOrElse(
                    obj -> {
                        final String deviceId = (String) obj;
                        if (Strings.isNullOrEmpty(args)) {
                            result.fail("missing payload");
                        } else {
                            final byte[] payload = Buffer.buffer(args).getBytes();
                            amqpAdapterClientFactory.getOrCreateEventSender()
                                .compose(sender -> sender.send(deviceId, payload, CONTENT_TYPE_BINARY_OPAQUE, null))
                                .map((Void) null)
                                .onComplete(result);
                        }
                    },
                    () -> {
                        result.fail("device not logged in");
                    });
        return result.future();
    }
 
Example #22
Source File: ProtocolGateway.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
private Future<Void> executeCommand(final String[] command, final NetSocket socket, final Map<String, Object> dictionary) {

        final String commandName = command[0];
        final String args = command.length > 1 ? command[1] : null;

        LOG.debug("processing command: {}", commandName);
        switch (commandName) {
        case CMD_LOGIN:
            return login(args, socket, dictionary);
        case TelemetryConstants.TELEMETRY_ENDPOINT:
        case TelemetryConstants.TELEMETRY_ENDPOINT_SHORT:
            return sendTelemetry(args, socket, dictionary);
        case EventConstants.EVENT_ENDPOINT:
        case EventConstants.EVENT_ENDPOINT_SHORT:
            return sendEvent(args, socket, dictionary);
        case CMD_SUBSCRIBE:
            return subscribe(socket, dictionary);
        case CMD_UNSUBSCRIBE:
            return unsubscribe(socket, dictionary);
        default:
            LOG.debug("unsupported command [{}]", commandName);
            return Future.failedFuture("no such command");
        }
    }
 
Example #23
Source File: ProcessModuleHandle.java    From okapi with Apache License 2.0 6 votes vote down vote up
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(
              messages.getMessage("11503", Integer.toString(port))));
        }
      } else {
        stopFuture.handle(Future.succeededFuture());
      }
    });
  } else {
    stopFuture.handle(Future.succeededFuture());
  }
}
 
Example #24
Source File: ProcessModuleHandle.java    From okapi with Apache License 2.0 6 votes vote down vote up
@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(
            messages.getMessage("11502", Integer.toString(port))));
      } else {
        start2(startFuture);
      }
    });
  } else {
    start2(startFuture);
  }
}
 
Example #25
Source File: MSSQLConnectionFactory.java    From vertx-sql-client with Apache License 2.0 6 votes vote down vote up
public void doConnect(Promise<Connection> promise) {
  Future<NetSocket> fut = netClient.connect(port, host);
  fut.onComplete(ar -> {
    if (ar.succeeded()) {
      NetSocket so = ar.result();
      MSSQLSocketConnection conn = new MSSQLSocketConnection((NetSocketInternal) so, false, 0, sql -> true, 1, context);
      conn.init();
      conn.sendPreLoginMessage(false, preLogin -> {
        if (preLogin.succeeded()) {
          conn.sendLoginMessage(username, password, database, properties, promise);
        } else {
          promise.fail(preLogin.cause());
        }
      });
    } else {
      promise.fail(ar.cause());
    }
  });
}
 
Example #26
Source File: RedisConnectionImpl.java    From vertx-redis-client with Apache License 2.0 5 votes vote down vote up
public RedisConnectionImpl(Vertx vertx, ContextInternal context, ConnectionListener<RedisConnection> connectionListener, NetSocket netSocket, RedisOptions options) {
  this.listener = connectionListener;
  this.eventBus = vertx.eventBus();
  this.context = context;
  this.netSocket = netSocket;
  this.waiting = new ArrayQueue(options.getMaxWaitingHandlers());
  this.recycleTimeout = options.getPoolRecycleTimeout();
}
 
Example #27
Source File: ProtonSaslServerAuthenticatorImpl.java    From vertx-proton with Apache License 2.0 5 votes vote down vote up
@Override
public void init(NetSocket socket, ProtonConnection protonConnection, Transport transport) {
  this.sasl = transport.sasl();
  sasl.server();
  sasl.allowSkip(false);
  sasl.setMechanisms(ProtonSaslAnonymousImpl.MECH_NAME);
  succeeded = false;
}
 
Example #28
Source File: SocketClient.java    From enode with MIT License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    NetClient client = Vertx.vertx().createNetClient();
    String host = "127.0.0.1";
    long start = System.currentTimeMillis();
    int total = 1000000;
    CompletableFuture<NetSocket> future = new CompletableFuture<>();
    if (smap.putIfAbsent(host, future) == null) {
        client.connect(6008, host, socketAsyncResult -> {
            if (socketAsyncResult.succeeded()) {
                NetSocket socket = socketAsyncResult.result();
                socket.closeHandler(x -> {
                    smap.remove(host);
                }).endHandler(x -> {
                    smap.remove(host);
                    logger.info("end:{}", x);
                });
                future.complete(socket);
            }
        });
    }
    smap.get(host).thenAccept(socket -> {
        for (int i = 0; i < total; i++) {
            socket.write("send message:" + i + SysProperties.DELIMITED);
        }
    });

    long end = System.currentTimeMillis();
    logger.info("time:{}", end - start);
    System.in.read();
}
 
Example #29
Source File: ProtocolGateway.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
private Future<Void> login(final String args, final NetSocket socket, final Map<String, Object> dictionary) {
    if (Strings.isNullOrEmpty(args)) {
        return Future.failedFuture("missing device identifier");
    } else {
        final String deviceId = args;
        LOG.info("authenticating device [id: {}]", deviceId);
        dictionary.put(KEY_DEVICE_ID, deviceId);
        socket.write(String.format("device [%s] logged in\n", deviceId));
        return Future.succeededFuture();
    }
}
 
Example #30
Source File: ProtocolGateway.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
private Future<Void> sendTelemetry(final String args, final NetSocket socket, final Map<String, Object> dictionary) {

        final Promise<Void> result = Promise.promise();
        LOG.debug("Command: send Telemetry");
        Optional.ofNullable(dictionary.get(KEY_DEVICE_ID))
            .ifPresentOrElse(
                    obj -> {
                        final String deviceId = (String) obj;
                        if (Strings.isNullOrEmpty(args)) {
                            result.fail("missing params qos and payload");
                        } else {
                            final String[] params = args.split(" ", 2);
                            final String qos = params[0];
                            final byte[] payload = Optional.ofNullable(params[1]).map(p -> Buffer.buffer(p).getBytes()).orElse(null);
                            amqpAdapterClientFactory.getOrCreateTelemetrySender()
                                .compose(sender -> {
                                    if ("0".equals(qos)) {
                                        return sender.send(deviceId, payload, CONTENT_TYPE_BINARY_OPAQUE, null);
                                    } else {
                                        return sender.sendAndWaitForOutcome(deviceId, payload, CONTENT_TYPE_BINARY_OPAQUE, null);
                                    }
                                })
                                .map((Void) null)
                                .onComplete(result);
                        }
                    },
                    () -> {
                        result.fail("device not logged in");
                    });
        return result.future();
    }