public static Packet createRPCPacket(NetworkManager m, RPC rpc) throws IOException {
   if (!rpc.isInitialized()) {
     if (T.t) {
       T.error("RPC not initialized!");
     }
   }
   Packet p = m.createPacketForSend();
   p.writeByte(RPCFactory.getPacketIdFor(rpc));
   p = rpc.serializeTo(p);
   return p;
 }
Esempio n. 2
0
  @Test(dependsOnGroups = "example.ipc.server")
  public void clientRPC() throws Exception {
    RPC.ClientRPC client = RPC.getClientRPC(socketAddress);
    GetRequest request = GetRequest.newBuilder().setRow(ByteString.copyFromUtf8("row1")).build();

    Deferred<GetResponse> response = client.getData(request);
    GetResponse data = response.join();
    System.out.println(data);

    Deferred<GetResponse> deferred = client.getData(request);
    deferred
        .addCallback(
            new Callback<Object, GetResponse>() {
              public Object call(final GetResponse getResponse) throws Exception {
                System.out.println(getResponse);
                return null;
              }
            })
        .addErrback(
            new Callback<Object, Object>() {
              public Object call(final Object o) throws Exception {
                System.err.println("ERROR: " + o);
                return null;
              }
            });
  }
 static void invalidate(H2ONode h2o, Key key, Value newval, Futures fs) {
   assert newval._key != null && key.home();
   // Prevent the new Value from being overwritten by Yet Another PUT by
   // read-locking it.  It's safe to read, but not to over-write, until this
   // invalidate completes on the *prior* value.
   newval.read_lock(); // block further writes until all invalidates complete
   fs.add(RPC.call(h2o, new TaskInvalidateKey(key, newval)));
 }
 public void send(int dstGuid, RPC rpc) throws IOException {
   if (dstGuid != getRemoteUserGUID()) {
     if (T.t) {
       T.debug("Rerouting package " + rpc + " to " + dstGuid);
     }
     route(dstGuid, rpc);
   } else {
     if (!rpc.isInitialized()) {
       rpc.init(
           this); // under certain conditions a rpc can be reused and sent a second time - then
       // it's the first init call that counts. Don't make it twice.
     }
     Packet p = createRPCPacket(rpc);
     if (T.t) {
       T.debug("--> Sending " + rpc + " (" + p.getPos() + " bytes) to " + getRemoteFriend());
     }
     send(p);
   }
 }
 public void received(int fromGuid, int hops, Packet packet, RPC outerRPC) throws IOException {
   int id = packet.readByte();
   RPC rpc = RPCFactory.newInstance(id);
   if (rpc == null) {
     if (T.t) {
       T.warn("Skipping unknown RPC ID: " + id + "!!!");
     }
     packet.skip(packet.getAvailable()); // skip contents of packet
     return;
   } else {
     if (T.t) {
       if (outerRPC == null) {
         T.debug(
             "<-- Recived "
                 + rpc
                 + " ("
                 + (packet.getAvailable() + 1)
                 + " bytes) from "
                 + netMan.getFriendManager().getNode(fromGuid)
                 + " (con: "
                 + getRemoteFriend()
                 + ")"); // +1 because we read one byte above
       } else {
         T.debug(
             "<----- Recived "
                 + rpc
                 + " ("
                 + (packet.getAvailable() + 1)
                 + " bytes) from "
                 + netMan.getFriendManager().getNode(fromGuid)
                 + " (con: "
                 + getRemoteFriend()
                 + ", outer: "
                 + outerRPC
                 + ")"); // +1 because we read one byte above
       }
     }
     rpc.init(this, fromGuid, hops);
     rpc.execute(packet);
     signalReceived(rpc);
   }
 }
 public void route(int dstGuid, RPC rpc) throws IOException {
   Friend f = netMan.getFriendManager().getFriend(dstGuid);
   if (f != null && f.getFriendConnection() != null) {
     if (T.t) {
       T.info("Rerouting package to friend");
     }
     f.getFriendConnection().send(rpc);
   } else {
     // note that one of our friends COULD actually be a closer Route to the destination. But this
     // way we send
     // the rpc the same way back as be got it. No biggie probably.
     rpc.init(this);
     Packet p = createRPCPacket(rpc);
     send(new Route(netMan.getFriendManager().getMyGUID(), dstGuid, p));
   }
 }
