Exemplo n.º 1
0
 public Request subscribeAccount(AccountID... accounts) {
   Request request = newRequest(Command.subscribe);
   JSONArray accounts_arr = new JSONArray();
   for (AccountID acc : accounts) {
     accounts_arr.put(acc);
   }
   request.json("accounts", accounts_arr);
   return request;
 }
Exemplo n.º 2
0
  void onResponse(JSONObject msg) {
    Request request = requests.remove(msg.optInt("id", -1));

    if (request == null) {
      log(Level.WARNING, "Response without a request: {0}", msg);
      return;
    }
    request.handleResponse(msg);
  }
Exemplo n.º 3
0
 public Request subscribeBookOffers(Issue get, Issue pay) {
   Request request = newRequest(Command.subscribe);
   JSONObject book = new JSONObject();
   JSONArray books = new JSONArray(new Object[] {book});
   book.put("snapshot", true);
   book.put("taker_gets", get.toJSON());
   book.put("taker_pays", pay.toJSON());
   request.json("books", books);
   return request;
 }
Exemplo n.º 4
0
  public <T> Request makeManagedRequest(
      final Command cmd, final Manager<T> manager, final Request.Builder<T> builder) {
    final Request request = newRequest(cmd);
    final boolean[] responded = new boolean[] {false};
    request.once(
        Request.OnTimeout.class,
        new Request.OnTimeout() {
          @Override
          public void called(Response args) {
            if (!responded[0] && manager.retryOnUnsuccessful(null)) {
              logRetry(request, "Request timed out");
              request.clearAllListeners();
              queueRetry(50, cmd, manager, builder);
            }
          }
        });
    final OnDisconnected cb =
        new OnDisconnected() {
          @Override
          public void called(Client c) {
            if (!responded[0] && manager.retryOnUnsuccessful(null)) {
              logRetry(request, "Client disconnected");
              request.clearAllListeners();
              queueRetry(50, cmd, manager, builder);
            }
          }
        };
    once(OnDisconnected.class, cb);
    request.once(
        Request.OnResponse.class,
        new Request.OnResponse() {
          @Override
          public void called(final Response response) {
            responded[0] = true;
            Client.this.removeListener(OnDisconnected.class, cb);

            if (response.succeeded) {
              final T t = builder.buildTypedResponse(response);
              manager.cb(response, t);
            } else {
              if (manager.retryOnUnsuccessful(response)) {
                queueRetry(50, cmd, manager, builder);
              } else {
                manager.cb(response, null);
              }
            }
          }
        });
    builder.beforeRequest(request);
    manager.beforeRequest(request);
    request.request();
    return request;
  }
Exemplo n.º 5
0
  private void subscribe(JSONObject subscription) {
    Request request = newRequest(Command.subscribe);

    request.json(subscription);
    request.on(
        Request.OnSuccess.class,
        new Request.OnSuccess() {
          @Override
          public void called(Response response) {
            // TODO ... make sure this isn't just an account subscription
            serverInfo.update(response.result);
            emit(OnSubscribed.class, serverInfo);
          }
        });
    request.request();
  }
Exemplo n.º 6
0
  void manageTimedOutRequests() {
    long now = System.currentTimeMillis();
    ArrayList<Request> timedOut = new ArrayList<Request>();

    for (Request request : requests.values()) {
      if (request.sendTime != 0) {
        long since = now - request.sendTime;
        if (since >= Request.TIME_OUT) {
          timedOut.add(request);
        }
      }
    }
    for (Request request : timedOut) {
      request.emit(Request.OnTimeout.class, request.response);
      requests.remove(request.id);
    }
  }
Exemplo n.º 7
0
  public void sendRequest(final Request request) {
    Logger reqLog = Request.logger;

    try {
      requests.put(request.id, request);
      request.bumpSendTime();
      sendMessage(request.toJSON());
      // Better safe than sorry
    } catch (Exception e) {
      if (reqLog.isLoggable(Level.WARNING)) {
        reqLog.log(Level.WARNING, "Exception when trying to request: {0}", e);
      }
      nextTickOrWhenConnected(
          new OnConnected() {
            @Override
            public void called(Client args) {
              sendRequest(request);
            }
          });
    }
  }
