Ejemplo n.º 1
0
 public static boolean buffersEqual(Buffer b1, Buffer b2) {
   if (b1.length() != b2.length()) return false;
   for (int i = 0; i < b1.length(); i++) {
     if (b1.getByte(i) != b2.getByte(i)) return false;
   }
   return true;
 }
Ejemplo n.º 2
0
 /**
  * Appends the specified {@code Buffer} to the end of the Buffer. The buffer will expand as
  * necessary to accomodate any bytes written.
  *
  * <p>Returns a reference to {@code this} so multiple operations can be appended together.
  */
 public Buffer appendBuffer(Buffer buff) {
   ChannelBuffer cb = buff.getChannelBuffer();
   buffer.writeBytes(buff.getChannelBuffer());
   cb.readerIndex(
       0); // Need to reset readerindex since Netty write modifies readerIndex of source!
   return this;
 }
Ejemplo n.º 3
0
  @Test
  public void testGetBytes() throws Exception {
    byte[] bytes = TestUtils.generateRandomByteArray(100);
    Buffer b = new Buffer(bytes);

    assertTrue(TestUtils.byteArraysEqual(bytes, b.getBytes()));
  }
Ejemplo n.º 4
0
 private void testSetFloat(Buffer buff) throws Exception {
   for (int i = 0; i < numSets; i++) {
     buff.setFloat(i * 4, (float) i);
   }
   for (int i = 0; i < numSets; i++) {
     assertEquals((float) i, buff.getFloat(i * 4));
   }
 }
Ejemplo n.º 5
0
 private void testSetShort(Buffer buff) throws Exception {
   for (int i = 0; i < numSets; i++) {
     buff.setShort(i * 2, (short) i);
   }
   for (int i = 0; i < numSets; i++) {
     assertEquals(i, buff.getShort(i * 2));
   }
 }
Ejemplo n.º 6
0
 private void testSetLong(Buffer buff) throws Exception {
   for (int i = 0; i < numSets; i++) {
     buff.setLong(i * 8, i);
   }
   for (int i = 0; i < numSets; i++) {
     assertEquals(i, buff.getLong(i * 8));
   }
 }
Ejemplo n.º 7
0
 private void testSetByte(Buffer buff) throws Exception {
   for (int i = 0; i < numSets; i++) {
     buff.setByte(i, (byte) i);
   }
   for (int i = 0; i < numSets; i++) {
     assertEquals(i, buff.getByte(i));
   }
 }
Ejemplo n.º 8
0
 private void testSetDouble(Buffer buff) throws Exception {
   for (int i = 0; i < numSets; i++) {
     buff.setDouble(i * 8, (double) i);
   }
   for (int i = 0; i < numSets; i++) {
     assertEquals((double) i, buff.getDouble(i * 8));
   }
 }
Ejemplo n.º 9
0
  @Test
  public void testToString() throws Exception {
    String str = TestUtils.randomUnicodeString(100);
    Buffer buff = new Buffer(str);
    assertEquals(str, buff.toString());

    // TODO toString with encoding
  }
 private void manualEncodeVertxMessageBody(ActiveMQBuffer bodyBuffer, Object body, int type) {
   switch (type) {
     case VertxConstants.TYPE_BOOLEAN:
       bodyBuffer.writeBoolean(((Boolean) body));
       break;
     case VertxConstants.TYPE_BUFFER:
       Buffer buff = (Buffer) body;
       int len = buff.length();
       bodyBuffer.writeInt(len);
       bodyBuffer.writeBytes(((Buffer) body).getBytes());
       break;
     case VertxConstants.TYPE_BYTEARRAY:
       byte[] bytes = (byte[]) body;
       bodyBuffer.writeInt(bytes.length);
       bodyBuffer.writeBytes(bytes);
       break;
     case VertxConstants.TYPE_BYTE:
       bodyBuffer.writeByte((byte) body);
       break;
     case VertxConstants.TYPE_CHARACTER:
       bodyBuffer.writeChar((Character) body);
       break;
     case VertxConstants.TYPE_DOUBLE:
       bodyBuffer.writeDouble((double) body);
       break;
     case VertxConstants.TYPE_FLOAT:
       bodyBuffer.writeFloat((Float) body);
       break;
     case VertxConstants.TYPE_INT:
       bodyBuffer.writeInt((Integer) body);
       break;
     case VertxConstants.TYPE_LONG:
       bodyBuffer.writeLong((Long) body);
       break;
     case VertxConstants.TYPE_SHORT:
       bodyBuffer.writeShort((Short) body);
       break;
     case VertxConstants.TYPE_STRING:
     case VertxConstants.TYPE_PING:
       bodyBuffer.writeString((String) body);
       break;
     case VertxConstants.TYPE_JSON_OBJECT:
       bodyBuffer.writeString(((JsonObject) body).encode());
       break;
     case VertxConstants.TYPE_JSON_ARRAY:
       bodyBuffer.writeString(((JsonArray) body).encode());
       break;
     case VertxConstants.TYPE_REPLY_FAILURE:
       ReplyException except = (ReplyException) body;
       bodyBuffer.writeInt(except.failureType().toInt());
       bodyBuffer.writeInt(except.failureCode());
       bodyBuffer.writeString(except.getMessage());
       break;
     default:
       throw new IllegalArgumentException("Invalid body type: " + type);
   }
 }
