org.apache.thrift.async.TAsyncClientManager Java Examples

The following examples show how to use org.apache.thrift.async.TAsyncClientManager. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AsyncMockServerRuleTest.java    From thrift-mock with Apache License 2.0 5 votes vote down vote up
@Test
public void testAsyncServerRule() throws Exception {
  String responseMsg = "asyncHello";
  Response expectHelloResponse = new Response(200, responseMsg);
  server.setExpectReturn("sayHello", expectHelloResponse);

  TNonblockingTransport transport = new TNonblockingSocket("127.0.0.1",
                                                           9999,
                                                           3000);
  HelloService.AsyncIface client = new HelloService.AsyncClient(new TBinaryProtocol.Factory(),
                                                                new TAsyncClientManager(),
                                                                transport);
  Request request = new Request();
  request.setMsg("hello async!");
  Response result = new Response();
  Stopwatch stopwatch = Stopwatch.createStarted();
  client.sayHello(request, new AsyncMethodCallback() {
    @Override
    public void onComplete(Object response) {
      System.out.println("cost:" + stopwatch.elapsed(TimeUnit.MILLISECONDS));
      result.setCode(((Response)response).getCode());
      result.setResponseMsg(((Response)response).getResponseMsg());
    }

    @Override
    public void onError(Exception exception) {
      System.out.println(exception.getMessage());
    }
  });
  Thread.sleep(50);
  System.out.println("final result:" + result);
  Assert.assertTrue(result.getCode() == 200);
  Assert.assertTrue(responseMsg.equals(result.getResponseMsg()));
}
 
Example #2
Source File: ThriftTest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@Test
public void async() throws Exception {
  TestUtil.setGlobalTracer(tracer);

  startAsyncServer();

  final Factory protocolFactory = new Factory();
  final TNonblockingTransport transport = new TNonblockingSocket("localhost", port);
  final TAsyncClientManager clientManager = new TAsyncClientManager();
  final AsyncClient asyncClient = new AsyncClient(protocolFactory, clientManager, transport);
  final AtomicInteger counter = new AtomicInteger();
  asyncClient.say("Async", "World", new AsyncMethodCallback<String>() {
    @Override
    public void onComplete(final String response) {
      assertEquals("Say Async World", response);
      assertNotNull(GlobalTracer.get().activeSpan());
      counter.incrementAndGet();
    }

    @Override
    public void onError(final Exception exception) {
      exception.printStackTrace();
    }
  });

  await().atMost(15, TimeUnit.SECONDS).until(TestUtil.reportedSpansSize(tracer), equalTo(2));
  assertEquals(1, counter.get());

  final List<MockSpan> spans = tracer.finishedSpans();
  assertEquals(2, spans.size());

  assertNull(tracer.activeSpan());
  verify(tracer, times(2)).buildSpan(anyString());
  verify(tracer, times(1)).inject(any(SpanContext.class), any(Format.class), any());
}
 
Example #3
Source File: ThriftTest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@Test
public void asyncWithoutArgs() throws Exception {
  TestUtil.setGlobalTracer(tracer);

  startAsyncServer();

  final Factory protocolFactory = new Factory();

  final TNonblockingTransport transport = new TNonblockingSocket("localhost", port);
  final TAsyncClientManager clientManager = new TAsyncClientManager();
  final AsyncClient asyncClient = new AsyncClient(protocolFactory, clientManager, transport);
  final AtomicInteger counter = new AtomicInteger();
  asyncClient.withoutArgs(new AsyncMethodCallback<String>() {
    @Override
    public void onComplete(final String response) {
      assertEquals("no args", response);
      assertNotNull(GlobalTracer.get().activeSpan());
      counter.incrementAndGet();
    }

    @Override
    public void onError(final Exception exception) {
      exception.printStackTrace();
    }
  });

  await().atMost(15, TimeUnit.SECONDS).until(TestUtil.reportedSpansSize(tracer), equalTo(2));
  assertEquals(1, counter.get());

  final List<MockSpan> spans = tracer.finishedSpans();
  assertEquals(2, spans.size());

  assertNull(tracer.activeSpan());
  verify(tracer, times(2)).buildSpan(anyString());
  verify(tracer, times(1)).inject(any(SpanContext.class), any(Format.class), any());
}
 
Example #4
Source File: ThriftTest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@Test
public void asyncMany() throws Exception {
  TestUtil.setGlobalTracer(tracer);

  startAsyncServer();

  final AtomicInteger counter = new AtomicInteger();
  for (int i = 0; i < 4; ++i) {
    final Factory protocolFactory = new Factory();
    final TNonblockingTransport transport = new TNonblockingSocket("localhost", port);
    final TAsyncClientManager clientManager = new TAsyncClientManager();
    final AsyncClient asyncClient = new AsyncClient(protocolFactory, clientManager, transport);
    asyncClient.withDelay(1, new AsyncMethodCallback<String>() {
      @Override
      public void onComplete(final String response) {
        assertEquals("delay 1", response);
        assertNotNull(GlobalTracer.get().activeSpan());
        counter.incrementAndGet();
      }

      @Override
      public void onError(final Exception exception) {
        exception.printStackTrace();
      }
    });
  }

  await().atMost(15, TimeUnit.SECONDS).until(TestUtil.reportedSpansSize(tracer), equalTo(8));
  assertEquals(4, counter.get());

  final List<MockSpan> spans = tracer.finishedSpans();
  assertEquals(8, spans.size());

  assertNull(tracer.activeSpan());
  verify(tracer, times(8)).buildSpan(anyString());
  verify(tracer, times(4)).inject(any(SpanContext.class), any(Format.class), any());
}
 