Exemplo n.º 8
0
 private void logRetry(Request request, String reason) {
   if (logger.isLoggable(Level.WARNING)) {
     log(
         Level.WARNING,
         previousUri
             + ": "
             + reason
             + ", muting listeners "
             + "for "
             + request.json()
             + "and trying again");
   }
 }
  private static void walkAccountTx(final Client c, final Object marker, final int pages) {
    Request request = c.newRequest(Command.account_tx);
    request.json("binary", true);
    request.json("account", theAccount);

    if (marker != null) {
      request.json("marker", marker);
    }
    request.json("ledger_index_max", -1);

    request.once(
        Request.OnSuccess.class,
        new Request.OnSuccess() {
          @Override
          public void called(Response response) {
            JSONObject result = response.result;
            try {
              JSONArray transactions = result.getJSONArray("transactions");
              System.out.printf("Found %d (more) transactions %n", transactions.length());
              appendTo(outputFile, result.toString());

              Object newMarker = result.opt("marker");
              System.out.printf("Marker %s%n", newMarker);
              if (marker != null
                  && newMarker != null
                  && marker.toString().equals(newMarker.toString())) {
                // This shouldn't happen since Stef's patch but who knows how
                // pervasively it's been deployed ?
                //                        return;
                newMarker = null;
              }
              if ((newMarker != null) && (pages - 1 > 0) && transactions.length() > 0) {
                System.out.printf("Found new marker %s%n", newMarker);
                walkAccountTx(c, newMarker, pages - 1);
              } else {
                System.out.printf("Found all transactions");
              }

            } catch (Exception e) {
              throw new RuntimeException(e);
            }
          }
        });

    request.request();
  }
Exemplo n.º 10
0
 public Request requestBookOffers(Issue get, Issue pay) {
   Request request = newRequest(Command.book_offers);
   request.json("taker_gets", get.toJSON());
   request.json("taker_pays", pay.toJSON());
   return request;
 }
Exemplo n.º 11
0
 public Request accountInfo(AccountID account) {
   Request req = newRequest(Command.account_info);
   req.json("account", account.address);
   return req;
 }
Exemplo n.º 12
0
 public Request accountLines(AccountID account) {
   Request req = newRequest(Command.account_lines);
   req.json("account", account.address);
   return req;
 }
Exemplo n.º 13
0
 public Request submit(String tx_blob, boolean fail_hard) {
   Request req = newRequest(Command.submit);
   req.json("tx_blob", tx_blob);
   req.json("fail_hard", fail_hard);
   return req;
 }
Exemplo n.º 14
0
  @Test
  public void testMockPairSubscription() throws JSONException {
    MockPair pair = new MockPair().connect();
    MockPair.RippledMock mock = pair.server;
    Client client = pair.client;

    // We can pop the latest JSON message received from the client then
    // actually get the Request object (to inspect and set event handlers etc)
    final Request subscribeRequest = mock.popMessage().getRequest(client);
    assertEquals(
        "We expect the first message sent by the client to be a subscribe request",
        Command.subscribe,
        subscribeRequest.cmd);

    // There's a buffer for read/unread messages sent from client
    assertEquals("There should be no unread messages", 0, mock.messages.size());
    assertEquals("There should be one archived", 1, mock.archived.size());

    int ledger_time = 434537640;
    final String random_seed = "064486ACF5FEE8A9FD1A9026E0D9D763DDFC51FC2220E13E6E392F81B0CA4D25";

    // We build a result to send
    JSONObject subscribeResult =
        JSONBuilder.build()
            .fee_base(10)
            .fee_ref(10)
            .ledger_hash("95B5F9CA0AEAD59CBBA5D14F0F248472255F241DEF3CF881CECA3CA4B01FC178")
            .ledger_index(2642686)
            .ledger_time(ledger_time)
            .load_base(256)
            .load_factor(256)
            .random(random_seed)
            .reserve_base(50000000)
            .reserve_inc(12500000)
            .server_status("full")
            .validated_ledgers("32570-2642686")
            .finish();

    // A ServerInfo object is where we store all the fields above
    ServerInfo info = client.serverInfo;
    assertEquals("Right now we don't know", 0, info.fee_base);
    assertFalse(info.updated);

    final boolean[] successRan = new boolean[] {false};
    subscribeRequest.on(
        Request.OnSuccess.class,
        new Request.OnSuccess() {
          public void called(Response response) {
            successRan[0] = true; // yee old python 2.x trick
            assertEquals(random_seed, response.result.optString("random"));
          }
        });

    // Then we can actually respond to that Request object with a message result
    // The `id` is retrieved from the Request object
    assertNull(subscribeRequest.response);
    mock.respondSuccess(subscribeRequest, subscribeResult);

    assertTrue(successRan[0]);

    // Once responded the response object will hung off the Request
    assertNotNull(subscribeRequest.response);
    Response response = subscribeRequest.response;

    // You can retrieve the message and also the result
    JSONObject rsp = response.message, result = response.result;

    // The response id should match up, and result fields match those as passed
    // to respondSuccess
    assertEquals(subscribeRequest.id, rsp.optInt("id", -1));
    assertEquals(random_seed, result.getString("random"));
    assertEquals(ledger_time, result.getInt("ledger_time"));

    // We should now actually have some fields available on the client
    // We should be able to compute a fee
    assertEquals(true, info.updated);
    assertEquals(10, info.fee_base);
    assertEquals(10, info.fee_ref);
    assertEquals(256, info.load_base);
    assertEquals(256, info.load_factor);
  }