Пример #1
0
 private void testWriteMessage(int size, WebsocketVersion version) {
   String path = "/some/path";
   byte[] expected = TestUtils.randomByteArray(size);
   server =
       vertx
           .createHttpServer(new HttpServerOptions().setPort(HttpTestBase.DEFAULT_HTTP_PORT))
           .websocketHandler(
               ws -> {
                 ws.writeMessage(Buffer.buffer(expected));
                 ws.close();
               });
   server.listen(
       ar -> {
         assertTrue(ar.succeeded());
         client.connectWebsocket(
             HttpTestBase.DEFAULT_HTTP_PORT,
             HttpTestBase.DEFAULT_HTTP_HOST,
             path,
             null,
             version,
             ws -> {
               Buffer actual = Buffer.buffer();
               ws.handler(actual::appendBuffer);
               ws.closeHandler(
                   v -> {
                     assertArrayEquals(expected, actual.getBytes());
                     testComplete();
                   });
             });
       });
   await();
 }
Пример #2
0
  private void testContinuationWriteFromConnectHandler(WebsocketVersion version) throws Exception {
    String path = "/some/path";
    String firstFrame = "AAA";
    String continuationFrame = "BBB";

    server =
        vertx
            .createHttpServer(new HttpServerOptions().setPort(HttpTestBase.DEFAULT_HTTP_PORT))
            .requestHandler(
                req -> {
                  NetSocket sock = getUpgradedNetSocket(req, path);

                  // Let's write a Text frame raw
                  Buffer buff = Buffer.buffer();
                  buff.appendByte((byte) 0x01); // Incomplete Text frame
                  buff.appendByte((byte) firstFrame.length());
                  buff.appendString(firstFrame);
                  sock.write(buff);

                  buff = Buffer.buffer();
                  buff.appendByte((byte) (0x00 | 0x80)); // Complete continuation frame
                  buff.appendByte((byte) continuationFrame.length());
                  buff.appendString(continuationFrame);
                  sock.write(buff);
                });

    server.listen(
        ar -> {
          assertTrue(ar.succeeded());
          client.connectWebsocket(
              HttpTestBase.DEFAULT_HTTP_PORT,
              HttpTestBase.DEFAULT_HTTP_HOST,
              path,
              null,
              version,
              ws -> {
                AtomicBoolean receivedFirstFrame = new AtomicBoolean();
                ws.frameHandler(
                    received -> {
                      Buffer receivedBuffer = Buffer.buffer(received.textData());
                      if (!received.isFinal()) {
                        assertEquals(firstFrame, receivedBuffer.toString());
                        receivedFirstFrame.set(true);
                      } else if (receivedFirstFrame.get() && received.isFinal()) {
                        assertEquals(continuationFrame, receivedBuffer.toString());
                        ws.close();
                        testComplete();
                      }
                    });
              });
        });
    await();
  }
Пример #3
0
  private void testWSWriteStream(WebsocketVersion version) throws Exception {

    String path = "/some/path";
    String query = "foo=bar&wibble=eek";
    String uri = path + "?" + query;

    server =
        vertx
            .createHttpServer(new HttpServerOptions().setPort(HttpTestBase.DEFAULT_HTTP_PORT))
            .websocketHandler(
                ws -> {
                  assertEquals(uri, ws.uri());
                  assertEquals(path, ws.path());
                  assertEquals(query, ws.query());
                  assertEquals("Upgrade", ws.headers().get("Connection"));
                  ws.handler(data -> ws.write(data));
                });

    server.listen(
        ar -> {
          assertTrue(ar.succeeded());
          int bsize = 100;
          int sends = 10;

          client.connectWebsocket(
              HttpTestBase.DEFAULT_HTTP_PORT,
              HttpTestBase.DEFAULT_HTTP_HOST,
              path + "?" + query,
              null,
              version,
              ws -> {
                final Buffer received = Buffer.buffer();
                ws.handler(
                    data -> {
                      received.appendBuffer(data);
                      if (received.length() == bsize * sends) {
                        ws.close();
                        testComplete();
                      }
                    });
                final Buffer sent = Buffer.buffer();
                for (int i = 0; i < sends; i++) {
                  Buffer buff = Buffer.buffer(TestUtils.randomByteArray(bsize));
                  ws.write(buff);
                  sent.appendBuffer(buff);
                }
              });
        });
    await();
  }
  @Test
  public void writeTwoDifferentMessages() throws Exception {
    byte[] bytes = {0x1, 0x3, 0x5, 0x7};
    String strContent = "foo";

    _wsStream.write(Buffer.buffer(bytes));
    _wsStream.finishCurrentMessage();

    _wsStream.setDataFormat(DataFormat.Text);
    _wsStream.write(Buffer.buffer(strContent.getBytes(StandardCharsets.UTF_8)));
    _wsStream.finishCurrentMessage();

    verify(_socket).writeFrame(binaryFrameEq(true, bytes));
    verify(_socket).writeFrame(textFrameEq(true, strContent));
  }