Example #5
Source File: ThriftTest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@Test
public void oneWayAsync() throws Exception {
  TestUtil.setGlobalTracer(tracer);

  startAsyncServer();

  final Factory protocolFactory = new Factory();
  final TNonblockingTransport transport = new TNonblockingSocket("localhost", port);
  final TAsyncClientManager clientManager = new TAsyncClientManager();
  final AsyncClient asyncClient = new AsyncClient(protocolFactory, clientManager, transport);
  final AtomicInteger counter = new AtomicInteger();
  asyncClient.oneWay(new AsyncMethodCallback<Void>() {
    @Override
    public void onComplete(final Void response) {
      assertNotNull(GlobalTracer.get().activeSpan());
      counter.incrementAndGet();
    }

    @Override
    public void onError(final Exception exception) {
      exception.printStackTrace();
    }
  });

  await().atMost(15, TimeUnit.SECONDS).until(TestUtil.reportedSpansSize(tracer), equalTo(2));
  assertEquals(1, counter.get());

  final List<MockSpan> spans = tracer.finishedSpans();
  assertEquals(2, spans.size());

  assertNull(tracer.activeSpan());
  verify(tracer, times(2)).buildSpan(anyString());
  verify(tracer, times(1)).inject(any(SpanContext.class), any(Format.class), any());
}
 
Example #6
Source File: ServerTest.java    From ikasoa with MIT License 5 votes vote down vote up
@Test
public void testAysncThriftServerImpl() {
	int serverPort = ServerUtil.getNewPort();
	ThriftServerConfiguration thriftServerConfiguration = new ThriftServerConfiguration();
	thriftServerConfiguration.setProtocolFactory(new TCompactProtocol.Factory());
	thriftServerConfiguration.setProcessorFactory(new TProcessorFactory(processor));
	thriftServerConfiguration.setServerArgsAspect(new ServerArgsAspect() {
		@Override
		public TThreadPoolServer.Args tThreadPoolServerArgsAspect(TThreadPoolServer.Args args) {
			args.stopTimeoutVal = 1;
			return args;
		}
	});
	Factory factory = new GeneralFactory(thriftServerConfiguration);
	ThriftServer thriftServer = factory.getThriftServer(serverName, serverPort, processor);
	thriftServer.run();
	waiting();
	try {
		ThriftSimpleService.AsyncClient thriftClient = new ThriftSimpleService.AsyncClient(
				new TCompactProtocol.Factory(), new TAsyncClientManager(),
				new TNonblockingSocket(TestConstants.LOCAL_HOST, serverPort));
		thriftClient.get(TestConstants.TEST_STRING, new TestCallback());
		waiting();
	} catch (Exception e) {
		fail();
	} finally {
		thriftServer.stop();
	}
}
 
Example #7
Source File: AsyncEchoTestClient.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Override
public void verifyTraces(PluginTestVerifier verifier, String expectedMessage) throws Exception {
    final InetSocketAddress socketAddress = this.environment.getServerAddress();
    final String hostName = SocketAddressUtils.getHostNameFirst(socketAddress);
    // refer to com.navercorp.pinpoint.plugin.thrift.ThriftUtils#getHostPort
    final String remoteAddress = HostAndPort.toHostAndPortString(hostName, socketAddress.getPort());
    // ********** Asynchronous Traces
    // SpanEvent - Asynchronous Invocation
    ExpectedTrace asyncInvocationTrace = event("ASYNC", "Asynchronous Invocation");

    // SpanEvent - TAsyncMethodCall.cleanUpAndFireCallback
    Method cleanUpAndFireCallback = TAsyncMethodCall.class.getDeclaredMethod("cleanUpAndFireCallback",
            SelectionKey.class);
    ExpectedTrace cleanUpAndFireCallbackTrace = event("THRIFT_CLIENT_INTERNAL", cleanUpAndFireCallback);

    // SpanEvent - TServiceClient.receiveBase
    Method receiveBase = TServiceClient.class.getDeclaredMethod("receiveBase", TBase.class, String.class);
    ExpectedAnnotation thriftResult = Expectations.annotation("thrift.result", "echo_result(success:"
            + expectedMessage + ")");
    ExpectedTrace receiveBaseTrace = event("THRIFT_CLIENT_INTERNAL", // ServiceType
            receiveBase, // Method
            thriftResult // Annotation("thrift.result")
    );

    // ********** Root trace for Asynchronous traces
    // SpanEvent - TAsyncClientManager.call
    Method call = TAsyncClientManager.class.getDeclaredMethod("call", TAsyncMethodCall.class);
    ExpectedAnnotation thriftUrl = Expectations.annotation("thrift.url",
            remoteAddress + "/com/navercorp/pinpoint/plugin/thrift/dto/EchoService/echo");
    ExpectedTrace callTrace = event("THRIFT_CLIENT", // ServiceType
            call, // Method
            null, // rpc
            null, // endPoint
            remoteAddress, // destinationId
            thriftUrl // Annotation("thrift.url")
    );
    verifier.verifyTrace(async(callTrace, asyncInvocationTrace, cleanUpAndFireCallbackTrace, receiveBaseTrace));
}
 