Ejemplo n.º 11
0
  @Test
  public void testGetByte() throws Exception {
    int bytesLen = 100;
    byte[] bytes = TestUtils.generateRandomByteArray(bytesLen);

    Buffer b = new Buffer(bytes);
    for (int i = 0; i < bytesLen; i++) {
      assertEquals(bytes[i], b.getByte(i));
    }
  }
Ejemplo n.º 12
0
  @Test
  public void testGetBytes2() throws Exception {
    byte[] bytes = TestUtils.generateRandomByteArray(100);
    Buffer b = new Buffer(bytes);

    byte[] sub = new byte[bytes.length / 2];
    System.arraycopy(bytes, bytes.length / 4, sub, 0, bytes.length / 2);
    assertTrue(
        TestUtils.byteArraysEqual(
            sub, b.getBytes(bytes.length / 4, bytes.length / 4 + bytes.length / 2)));
  }
Ejemplo n.º 13
0
  @Test
  public void testAppendString1() throws Exception {

    String str = TestUtils.randomUnicodeString(100);
    byte[] sb = str.getBytes("UTF-8");

    Buffer b = new Buffer();
    b.appendString(str);
    assertEquals(b.length(), sb.length);
    assertTrue(str.equals(b.toString("UTF-8")));
  }
Ejemplo n.º 14
0
  @Test
  public void testGetLong() throws Exception {
    int numLongs = 100;
    Buffer b = new Buffer(numLongs * 8);
    for (int i = 0; i < numLongs; i++) {
      b.setLong(i * 8, i);
    }

    for (int i = 0; i < numLongs; i++) {
      assertEquals(i, b.getLong(i * 8));
    }
  }
Ejemplo n.º 15
0
  private void testSetBytesString(Buffer buff) throws Exception {

    String str = TestUtils.randomUnicodeString(100);
    buff.setString(50, str);

    byte[] b1 = buff.getBytes(50, buff.length());
    String str2 = new String(b1, "UTF-8");

    assertEquals(str, str2);

    // TODO setString with encoding
  }
Ejemplo n.º 16
0
  @Test
  public void testGetShort() throws Exception {
    int numShorts = 100;
    Buffer b = new Buffer(numShorts * 2);
    for (short i = 0; i < numShorts; i++) {
      b.setShort(i * 2, i);
    }

    for (short i = 0; i < numShorts; i++) {
      assertEquals(i, b.getShort(i * 2));
    }
  }
Ejemplo n.º 17
0
  @Test
  public void testGetDouble() throws Exception {
    int numDoubles = 100;
    Buffer b = new Buffer(numDoubles * 8);
    for (int i = 0; i < numDoubles; i++) {
      b.setDouble(i * 8, i);
    }

    for (int i = 0; i < numDoubles; i++) {
      assertEquals((double) i, b.getDouble(i * 8));
    }
  }