Пример #5
0
 public Buffer encodeToWire() {
   int length = 1024; // TODO make this configurable
   Buffer buffer = Buffer.buffer(length);
   buffer.appendInt(0);
   buffer.appendByte(WIRE_PROTOCOL_VERSION);
   byte systemCodecID = messageCodec.systemCodecID();
   buffer.appendByte(systemCodecID);
   if (systemCodecID == -1) {
     // User codec
     writeString(buffer, messageCodec.name());
   }
   buffer.appendByte(send ? (byte) 0 : (byte) 1);
   writeString(buffer, address);
   if (replyAddress != null) {
     writeString(buffer, replyAddress);
   } else {
     buffer.appendInt(0);
   }
   buffer.appendInt(sender.port);
   writeString(buffer, sender.host);
   encodeHeaders(buffer);
   writeBody(buffer);
   buffer.setInt(0, buffer.length() - 4);
   return buffer;
 }
 @Override
 public void encodeToWire(Buffer buffer, String entries) {
   byte[] encoded = entries.getBytes(CharsetUtil.UTF_8);
   buffer.appendInt(encoded.length);
   Buffer buff = Buffer.buffer(encoded);
   buffer.appendBuffer(buff);
 }
Пример #7
0
 private Buffer getAnalogValueCallbackThresholdDefault() {
   Buffer buffer = Buffer.buffer();
   buffer.appendBytes(Utils.getCharRandomValue(1));
   buffer.appendBytes(Utils.get2ByteURandomValue(1));
   buffer.appendBytes(Utils.get2ByteURandomValue(1));
   return buffer;
 }
Пример #8
0
 @Override
 public void end(String chunk, String enc) {
   synchronized (getLock()) {
     Objects.requireNonNull(enc, "no null encoding accepted");
     end(Buffer.buffer(chunk, enc));
   }
 }
  @Override
  public void render(
      RoutingContext context, String templateFileName, Handler<AsyncResult<Buffer>> handler) {
    try {
      Template template = cache.get(templateFileName);
      if (template == null) {
        // real compile
        synchronized (this) {
          loader.setVertx(context.vertx());
          // Compile
          template = config.getTemplate(adjustLocation(templateFileName));
        }
        cache.put(templateFileName, template);
      }

      Map<String, RoutingContext> variables = new HashMap<>(1);
      variables.put("context", context);

      try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
        template.process(variables, new OutputStreamWriter(baos));
        handler.handle(Future.succeededFuture(Buffer.buffer(baos.toByteArray())));
      }

    } catch (Exception ex) {
      handler.handle(Future.failedFuture(ex));
    }
  }
  @Test
  public void writeOneByteAndClose() throws Exception {
    byte b = 0x13; // arbitrary byte
    _wsStream.write(Buffer.buffer(new byte[] {b}));
    _wsStream.finishCurrentMessage(); // should flush and send websocket frame

    verify(_socket).writeFrame(binaryFrameEq(true, new byte[] {b}));
  }
