Beispiel #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;
 }
Beispiel #2
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);
  }
 /**
  * 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();
 }
Beispiel #4
0
  @Test
  public void testCreateBuffers() throws Exception {
    Buffer buff = new Buffer(1000);
    assertEquals(0, buff.length());

    String str = TestUtils.randomUnicodeString(100);
    buff = new Buffer(str);
    assertEquals(buff.length(), str.getBytes("UTF-8").length);
    assertEquals(str, buff.toString());

    // TODO create with string with encoding

    byte[] bytes = TestUtils.generateRandomByteArray(100);
    buff = new Buffer(bytes);
    assertEquals(buff.length(), bytes.length);
    assertTrue(TestUtils.buffersEqual(new Buffer(bytes), new Buffer(buff.getBytes())));
  }
 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);
   }
 }
Beispiel #6
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")));
  }
Beispiel #7
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));
  }
Beispiel #8
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
  }
Beispiel #9
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));
    }
    @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);
    }
Beispiel #11
0
 @Test
 public void testAppendByte2() throws Exception {
   int bytesLen = 100;
   Buffer b = new Buffer(TestUtils.generateRandomByteArray(bytesLen));
   b.setByte(b.length(), (byte) 9);
 }
  private void submitGCM(
      final ResponseHelper helper,
      final JsonObject notif,
      final String apiKey,
      final HttpClient client,
      final Message<JsonObject> message,
      final int attempt) {
    final Buffer toSend;
    try {
      toSend = new Buffer(notif.encode().getBytes("UTF-8"));
    } catch (UnsupportedEncodingException e) {
      logger.error(e.getMessage());
      return;
    }
    logger.debug(
        "Attempt #"
            + (attempt + 1)
            + " to send notification to regIds "
            + notif.getArray("registration_ids").encode());
    HttpClientRequest request =
        client
            .post(
                uri.getPath(),
                new Handler<HttpClientResponse>() {
                  @Override
                  public void handle(final HttpClientResponse resp) {
                    final Buffer body = new Buffer(0);
                    resp.dataHandler(
                        new Handler<Buffer>() {
                          @Override
                          public void handle(Buffer data) {
                            body.appendBuffer(data);
                          }
                        });
                    resp.endHandler(
                        new VoidHandler() {
                          @Override
                          public void handle() {
                            boolean tryAgain = false;
                            JsonObject[] reply = {null};
                            JsonObject newNotif = new JsonObject();
                            int status = resp.statusCode();
                            if (status == 200) {
                              logger.debug("GCM response: " + body);
                              reply[0] = new JsonObject(new String(body.getBytes()));
                            } else {
                              logger.error("GCM error response: " + body);
                            }
                            if (reply[0] != null) {
                              helper.setMulticastId(
                                  reply[0].getLong("multicast_id") == null
                                      ? 0
                                      : reply[0].getLong("multicast_id"));
                              newNotif = updateStatus(notif, helper.getResponse(), reply[0]);
                              tryAgain =
                                  newNotif.getArray("registration_ids").size() != 0
                                      && attempt < gcm_backoff_retries;
                            } else {
                              tryAgain = attempt < gcm_backoff_retries;
                            }
                            if (tryAgain) {
                              int sleepTime =
                                  helper.getBackoff() / 2
                                      + helper.getRandom().nextInt(helper.getBackoff());
                              try {
                                Thread.sleep(sleepTime);
                              } catch (InterruptedException ie) {
                              }
                              if (2 * helper.getBackoff() < gcm_max_backoff_delay) {
                                helper.setBackoff(helper.getBackoff() * 2);
                              }
                              submitGCM(helper, newNotif, apiKey, client, message, attempt + 1);
                            } else {
                              if (helper.getResponse().isEmpty()) {
                                // all JSON posts failed due to GCM unavailability
                                sendError(message, "GCM is unavailable");
                              } else {
                                //                                JsonObject sendBack =
                                // calculateSummary( message.body().getObject( "notification"
                                // ).getArray( "registration_ids" ), helper.getResponse(),
                                // helper.getMulticastId() );
                                JsonObject sendBack =
                                    calculateSummary(
                                        notif.getArray("registration_ids"),
                                        helper.getResponse(),
                                        helper.getMulticastId());
                                sendOK(message, sendBack);
                              }
                            }
                          }
                        });
                  }
                })
            .putHeader("Content-Type", "application/json")
            .putHeader("Content-Length", String.valueOf(toSend.length()))
            .putHeader("Authorization", "key=" + apiKey)
            .write(toSend);

    request.end();
  }
Beispiel #13
0
 /**
  * Sets the bytes at position {@code pos} in the Buffer to the value {@code b}.
  *
  * <p>The buffer will expand as necessary to accomodate any value written.
  */
 public Buffer setBuffer(int pos, Buffer b) {
   ensureWritable(pos, b.length());
   buffer.setBytes(pos, b.getChannelBuffer());
   return this;
 }
