io.vertx.core.parsetools.RecordParser Java Examples

The following examples show how to use io.vertx.core.parsetools.RecordParser. 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: 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 #2
Source File: ProtocolGateway.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
void handleConnect(final NetSocket socket) {

        final Map<String, Object> dict = new HashMap<>();
        final RecordParser commandParser = RecordParser.newDelimited("\n", socket);
        commandParser.endHandler(end -> socket.close());
        commandParser.exceptionHandler(t -> {
            LOG.debug("error processing data from device", t);
            socket.close();
        });
        commandParser.handler(data -> handleData(socket, dict, data));
        socket.closeHandler(remoteClose -> {
            LOG.debug("device closed connection");
            Optional.ofNullable((CommandConsumer) dict.get(KEY_COMMAND_CONSUMER))
                .ifPresent(c -> {
                    c.close(res -> {
                        LOG.debug("closed device's command consumer");
                    });
                });
            socket.close();
        });

        socket.write(String.format("Welcome to the Protocol Gateway for devices of tenant [%s], please enter a command\n", tenant));
        LOG.debug("connection with client established");
    }
 
Example #3
Source File: PrometheusTestHelper.java    From vertx-micrometer-metrics with Apache License 2.0 6 votes vote down vote up
public static Set<String> getMetricNames(Vertx vertx,
                                         TestContext context,
                                         int port,
                                         String host,
                                         String requestURI,
                                         long timeout,
                                         int maxAttempts,
                                         long sleepBeforeRetryMs) {
  Async async = context.async();
  Set<String> metrics = Collections.synchronizedSet(new HashSet<>());
  tryConnect(vertx, context, port, host, requestURI, resp -> {
    context.assertEquals(200, resp.statusCode());
    RecordParser parser = RecordParser.newDelimited("\n", resp);
    parser.exceptionHandler(context::fail).endHandler(v -> {
      async.countDown();
    }).handler(buffer -> {
      String line = buffer.toString();
      if (line.startsWith("# TYPE")) {
        metrics.add(line.split(" ")[2]);
      }
    });
  }, maxAttempts, sleepBeforeRetryMs, 0);
  async.await(timeout);
  return metrics;
}
 
Example #4
Source File: PipePayloadParser.java    From jetlinks-community with Apache License 2.0 5 votes vote down vote up
public PipePayloadParser fixed(int size) {
    if (recordParser == null) {
        setParser(RecordParser.newFixed(size));
        firstInit = (parser -> parser.fixedSizeMode(size));
        return this;
    }
    recordParser.fixedSizeMode(size);
    return this;
}
 