Пример #11
0
 @Override
 public HttpClientRequestImpl write(String chunk) {
   synchronized (getLock()) {
     checkComplete();
     checkResponseHandler();
     return write(Buffer.buffer(chunk));
   }
 }
  @Test
  public void writeMultipleBytesAndClose() throws Exception {
    byte[] bytes = {0x1, 0x3, 0x5, 0x7};
    _wsStream.write(Buffer.buffer(bytes));
    _wsStream.finishCurrentMessage();

    verify(_socket).writeFrame(binaryFrameEq(true, bytes));
  }
Пример #13
0
 @Override
 public Buffer writeToBuffer() {
   String encoded = encode();
   byte[] bytes = encoded.getBytes();
   Buffer buffer = Buffer.buffer(bytes.length + 4);
   buffer.appendInt(bytes.length);
   buffer.appendBytes(bytes);
   return buffer;
 }
Пример #14
0
 @Override
 public HttpClientRequestImpl write(String chunk, String enc) {
   synchronized (getLock()) {
     Objects.requireNonNull(enc, "no null encoding accepted");
     checkComplete();
     checkResponseHandler();
     return write(Buffer.buffer(chunk, enc));
   }
 }
  private void writeToTarget(String sendPacket, String cmd) {
    logger.debug(name_log + "writeToDCU(), Command: " + cmd);

    // Writing Data to The Socket
    Buffer outBuffer = Buffer.buffer();
    outBuffer.setString(0, sendPacket);
    logger.info(name_log + "SEND[" + outBuffer.length() + "]> \n" + outBuffer.toString() + "\n");

    netSocket.write(outBuffer);
  }
  @Test
  public void writeUnicodeFrameAndClose() throws Exception {
    String unicodeStr = "\u0628\u00de";

    _wsStream.setDataFormat(DataFormat.Text);
    _wsStream.write(Buffer.buffer(unicodeStr.getBytes(StandardCharsets.UTF_8)));
    _wsStream.finishCurrentMessage();

    verify(_socket).writeFrame(textFrameEq(true, unicodeStr));
  }
  @Test
  public void streamAutoFlushesFrames() throws Exception {
    byte[] bytes = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};

    _wsStream.write(Buffer.buffer(bytes));

    verify(_socket).writeFrame(binaryFrameEq(false, Arrays.copyOfRange(bytes, 0, 5)));
    verify(_socket).writeFrame(continuationFrameEq(false, Arrays.copyOfRange(bytes, 5, 10)));

    _wsStream.finishCurrentMessage();
    verify(_socket).writeFrame(continuationFrameEq(true, Arrays.copyOfRange(bytes, 10, 11)));
  }
Пример #18
0
 @Override
 public synchronized NetSocket resume() {
   if (paused) {
     paused = false;
     if (pendingData != null) {
       // Send empty buffer to trigger sending of pending data
       context.runOnContext(v -> handleDataReceived(Buffer.buffer()));
     }
     doResume();
   }
   return this;
 }
 @Override
 public void onToken(byte[] token, boolean timeout) throws Exception {
   try {
     Buffer buffer = Buffer.buffer(token);
     AbstractMessage message = decoder.dec(buffer);
     onMessageFromClient(message);
   } catch (Throwable ex) {
     String clientInfo = getClientInfo();
     Container.logger().error(clientInfo + ", Bad error in processing the message", ex);
     closeConnection();
   }
 }