Ejemplo n.º 18
0
  private void testSetBytesBuffer(Buffer buff) throws Exception {

    Buffer b = TestUtils.generateRandomBuffer(100);
    buff.setBuffer(50, b);
    byte[] b2 = buff.getBytes(50, 150);
    assertTrue(TestUtils.buffersEqual(b, new Buffer(b2)));

    byte[] b3 = TestUtils.generateRandomByteArray(100);
    buff.setBytes(50, b3);
    byte[] b4 = buff.getBytes(50, 150);
    assertTrue(TestUtils.buffersEqual(new Buffer(b3), new Buffer(b4)));
  }
Ejemplo n.º 19
0
  @Test
  public void testCopy() throws Exception {
    Buffer buff = TestUtils.generateRandomBuffer(100);
    assertTrue(TestUtils.buffersEqual(buff, buff.copy()));

    Buffer copy = buff.getBuffer(0, buff.length());
    assertTrue(TestUtils.buffersEqual(buff, copy));

    // Make sure they don't share underlying buffer
    buff.setInt(0, 1);
    assertTrue(!TestUtils.buffersEqual(buff, copy));
  }
Ejemplo n.º 20
0
  @Test
  public void testGetFloat() throws Exception {
    int numFloats = 100;
    Buffer b = new Buffer(numFloats * 4);
    for (int i = 0; i < numFloats; i++) {
      b.setFloat(i * 4, i);
    }

    for (int i = 0; i < numFloats; i++) {
      assertEquals((float) i, b.getFloat(i * 4));
    }
  }
Ejemplo n.º 21
0
  @Test
  public void testhandleOne() {
    final EventManager eventManager = mock(EventManager.class);
    final PostParams postParams = new PostParams(eventManager);
    final Buffer buff = new Buffer();
    buff.appendString("param1=value1");
    postParams.handle(buff);

    final ArgumentCaptor<HashMap> arguments = ArgumentCaptor.forClass(HashMap.class);
    verify(eventManager, only()).run(arguments.capture());
    assertEquals(1, arguments.getValue().entrySet().size());
    assertEquals("value1", arguments.getValue().get("param1"));
  }
Ejemplo n.º 22
0
    Icon(Buffer buffer) {
      headers = new HashMap<>();
      body = buffer;

      headers.put("content-type", "image/x-icon");
      headers.put("content-length", buffer.length());

      try {
        MessageDigest md = MessageDigest.getInstance("MD5");
        headers.put("etag", "\"" + Utils.base64(md.digest(buffer.getBytes())) + "\"");
      } catch (NoSuchAlgorithmException e) {
        // ignore
      }
      headers.put("cache-control", "public, max-age=" + (maxAge / 1000));
    }
Ejemplo n.º 23
0
  public void fillInRequest(HttpClientRequest req, String hostHeader) throws Exception {

    req.headers().put(HttpHeaders.Names.CONNECTION, "Upgrade");
    req.headers().put(HttpHeaders.Names.UPGRADE, "WebSocket");
    req.headers().put(HttpHeaders.Names.HOST, hostHeader);

    req.headers().put(HttpHeaders.Names.SEC_WEBSOCKET_KEY1, this.challenge.getKey1String());
    req.headers().put(HttpHeaders.Names.SEC_WEBSOCKET_KEY2, this.challenge.getKey2String());

    Buffer buff = new Buffer(6);
    buff.appendBytes(challenge.getKey3());
    buff.appendByte((byte) '\r');
    buff.appendByte((byte) '\n');
    req.write(buff);
  }
Ejemplo n.º 24
0
  @Override
  public void onData(Buffer input) {

    // Create our own copy since we will process later.
    final ByteBuffer source = ByteBuffer.wrap(input.getBytes());

    serializer.execute(
        new Runnable() {

          @Override
          public void run() {
            LOG.trace("Received from Broker {} bytes:", source.remaining());

            do {
              ByteBuffer buffer = protonTransport.getInputBuffer();
              int limit = Math.min(buffer.remaining(), source.remaining());
              ByteBuffer duplicate = source.duplicate();
              duplicate.limit(source.position() + limit);
              buffer.put(duplicate);
              protonTransport.processInput();
              source.position(source.position() + limit);
            } while (source.hasRemaining());

            // Process the state changes from the latest data and then answer back
            // any pending updates to the Broker.
            processUpdates();
            pumpToProtonTransport();
          }
        });
  }