Example #5
Source File: EventBusWebsocketBridge.java    From vertx-mqtt-broker with Apache License 2.0 5 votes vote down vote up
public RecordParser initialHandhakeProtocolParser() {
    if(!(webSocket instanceof ServerWebSocket)) {
        throw new IllegalStateException("This must be a server! websocket instance is of type '"+webSocket.getClass().getSimpleName()+"'");
    }
    ServerWebSocket sock = (ServerWebSocket)webSocket;
    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 #6
Source File: SocketServer.java    From enode with MIT License 5 votes vote down vote up
public static void main(String[] args) throws IOException {
    Vertx.vertx().createNetServer().connectHandler(s -> {
        RecordParser parser = RecordParser.newDelimited(SysProperties.DELIMITED, s);
        parser.handler(b -> logger.info("receive.:{}", b.toString()));
    }).listen(6008);
    System.in.read();
}
 
Example #7
Source File: DefaultCommandResultProcessor.java    From enode with MIT License 5 votes vote down vote up
public void startServer(int port, int completionSourceTimeout) {
    netServer = vertx.createNetServer();
    netServer.connectHandler(sock -> {
        RecordParser parser = RecordParser.newDelimited(SysProperties.DELIMITED, sock);
        parser.endHandler(v -> sock.close()).exceptionHandler(t -> {
            logger.error("Failed to start NetServer", t);
            sock.close();
        }).handler(buffer -> {
            RemoteReply name = buffer.toJsonObject().mapTo(RemoteReply.class);
            processRequestInternal(name);
        });
    });
    bindAddress = new InetSocketAddress(port);
    netServer.listen(port);
    commandTaskDict = CacheBuilder.newBuilder().removalListener((RemovalListener<String, CommandTaskCompletionSource>) notification -> {
        if (notification.getCause().equals(RemovalCause.EXPIRED)) {
            processTimeoutCommand(notification.getKey(), notification.getValue());
        }
    }).expireAfterWrite(completionSourceTimeout, TimeUnit.MILLISECONDS).build();
    commandExecutedMessageLocalQueue = new LinkedBlockingQueue<>();
    domainEventHandledMessageLocalQueue = new LinkedBlockingQueue<>();
    commandExecutedMessageWorker = new Worker("ProcessExecutedCommandMessage", () -> {
        processExecutedCommandMessage(commandExecutedMessageLocalQueue.take());
    });
    domainEventHandledMessageWorker = new Worker("ProcessDomainEventHandledMessage", () -> {
        processDomainEventHandledMessage(domainEventHandledMessageLocalQueue.take());
    });
}
 
Example #8
Source File: DatabaseReader.java    From vertx-in-action with MIT License 5 votes vote down vote up
public static void main(String[] args) {
  Vertx vertx = Vertx.vertx();

  AsyncFile file = vertx.fileSystem().openBlocking("sample.db",
    new OpenOptions().setRead(true));

  RecordParser parser = RecordParser.newFixed(4, file);
  parser.handler(header -> readMagicNumber(header, parser));
  parser.endHandler(v -> vertx.close());
}
 
Example #9
Source File: GeneratorTest.java    From vertx-starter with Apache License 2.0 5 votes vote down vote up
private void runDevMode(Vertx vertx, BuildTool buildTool, Handler<AsyncResult<Void>> handler) {
  ProcessOptions processOptions = new ProcessOptions().setCwd(workdir.toString());
  String command;
  List<String> args;
  if (buildTool == MAVEN) {
    command = "./mvnw";
    args = Arrays.asList("clean", "compile", "exec:java");
  } else if (buildTool == GRADLE) {
    command = "./gradlew";
    args = Arrays.asList("clean", "run");
  } else {
    handler.handle(Future.failedFuture(unsupported(buildTool)));
    return;
  }
  Process process = Process.create(vertx, command, args, processOptions);
  cleanupTasks.add(() -> process.kill(true));
  Promise<Void> promise = Promise.promise();
  promise.future().onComplete(handler);
  RecordParser parser = RecordParser.newDelimited("\n")
    .exceptionHandler(promise::tryFail)
    .handler(buffer -> {
      String line = buffer.toString().trim();
      if (line.contains("HTTP server started on port 8888")) {
        promise.tryComplete();
      }
    });
  process.stdout().exceptionHandler(promise::tryFail).handler(parser);
  process.start();
}
 
Example #10
Source File: TcpParser.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
/**
 * 在解析出错时,通过重新创建parser对象,将整个缓冲区重置
 */
protected void reset() {
  parser = RecordParser.newFixed(TCP_HEADER_LENGTH, this::onParse);
  status = ParseStatus.TCP_HEADER;

  parser.handle(Buffer.buffer(0));
}
 
Example #11
Source File: FetchDatabaseReader.java    From vertx-in-action with MIT License 5 votes vote down vote up
private static void finishEntry(String key, Buffer valueLength, RecordParser parser) {
  parser.fixedSizeMode(valueLength.getInt(0));
  parser.handler(value -> {
    logger.info("Key: {} / Value: {}", key, value);
    parser.fixedSizeMode(4);
    parser.handler(keyLength -> readKey(keyLength, parser));
    parser.fetch(1);
  });
  parser.fetch(1);
}
 
Example #12
Source File: DatabaseReader.java    From vertx-in-action with MIT License 5 votes vote down vote up
private static void finishEntry(String key, Buffer valueLength, RecordParser parser) {
  parser.fixedSizeMode(valueLength.getInt(0));
  parser.handler(value -> {
    logger.info("Key: {} / Value: {}", key, value);
    parser.fixedSizeMode(4);
    parser.handler(keyLength -> readKey(keyLength, parser));
  });
}
 
Example #13
Source File: FetchDatabaseReader.java    From vertx-in-action with MIT License 5 votes vote down vote up
public static void main(String[] args) {
  Vertx vertx = Vertx.vertx();

  AsyncFile file = vertx.fileSystem().openBlocking("sample.db",
    new OpenOptions().setRead(true));

  RecordParser parser = RecordParser.newFixed(4, file);
  parser.pause();
  parser.fetch(1);
  parser.handler(header -> readMagicNumber(header, parser));
  parser.endHandler(v -> vertx.close());
}
 
Example #14
Source File: FetchDatabaseReader.java    From vertx-in-action with MIT License 4 votes vote down vote up
private static void readKey(Buffer keyLength, RecordParser parser) {
  parser.fixedSizeMode(keyLength.getInt(0));
  parser.handler(key -> readValue(key.toString(), parser));
  parser.fetch(1);
}
 
Example #15
Source File: EventBusBridgeWebsocketServerVerticle.java    From vertx-mqtt-broker with Apache License 2.0 4 votes vote down vote up
@Override
public void start() throws Exception {
    address = MQTTSession.ADDRESS;

    JsonObject conf = config();

    localBridgePort = conf.getInteger("local_bridge_port", 7007);
    idleTimeout = conf.getInteger("socket_idle_timeout", 120);
    ssl_cert_key = conf.getString("ssl_cert_key");
    ssl_cert = conf.getString("ssl_cert");
    ssl_trust = conf.getString("ssl_trust");


    // [WebSocket -> BUS] listen WebSocket publish to BUS
    HttpServerOptions opt = new HttpServerOptions()
            .setTcpKeepAlive(true)
            .setIdleTimeout(idleTimeout)
            .setPort(localBridgePort)
    ;

    if(ssl_cert_key != null && ssl_cert != null && ssl_trust != null) {
        opt.setSsl(true).setClientAuth(ClientAuth.REQUIRED)
            .setPemKeyCertOptions(new PemKeyCertOptions()
                .setKeyPath(ssl_cert_key)
                .setCertPath(ssl_cert)
            )
            .setPemTrustOptions(new PemTrustOptions()
                .addCertPath(ssl_trust)
            )
        ;
    }

    netServer = vertx.createHttpServer(opt);
    netServer.requestHandler(httpServerRequest -> httpServerRequest.response().end() );
    netServer.websocketHandler(sock -> {
        final EventBusWebsocketBridge ebnb = new EventBusWebsocketBridge(sock, vertx.eventBus(), address);
        sock.closeHandler(aVoid -> {
            logger.info("Bridge Server - closed connection from client ip: " + sock.remoteAddress());
            ebnb.stop();
        });
        sock.exceptionHandler(throwable -> {
            logger.error("Bridge Server - Exception: " + throwable.getMessage(), throwable);
            ebnb.stop();
        });

        logger.info("Bridge Server - new connection from client ip: " + sock.remoteAddress());

        RecordParser parser = ebnb.initialHandhakeProtocolParser();
        sock.handler(parser::handle);

    }).listen();
}
 
Example #16
Source File: FetchDatabaseReader.java    From vertx-in-action with MIT License 4 votes vote down vote up
private static void readValue(String key, RecordParser parser) {
  parser.fixedSizeMode(4);
  parser.handler(valueLength -> finishEntry(key, valueLength, parser));
  parser.fetch(1);
}
 
Example #17
Source File: NetControl.java    From vertx-in-action with MIT License 4 votes vote down vote up
private void handleClient(NetSocket socket) {
  logger.info("New connection");
  RecordParser.newDelimited("\n", socket)
    .handler(buffer -> handleBuffer(socket, buffer))
    .endHandler(v -> logger.info("Connection ended"));
}
 
Example #18
Source File: EventBusBridgeServerVerticle.java    From vertx-mqtt-broker with Apache License 2.0 4 votes vote down vote up
@Override
public void start() throws Exception {
    address = MQTTSession.ADDRESS;

    JsonObject conf = config();

    localBridgePort = conf.getInteger("local_bridge_port", 7007);
    idleTimeout = conf.getInteger("socket_idle_timeout", 120);
    ssl_cert_key = conf.getString("ssl_cert_key");
    ssl_cert = conf.getString("ssl_cert");
    ssl_trust = conf.getString("ssl_trust");


    // [TCP -> BUS] listen TCP publish to BUS
    NetServerOptions opt = new NetServerOptions()
            .setTcpKeepAlive(true)
            .setIdleTimeout(idleTimeout)
            .setPort(localBridgePort)
    ;

    if(ssl_cert_key != null && ssl_cert != null && ssl_trust != null) {
        opt.setSsl(true).setClientAuth(ClientAuth.REQUIRED)
            .setPemKeyCertOptions(new PemKeyCertOptions()
                .setKeyPath(ssl_cert_key)
                .setCertPath(ssl_cert)
            )
            .setPemTrustOptions(new PemTrustOptions()
                .addCertPath(ssl_trust)
            )
        ;
    }

    netServer = vertx.createNetServer(opt);
    netServer.connectHandler(sock -> {
        final EventBusNetBridge ebnb = new EventBusNetBridge(sock, vertx.eventBus(), address);
        sock.closeHandler(aVoid -> {
            logger.info("Bridge Server - closed connection from client ip: " + sock.remoteAddress());
            ebnb.stop();
        });
        sock.exceptionHandler(throwable -> {
            logger.error("Bridge Server - Exception: " + throwable.getMessage(), throwable);
            ebnb.stop();
        });

        logger.info("Bridge Server - new connection from client ip: " + sock.remoteAddress());

        RecordParser parser = ebnb.initialHandhakeProtocolParser();
        sock.handler(parser::handle);

    }).listen();
}
 
Example #19
Source File: FetchDatabaseReader.java    From vertx-in-action with MIT License 4 votes vote down vote up
private static void readName(Buffer name, RecordParser parser) {
  logger.info("Name: {}", name.toString());
  parser.fixedSizeMode(4);
  parser.handler(keyLength -> readKey(keyLength, parser));
  parser.fetch(1);
}
 
Example #20
Source File: FetchDatabaseReader.java    From vertx-in-action with MIT License 4 votes vote down vote up
private static void readVersion(Buffer header, RecordParser parser) {
  logger.info("Version: {}", header.getInt(0));
  parser.delimitedMode("\n");
  parser.handler(name -> readName(name, parser));
  parser.fetch(1);
}
 
Example #21
Source File: FetchDatabaseReader.java    From vertx-in-action with MIT License 4 votes vote down vote up
private static void readMagicNumber(Buffer header, RecordParser parser) {
  logger.info("Magic number: {}:{}:{}:{}", header.getByte(0), header.getByte(1), header.getByte(2), header.getByte(3));
  parser.handler(version -> readVersion(version, parser));
  parser.fetch(1);
}
 
Example #22
Source File: DatabaseReader.java    From vertx-in-action with MIT License 4 votes vote down vote up
private static void readValue(String key, RecordParser parser) {
  parser.fixedSizeMode(4);
  parser.handler(valueLength -> finishEntry(key, valueLength, parser));
}
 
Example #23
Source File: DatabaseReader.java    From vertx-in-action with MIT License 4 votes vote down vote up
private static void readKey(Buffer keyLength, RecordParser parser) {
  parser.fixedSizeMode(keyLength.getInt(0));
  parser.handler(key -> readValue(key.toString(), parser));
}
 
Example #24
Source File: DatabaseReader.java    From vertx-in-action with MIT License 4 votes vote down vote up
private static void readName(Buffer name, RecordParser parser) {
  logger.info("Name: {}", name.toString());
  parser.fixedSizeMode(4);
  parser.handler(keyLength -> readKey(keyLength, parser));
}
 
Example #25
Source File: DatabaseReader.java    From vertx-in-action with MIT License 4 votes vote down vote up
private static void readVersion(Buffer header, RecordParser parser) {
  logger.info("Version: {}", header.getInt(0));
  parser.delimitedMode("\n");
  parser.handler(name -> readName(name, parser));
}
 
Example #26
Source File: DatabaseReader.java    From vertx-in-action with MIT License 4 votes vote down vote up
private static void readMagicNumber(Buffer header, RecordParser parser) {
  logger.info("Magic number: {}:{}:{}:{}", header.getByte(0), header.getByte(1), header.getByte(2), header.getByte(3));
  parser.handler(version -> readVersion(version, parser));
}
 
Example #27
Source File: FixLengthPayloadParserBuilder.java    From jetlinks-community with Apache License 2.0 4 votes vote down vote up
@Override
protected RecordParser createParser(ValueObject config) {
    return RecordParser.newFixed(config.getInt("size")
            .orElseThrow(() -> new IllegalArgumentException("size can not be null")));
}
 
Example #28
Source File: PipePayloadParser.java    From jetlinks-community with Apache License 2.0 4 votes vote down vote up
private void setParser(RecordParser parser) {
    this.recordParser = parser;
    this.recordParser.handler(buffer -> getNextHandler().accept(buffer));
}
 
Example #29
Source File: DelimitedPayloadParserBuilder.java    From jetlinks-community with Apache License 2.0 4 votes vote down vote up
@Override
protected RecordParser createParser(ValueObject config) {

    return RecordParser.newDelimited(StringEscapeUtils.unescapeJava(config.getString("delimited")
            .orElseThrow(() -> new IllegalArgumentException("delimited can not be null"))));
}
 
Example #30
Source File: VertxPayloadParserBuilder.java    From jetlinks-community with Apache License 2.0 4 votes vote down vote up
public RecordPayloadParser(RecordParser recordParser) {
    this.recordParser = recordParser;
    this.recordParser.handler(buffer -> {
        processor.onNext(buffer);
    });
}