Пример #20
0
 private void testValidSubProtocol(WebsocketVersion version) throws Exception {
   String path = "/some/path";
   String subProtocol = "myprotocol";
   Buffer buff = Buffer.buffer("AAA");
   server =
       vertx
           .createHttpServer(
               new HttpServerOptions()
                   .setPort(HttpTestBase.DEFAULT_HTTP_PORT)
                   .setWebsocketSubProtocol(subProtocol))
           .websocketHandler(
               ws -> {
                 assertEquals(path, ws.path());
                 ws.writeFrame(WebSocketFrame.binaryFrame(buff, true));
               });
   server.listen(
       ar -> {
         assertTrue(ar.succeeded());
         client.connectWebsocket(
             HttpTestBase.DEFAULT_HTTP_PORT,
             HttpTestBase.DEFAULT_HTTP_HOST,
             path,
             null,
             version,
             subProtocol,
             ws -> {
               final Buffer received = Buffer.buffer();
               ws.handler(
                   data -> {
                     received.appendBuffer(data);
                     if (received.length() == buff.length()) {
                       assertEquals(buff, received);
                       ws.close();
                       testComplete();
                     }
                   });
             });
       });
   await();
 }
Пример #21
0
  private Buffer getIdentity(Packet packet) {
    logger.debug("function getIdentity");
    if (packet.getResponseExpected()) {
      byte length = (byte) 8 + 25;
      byte functionId = FUNCTION_GET_IDENTITY;
      byte flags = (byte) 0;
      Buffer header = Utils.createHeader(uidBytes, length, functionId, packet.getOptions(), flags);
      Buffer buffer = Buffer.buffer();
      buffer.appendBuffer(header);
      buffer.appendBuffer(Utils.getIdentityPayload(uidString, uidBytes, DEVICE_IDENTIFIER));
      return buffer;
    }

    return null;
  }
Пример #22
0
 private Buffer setVoltageCallbackThreshold(Packet packet) {
   logger.debug("function setVoltageCallbackThreshold");
   if (packet.getResponseExpected()) {
     byte length = (byte) 8 + 0;
     byte functionId = FUNCTION_SET_VOLTAGE_CALLBACK_THRESHOLD;
     byte flags = (byte) 0;
     Buffer header = Utils.createHeader(uidBytes, length, functionId, packet.getOptions(), flags);
     Buffer buffer = Buffer.buffer();
     buffer.appendBuffer(header);
     // TODO response expected bei settern
     return buffer;
   }
   this.voltageCallbackThreshold = packet.getPayload();
   return null;
 }
Пример #23
0
 private Buffer setAnalogValueCallbackPeriod(Packet packet) {
   logger.debug("function setAnalogValueCallbackPeriod");
   if (packet.getResponseExpected()) {
     byte length = (byte) 8 + 0;
     byte functionId = FUNCTION_SET_ANALOG_VALUE_CALLBACK_PERIOD;
     byte flags = (byte) 0;
     Buffer header = Utils.createHeader(uidBytes, length, functionId, packet.getOptions(), flags);
     Buffer buffer = Buffer.buffer();
     buffer.appendBuffer(header);
     // TODO response expected bei settern
     return buffer;
   }
   this.analogValueCallbackPeriod = packet.getPayload();
   return null;
 }
Пример #24
0
  private Buffer getAnalogValueCallbackThreshold(Packet packet) {
    logger.debug("function getAnalogValueCallbackThreshold");
    if (packet.getResponseExpected()) {
      byte length = (byte) 8 + 5;
      byte functionId = FUNCTION_GET_ANALOG_VALUE_CALLBACK_THRESHOLD;
      byte flags = (byte) 0;
      Buffer header = Utils.createHeader(uidBytes, length, functionId, packet.getOptions(), flags);
      Buffer buffer = Buffer.buffer();
      buffer.appendBuffer(header);
      buffer.appendBuffer(this.analogValueCallbackThreshold);
      return buffer;
    }

    return null;
  }
Пример #25
0
  private Buffer getVoltageCallbackPeriod(Packet packet) {
    logger.debug("function getVoltageCallbackPeriod");
    if (packet.getResponseExpected()) {
      byte length = (byte) 8 + 4;
      byte functionId = FUNCTION_GET_VOLTAGE_CALLBACK_PERIOD;
      byte flags = (byte) 0;
      Buffer header = Utils.createHeader(uidBytes, length, functionId, packet.getOptions(), flags);
      Buffer buffer = Buffer.buffer();
      buffer.appendBuffer(header);
      buffer.appendBuffer(this.voltageCallbackPeriod);
      return buffer;
    }

    return null;
  }