public class WebServer extends Verticle implements Handler<HttpServerRequest> {

  private static String helloWorld = "Hello, World!";
  private static Buffer helloWorldBuffer = new Buffer(helloWorld);
  private static String helloWorldContentLength = String.valueOf(helloWorldBuffer.length());

  @Override
  public void start() {
    vertx.createHttpServer().requestHandler(WebServer.this).listen(8080);
  }

  @Override
  public void handle(HttpServerRequest req) {
    String path = req.path();
    switch (path.charAt(1)) {
      case 'p':
        handlePlainText(req);
        break;
      case 'j':
        handleJson(req);
        break;
      case 'd':
        handleDbMongo(req);
        break;
      default:
        req.response().setStatusCode(404);
        req.response().end();
    }
  }

  private void handlePlainText(HttpServerRequest req) {
    req.response().putHeader("Content-Type", "application/json; charset=UTF-8");
    req.response().putHeader("Content-Length", helloWorldContentLength);
    req.response().end(helloWorldBuffer);
  }

  private void handleJson(HttpServerRequest req) {
    String result = Json.encode(Collections.singletonMap("message", "Hello, world!"));
    int contentLength = result.getBytes(StandardCharsets.UTF_8).length;
    req.response().putHeader("Content-Type", "application/json; charset=UTF-8");
    req.response().putHeader("Content-Length", String.valueOf(contentLength));
    req.response().end(result);
  }

  private void handleDbMongo(final HttpServerRequest req) {
    int queriesParam = 1;
    try {
      queriesParam = Integer.parseInt(req.params().get("queries"));
    } catch (NumberFormatException e) {
      // do nothing
    }

    final MongoHandler dbh = new MongoHandler(req, queriesParam);
    final Random random = ThreadLocalRandom.current();

    for (int i = 0; i < queriesParam; i++) {
      vertx
          .eventBus()
          .send(
              "hello.persistor",
              new JsonObject()
                  .putString("action", "findone")
                  .putString("collection", "world")
                  .putObject(
                      "matcher", new JsonObject().putNumber("id", (random.nextInt(10000) + 1))),
              dbh);
    }
  }

  private static class MongoHandler implements Handler<Message<JsonObject>> {
    private final HttpServerRequest req;
    private final int queries;
    private final List<Object> worlds = new ArrayList<>();

    public MongoHandler(HttpServerRequest request, int queriesParam) {
      this.req = request;
      this.queries = queriesParam;
    }

    @Override
    public void handle(Message<JsonObject> reply) {
      final JsonObject body = reply.body();

      if ("ok".equals(body.getString("status"))) {
        this.worlds.add(body.getObject("result"));
        if (this.worlds.size() == this.queries) {
          // All queries have completed; send the response.
          final String result = Json.encode(worlds);
          final int contentLength = result.getBytes(StandardCharsets.UTF_8).length;
          this.req.response().putHeader("Content-Type", "application/json; charset=UTF-8");
          this.req.response().putHeader("Content-Length", String.valueOf(contentLength));
          this.req.response().end(result);
        }
      } else {
        System.err.println("Failed to execute query");
      }
    }
  }
}