Esempio n. 7
0
  /**
   * Description: Here we are making our remote procedure call specifically using Pandora's JSON
   * protocol. This will return a JSONObject holding the contents of the results key in the
   * response. If an error occurs (ie "stat":"fail") an exception with the message body will be
   * thrown. Caution: When debugging, be sure to note that most data that flows through here is time
   * sensitive, and if stopped in the wrong places, it will cause "stat":"fail" responses from the
   * remote server.
   */
  private JSONObject doCall(
      String method,
      Map<String, Object> json_params,
      boolean http_secure_flag,
      boolean encrypt,
      Map<String, String> opt_url_params)
      throws Exception, RPCException, IOException, HttpResponseException {
    JSONObject response = null;
    JSONObject request = null;
    if (json_params != null) {
      request = new JSONObject(json_params);
    } else {
      request = new JSONObject();
    }

    Map<String, String> url_params = new HashMap<String, String>(standard_url_params);
    url_params.put("method", method);
    if (opt_url_params != null) {
      url_params.putAll(opt_url_params);
    }

    if (user_auth_token != null) {
      request.put("userAuthToken", user_auth_token);
    }
    if (sync_time != 0) {
      request.put("syncTime", calcSync());
    }

    String request_string = request.toString();
    if (encrypt) {
      request_string = this.pandoraEncrypt(request_string);
    }

    String response_string = pandora_rpc.call(url_params, request_string, http_secure_flag);
    response = new JSONObject(response_string);
    if (response.getString("stat").compareTo("ok") != 0) {
      if (response.getString("stat").compareTo("fail") == 0) {
        throw new RPCException(response.getInt("code"), response.getString("message"));
      } else {
        throw new Exception("RPC unknown error. stat: " + response.getString("stat"));
      }
    }

    return response.getJSONObject("result"); // Exception thrown if nonexistent
  }
 public void broadcast(short msgId, RPC rpc) throws IOException {
   rpc.init(this);
   Packet p = createRPCPacket(rpc);
   send(new Broadcast(netMan.getFriendManager().getMyGUID(), msgId, p));
 }
Esempio n. 9
0
  @Test
  public void test() throws UnknownHostException, ExecutionException, InterruptedException {
    final JavaSerializer serializer = new JavaSerializer();
    RPCHandler handler1 = new RPCHandler(serializer);
    RPCHandler handler2 = new RPCHandler(serializer);
    RoutingHandler router =
        new RoutingHandler(
            ImmutableMap.<String, ChannelHandler>builder()
                .put("/one", handler1)
                .put("/two", handler2)
                .build());
    HTTPServer server =
        new HTTPServer(
            TcpOptions.create().localAddress(new InetSocketAddress(InetAddress.getLocalHost(), 0)),
            2,
            router);

    RPCClient client1 = new RPCClient(TcpOptions.create(), "/one", 2, serializer);
    RPCClient client2 = new RPCClient(TcpOptions.create(), "/two", 2, serializer);
    RPCClient client3 = new RPCClient(TcpOptions.create(), "/noexisting", 2, serializer);

    RPC<Void, String> signature = RPC.signature("/method", Void.class, String.class);
    server.startAsync().awaitRunning();
    try {
      handler1.register(
          signature,
          new ServerMethod<Void, String>() {
            @Override
            public ListenableFuture<String> call(Envelope envelope, Void argument) {
              return Futures.immediateFuture("one");
            }
          });

      handler2.register(
          signature,
          new ServerMethod<Void, String>() {
            @Override
            public ListenableFuture<String> call(Envelope envelope, Void argument) {
              return Futures.immediateFuture("two");
            }
          });

      ClientMethod<Void, String> method1 = client1.createMethod(signature);
      ClientMethod<Void, String> method2 = client2.createMethod(signature);
      ClientMethod<Void, String> method3 = client3.createMethod(signature);

      Envelope envelope = new Envelope(1000, "asdfasdfas");
      assertEquals(method1.call(server.getLocalAddress(), envelope, null).get(), "one");
      assertEquals(method2.call(server.getLocalAddress(), envelope, null).get(), "two");

      try {
        assertEquals(method3.call(server.getLocalAddress(), envelope, null).get(), "wtf?");
        fail();
      } catch (ExecutionException e) {
        assertTrue(e.getCause() instanceof BadResponseException);
        assertTrue(e.getCause().getMessage().contains("404"));
      }

    } finally {
      client1.stopAsync().awaitTerminated();
      client2.stopAsync().awaitTerminated();
      client3.stopAsync().awaitTerminated();
      server.stopAsync().awaitTerminated();
    }
  }