Пример #26
0
 @Test
 public void testWebsocketPauseAndResume() {
   client.close();
   client = vertx.createHttpClient(new HttpClientOptions().setConnectTimeout(1000));
   String path = "/some/path";
   this.server =
       vertx.createHttpServer(
           new HttpServerOptions().setAcceptBacklog(1).setPort(HttpTestBase.DEFAULT_HTTP_PORT));
   AtomicBoolean paused = new AtomicBoolean();
   ReadStream<ServerWebSocket> stream = server.websocketStream();
   stream.handler(
       ws -> {
         assertFalse(paused.get());
         ws.writeMessage(Buffer.buffer("whatever"));
         ws.close();
       });
   server.listen(
       listenAR -> {
         assertTrue(listenAR.succeeded());
         stream.pause();
         paused.set(true);
         client
             .websocket(HttpTestBase.DEFAULT_HTTP_PORT, HttpTestBase.DEFAULT_HTTP_HOST, path)
             .exceptionHandler(
                 err -> {
                   assertTrue(paused.get());
                   assertTrue(err instanceof WebSocketHandshakeException);
                   paused.set(false);
                   stream.resume();
                   client.connectWebsocket(
                       HttpTestBase.DEFAULT_HTTP_PORT,
                       HttpTestBase.DEFAULT_HTTP_HOST,
                       path,
                       ws -> {
                         ws.handler(
                             buffer -> {
                               assertEquals("whatever", buffer.toString("UTF-8"));
                               ws.closeHandler(
                                   v2 -> {
                                     testComplete();
                                   });
                             });
                       });
                 })
             .handler(ws -> fail());
       });
   await();
 }
Пример #27
0
  private Buffer getVoltage(Packet packet) {
    logger.debug("function getVoltage");
    if (packet.getResponseExpected()) {
      byte length = (byte) 8 + 2;
      byte functionId = FUNCTION_GET_VOLTAGE;
      byte flags = (byte) 0;
      Buffer header = Utils.createHeader(uidBytes, length, functionId, packet.getOptions(), flags);
      Buffer buffer = Buffer.buffer();
      buffer.appendBuffer(header);
      buffer.appendBytes(Utils.get2ByteURandomValue(1));

      return buffer;
    }

    return null;
  }
Пример #28
0
  @Test
  // Let's manually handle the websocket handshake and write a frame to the client
  public void testHandleWSManually() throws Exception {
    String path = "/some/path";
    String message = "here is some text data";

    server =
        vertx
            .createHttpServer(new HttpServerOptions().setPort(HttpTestBase.DEFAULT_HTTP_PORT))
            .requestHandler(
                req -> {
                  NetSocket sock = getUpgradedNetSocket(req, path);
                  // Let's write a Text frame raw
                  Buffer buff = Buffer.buffer();
                  buff.appendByte((byte) 129); // Text frame
                  buff.appendByte((byte) message.length());
                  buff.appendString(message);
                  sock.write(buff);
                });
    server.listen(
        ar -> {
          assertTrue(ar.succeeded());
          client
              .websocket(HttpTestBase.DEFAULT_HTTP_PORT, HttpTestBase.DEFAULT_HTTP_HOST, path)
              .exceptionHandler(t -> fail(t.getMessage()))
              .handler(
                  ws -> {
                    ws.handler(
                        buff -> {
                          assertEquals(message, buff.toString("UTF-8"));
                          testComplete();
                        });
                  });
        });
    await();
  }
Пример #29
0
 private Buffer body() {
   if (body == null) {
     body = Buffer.buffer();
   }
   return body;
 }
Пример #30
0
 private Buffer getVoltageCallbackPeriodDefault() {
   Buffer buffer = Buffer.buffer();
   buffer.appendBytes(Utils.get4ByteURandomValue(1));
   return buffer;
 }