Example #8
Source File: DemoClientTraditionalTEST.java    From nettythrift with Apache License 2.0 4 votes vote down vote up
@Test
public void test_AsyncClient() throws Throwable {
	Random rnd = new Random(System.nanoTime());

	TProtocolFactory[] protfacs = new TProtocolFactory[] { new TCompactProtocol.Factory(),
			new TBinaryProtocol.Factory(), new TJSONProtocol.Factory(),
			new TSimpleJSONProtocol.Factory(TCalculator.Iface.class, false) };

	TProtocolFactory protocolFactory = protfacs[rnd.nextInt(protfacs.length)];

	System.out.println("protocolFactory: " + protocolFactory);

	TAsyncClientManager clientManager = new TAsyncClientManager();
	TNonblockingTransport transport = new TNonblockingSocket(HOST, PORT);
	TCalculator.AsyncClient client = new TCalculator.AsyncClient(protocolFactory, clientManager, transport);
	final int num1 = rnd.nextInt(Integer.MAX_VALUE / 2 - 1);
	final int num2 = rnd.nextInt(Integer.MAX_VALUE / 2 - 1);

	final CountDownLatch latch = new CountDownLatch(1);
	final Throwable[] exceptions = new Throwable[1];
	AsyncMethodCallback<TCalculator.AsyncClient.add_call> resultHandler = new AsyncMethodCallback<TCalculator.AsyncClient.add_call>() {
		@Override
		public void onComplete(TCalculator.AsyncClient.add_call response) {
			System.out.println("onComplete!");
			try {
				int result = response.getResult();
				Assert.assertEquals(num1 + num2, result);
			} catch (Throwable e) {
				exceptions[0] = e;
			} finally {
				latch.countDown();
			}
		}

		@Override
		public void onError(Exception exception) {
			System.err.println("onError!");
			exception.printStackTrace();
			latch.countDown();
		}

	};
	client.add(num1, num2, resultHandler);
	latch.await();
	transport.close();
	if (exceptions[0] != null) {
		throw exceptions[0];
	}
}
 
Example #9
Source File: AsyncServiceClientImpl.java    From ikasoa with MIT License 4 votes vote down vote up
public AsyncServiceClientImpl(TProtocolFactory protocolFactory, TAsyncClientManager manager,
		TNonblockingTransport transport) {
	super(protocolFactory, manager, transport);
}
 
Example #10
Source File: AsyncServiceClientImpl.java    From ikasoa with MIT License 4 votes vote down vote up
public AsyncServiceClientImpl(TProtocolFactory protocolFactory, TNonblockingTransport transport)
		throws IOException {
	super(protocolFactory, new TAsyncClientManager(), transport);
}
 
Example #11
Source File: AsyncClient.java    From ThriftBook with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) 
        throws IOException, InterruptedException, TException {
    //Async client and I/O stack setup
    TNonblockingSocket trans_ep = new TNonblockingSocket("localhost", 9090);
    TAsyncClientManager client_man = new TAsyncClientManager();
    TradeReporting.TradeHistory.AsyncClient client = 
        new TradeReporting.TradeHistory.AsyncClient(new TBinaryProtocol.Factory(),
                                                    client_man, trans_ep);

    //get_last_sale() async callback handler
    WaitableCallback<TradeReport> wc = 
            new WaitableCallback<TradeReport>() {

        @Override
        public void onComplete(TradeReport tr) {
            try {
                System.out.println("[Client] received [" + tr.seq_num + "] " + 
                                   tr.symbol + " : " + tr.size + " @ " + tr.price);
            } finally {
                complete();
            }
        }
    };

    //Make async calls
    wc.reset();
    client.get_last_sale("IBM", wc);
    System.out.println("[Client] get_last_sale() executing asynch...");
    wc.wait(500);
    wc.reset();
    client.get_last_sale("F", wc);
    wc.wait(25000);

    //Make an async call which will time out
    client.setTimeout(1000);
    wc.reset();
    client.get_last_sale("GE", wc);
    wc.wait(5000);

    //Shutdown async client manager and close network socket
    client_man.stop();
    trans_ep.close();
}