Ejemplo n.º 25
0
  public void onComplete(HttpClientResponse response, final CompletionHandler<Void> doneHandler) {

    final Buffer buff = Buffer.create(16);
    response.dataHandler(
        new Handler<Buffer>() {
          public void handle(Buffer data) {
            buff.appendBuffer(data);
          }
        });
    response.endHandler(
        new SimpleHandler() {
          public void handle() {
            byte[] bytes = buff.getBytes();
            SimpleFuture<Void> fut = new SimpleFuture<>();
            try {
              if (challenge.verify(bytes)) {
                fut.setResult(null);
              } else {
                fut.setException(new Exception("Invalid websocket handshake response"));
              }
            } catch (Exception e) {
              fut.setException(e);
            }
            doneHandler.handle(fut);
          }
        });
  }
Ejemplo n.º 26
0
 /**
  * Same as {@link #end()} but writes some data to the request body before ending. If the request
  * is not chunked and no other data has been written then the Content-Length header will be
  * automatically set
  */
 public void end(Buffer chunk) {
   if (!chunked && contentLength == 0) {
     contentLength = chunk.length();
     request.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(contentLength));
   }
   write(chunk);
   end();
 }
  private void hecPost(String bodyContent) throws Exception {

    Buffer buff = new Buffer();
    buff.appendString(bodyContent);

    HttpClientRequest request =
        client.post(
            "/services/collector",
            new Handler<HttpClientResponse>() {
              public void handle(HttpClientResponse resp) {
                if (resp.statusCode() != 200) logger.error("Got a response: " + resp.statusCode());
              }
            });
    request.headers().set("Authorization", "Splunk " + token);
    request.headers().set("Content-Length", String.valueOf(bodyContent.length()));
    request.write(buff);

    request.end();
  }
    @Override
    public void handle(Buffer body) {
      String query = body.getString(0, body.length());
      if (Strings.isNullOrEmpty(query) || query.equals("{}")) {
        replyHandler.replyForError(null);
        return;
      }

      //         object.putString("req-id",requestId);
      Action action = new Action();
      action.setId(requestId);
      action.setCategory(StringConstants.ACTION);
      action.setLabel(IManagerConstants.PUT_ENC_OBJECT);
      action.setOwnerId(com.getId());
      action.setComponentType("webservice");
      action.setTriggered("");
      action.setTriggers(new JsonArray());
      JsonObject object = new JsonObject(query);
      action.setData(object);
      action.setDestination(StringConstants.IMANAGERQUEUE);
      action.setStatus(ActionStatus.PENDING.toString());
      com.sendRequestTo(StringConstants.IMANAGERQUEUE, action.asJsonObject(), replyHandler);
    }
Ejemplo n.º 29
0
  private void parseConfigAndStart(final Buffer buffer) {
    final JsonObject config = new JsonObject(buffer.toString());

    container.deployModule(
        METRICS_MODULE,
        config.getObject("metrics"),
        ar -> {
          if (ar.succeeded()) {
            container
                .logger()
                .fatal("Deployed: " + METRICS_MODULE + " with id: " + ar.result(), ar.cause());

            start(config);
          } else {
            container.logger().fatal("Failed to deploy: " + METRICS_MODULE, ar.cause());
          }
        });
  }
Ejemplo n.º 30
0
  @Test
  public void testAppendBytes() throws Exception {

    int bytesLen = 100;
    byte[] bytes = TestUtils.generateRandomByteArray(bytesLen);

    Buffer b = new Buffer();
    b.appendBytes(bytes);
    assertEquals(b.length(), bytes.length);
    assertTrue(TestUtils.byteArraysEqual(bytes, b.getBytes()));

    b.appendBytes(bytes);
    assertEquals(b.length(), 2 * bytes.length);
  }