List of usage examples for org.apache.thrift.async AsyncMethodCallback AsyncMethodCallback
AsyncMethodCallback
From source file:com.kurento.kmf.connector.ThriftConnectorJsonRpcHandler.java
License:Open Source License
private void sendRequest(final Transaction transaction, final Request<JsonObject> request, final boolean retry) { final AsyncClient client = clientPool.acquireAsync(); final boolean subscribeRequest; if (request.getMethod().equals("subscribe")) { request.getParams().addProperty("ip", config.getHandlerAddress()); request.getParams().addProperty("port", config.getHandlerPort()); subscribeRequest = true;/*from ww w . ja v a 2s .co m*/ } else { subscribeRequest = false; } try { client.invokeJsonRpc(request.toString(), new AsyncMethodCallback<invokeJsonRpc_call>() { @Override public void onComplete(invokeJsonRpc_call response) { clientPool.release(client); if (request.getId() != null) { requestOnComplete(response, transaction, subscribeRequest); } } @Override public void onError(Exception exception) { clientPool.release(client); LOG.error("Error on release", exception); if (retry && exception instanceof ConnectException) { sendRequest(transaction, request, false); } else { requestOnError(exception, transaction); } } }); } catch (Exception e) { LOG.error("Exception while executing a command" + " in thrift interface of the MediaServer", e); } }
From source file:com.kurento.kmf.thrift.pool.AsyncClientWithValidation.java
License:Open Source License
@Override public void invokeJsonRpc(String request, final AsyncMethodCallback<invokeJsonRpc_call> resultHandler) throws TException { // FIXME: Implement retries super.invokeJsonRpc(request, new AsyncMethodCallback<KmsMediaServerService.AsyncClient.invokeJsonRpc_call>() { @Override/* w ww. j ava 2 s .co m*/ public void onComplete(KmsMediaServerService.AsyncClient.invokeJsonRpc_call response) { resultHandler.onComplete(response); } @Override public void onError(Exception exception) { resultHandler.onError(exception); } }); }
From source file:com.linecorp.armeria.client.thrift.ThriftOverHttpClientTest.java
License:Apache License
@Test(timeout = 10000) public void testHelloServiceAsync() throws Exception { HelloService.AsyncIface client = Clients.newClient(clientFactory(), getURI(Handlers.HELLO), Handlers.HELLO.asyncIface(), clientOptions); final int testCount = 10; final BlockingQueue<AbstractMap.SimpleEntry<Integer, ?>> resultQueue = new LinkedBlockingDeque<>(testCount); for (int i = 0; i < testCount; i++) { final int num = i; client.hello("kukuman" + num, new AsyncMethodCallback<String>() { @Override// w w w . j a va 2 s . co m public void onComplete(String response) { assertThat(resultQueue.add(new AbstractMap.SimpleEntry<>(num, response))).isTrue(); } @Override public void onError(Exception exception) { assertThat(resultQueue.add(new AbstractMap.SimpleEntry<>(num, exception))).isTrue(); } }); } for (int i = 0; i < testCount; i++) { AbstractMap.SimpleEntry<Integer, ?> pair = resultQueue.take(); assertThat(pair.getValue()).isEqualTo("Hello, kukuman" + pair.getKey() + '!'); } }
From source file:com.linecorp.armeria.server.thrift.ThriftCallService.java
License:Apache License
private static void invokeAsynchronously(Object impl, ThriftFunction func, TBase<TBase<?, ?>, TFieldIdEnum> args, DefaultRpcResponse reply) throws TException { final AsyncProcessFunction<Object, TBase<TBase<?, ?>, TFieldIdEnum>, Object> f = func.asyncFunc(); f.start(impl, args, new AsyncMethodCallback<Object>() { @Override//from w w w .ja v a 2s. c om public void onComplete(Object response) { if (func.isOneWay()) { reply.complete(null); } else { reply.complete(response); } } @Override public void onError(Exception e) { reply.completeExceptionally(e); } }); }
From source file:com.linecorp.armeria.server.thrift.ThriftServiceInvocationHandler.java
License:Apache License
private void invokeAsynchronously(ThriftServiceInvocationContext ctx, Promise<Object> promise) { final ThriftFunction func = ctx.func; final AsyncProcessFunction<Object, TBase<TBase<?, ?>, TFieldIdEnum>, Object> f = func.asyncFunc(); try {//w w w . j a va 2 s . co m f.start(service, ctx.args, new AsyncMethodCallback<Object>() { @Override public void onComplete(Object response) { if (func.isOneway()) { safeSetSuccess(ctx, promise, null); return; } try { TBase<TBase<?, ?>, TFieldIdEnum> result = func.newResult(); func.setSuccess(result, response); safeSetSuccess(ctx, promise, result); } catch (Throwable t) { safeSetFailure(ctx, promise, t); } } @Override public void onError(Exception e) { safeSetFailure(ctx, promise, e); } }); } catch (Throwable t) { safeSetFailure(ctx, promise, t); } }
From source file:com.twitter.common.thrift.ThriftFactoryTest.java
License:Apache License
@Test public void testCreateAsync() throws IOException, InterruptedException, ThriftFactory.ThriftFactoryException { final String responseHolder[] = new String[] { null }; final CountDownLatch done = new CountDownLatch(1); AsyncMethodCallback<String> callback = new AsyncMethodCallback<String>() { @Override/*ww w . ja v a 2 s. com*/ public void onComplete(String response) { responseHolder[0] = response; done.countDown(); } @Override public void onError(Throwable throwable) { responseHolder[0] = throwable.toString(); done.countDown(); } }; final Thrift<AsyncIface> thrift = ThriftFactory.create(GoodService.AsyncIface.class) .withMaxConnectionsPerEndpoint(1).useFramedTransport(true) .buildAsync(ImmutableSet.of(new InetSocketAddress(1234))); addTearDown(new TearDown() { @Override public void tearDown() { thrift.close(); } }); GoodService.AsyncIface client = thrift.builder().blocking().create(); client.doWork(callback); assertTrue("wasn't called back in time, callback got " + responseHolder[0], done.await(5000, TimeUnit.MILLISECONDS)); assertEquals(GoodService.DONE, responseHolder[0]); }
From source file:com.vmware.photon.controller.apife.resources.TopologyResource.java
License:Open Source License
private void getAgentResources(final ConcurrentHashMap<String, List<Resource>> responses, final CountDownLatch done, final String agent) throws TException, IOException { final ServerSet serverSet = serverSetFactory.createHostServerSet(agent); final ClientPool<Host.AsyncClient> clientPool = clientPoolFactory.create(serverSet, new ClientPoolOptions() .setServiceName("Host").setMaxClients(1).setMaxWaiters(1).setTimeout(30, TimeUnit.SECONDS)); Host.AsyncClient client = clientProxyFactory.create(clientPool).get(); client.setTimeout(30000);//from w w w. j a v a 2s . c o m client.get_resources(new GetResourcesRequest(), new AsyncMethodCallback<Host.AsyncClient.get_resources_call>() { @Override public void onComplete(Host.AsyncClient.get_resources_call response) { try { responses.put(agent, response.getResult().getResources()); cleanup(serverSet, clientPool); done.countDown(); } catch (TException e) { throw new RuntimeException(e); } } @Override public void onError(Exception exception) { logger.warn("Couldn't get resources from agent: {}", agent, exception); cleanup(serverSet, clientPool); done.countDown(); } private void cleanup(ServerSet serverSet, ClientPool<Host.AsyncClient> clientPool) { clientPool.close(); try { serverSet.close(); } catch (IOException e) { logger.warn("Unexpected IOException while closing server set: ", e); } } }); }
From source file:com.vmware.photon.controller.cloudstore.dcp.entity.HostService.java
License:Open Source License
/** * This method pings the agent on the host identified by the host document and updates the agent state in the host * document if it determines a change in agent state. * The thrift call to ping the agent is implemented as a runnable, which will be scheduled to run in the future. * The time after which it runs is determined by a random integer between 1 and maxPingWaitTimeMillis. This is needed * to achieve a randomized distribution of the polling task so that we reduce the number of concurrent connections. * @param maintenance/*from w w w. j a va 2s.co m*/ * @param hostState */ private void pingHost(Operation maintenance, State hostState) { final Service service = this; try { AgentControlClient agentControlClient = ((AgentControlClientProvider) getHost()) .getAgentControlClient(); agentControlClient.setIpAndPort(hostState.hostAddress, hostState.agentPort); agentControlClient.ping(new AsyncMethodCallback<AgentControl.AsyncClient.ping_call>() { @Override public void onComplete(AgentControl.AsyncClient.ping_call pingCall) { // Get the host metadata if we have reached the UPDATE_HOST_METADATA_INTERVAL if (System.currentTimeMillis() - lastHostMetadataUpdateTime >= UPDATE_HOST_METADATA_INTERVAL) { lastHostMetadataUpdateTime = System.currentTimeMillis(); getHostConfig(maintenance, hostState); } else { updateHostState(maintenance, hostState, AgentState.ACTIVE); } } @Override public void onError(Exception e) { ServiceUtils.logInfo(service, "Failed to ping " + hostState.hostAddress + ", will be marked as missing:" + e.getMessage()); updateHostState(maintenance, hostState, AgentState.MISSING); } }); } catch (Exception ex) { ServiceUtils.logWarning(this, "Unexpected exception while pinging " + hostState.hostAddress + ", will be " + "marked as missing:" + ex.getMessage()); updateHostState(maintenance, hostState, AgentState.MISSING); } }
From source file:com.vmware.photon.controller.cloudstore.dcp.entity.HostService.java
License:Open Source License
/** * This method gets the host config (datastores, networks, etc.) from agent. * @param hostState/*from www .ja va 2 s.com*/ */ private void getHostConfig(Operation maintenance, State hostState) { try { final Service service = this; HostClient hostClient = ((HostClientProvider) getHost()).getHostClient(); hostClient.setIpAndPort(hostState.hostAddress, hostState.agentPort); hostClient.getHostConfig(new AsyncMethodCallback<Host.AsyncClient.get_host_config_call>() { @Override public void onComplete(Host.AsyncClient.get_host_config_call getHostConfigCall) { try { GetConfigResponse response = getHostConfigCall.getResult(); HostClient.ResponseValidator.checkGetConfigResponse(response); processHostConfig(maintenance, hostState, response.getHostConfig()); } catch (Throwable t) { ServiceUtils.logWarning(service, "Get host config failed, host metadata will not be updated" + t.getMessage()); updateHostState(maintenance, hostState, AgentState.ACTIVE); } } @Override public void onError(Exception e) { ServiceUtils.logWarning(service, "Get host config failed, host metadata will not be updated" + e.getMessage()); updateHostState(maintenance, hostState, AgentState.ACTIVE); } }); } catch (Exception e) { ServiceUtils.logWarning(this, "Get host config failed, host metadata will not be updated" + e.getMessage()); updateHostState(maintenance, hostState, AgentState.ACTIVE); } }
From source file:com.vmware.photon.controller.cloudstore.xenon.entity.HostService.java
License:Open Source License
/** * This method pings the agent on the host identified by the host document and updates the agent state in the host * document if it determines a change in agent state. * The thrift call to ping the agent is implemented as a runnable, which will be scheduled to run in the future. * The time after which it runs is determined by a random integer between 1 and maxPingWaitTimeMillis. This is needed * to achieve a randomized distribution of the polling task so that we reduce the number of concurrent connections. * * @param maintenance// w w w . ja va2 s . c om * @param hostState */ private void pingHost(Operation maintenance, State hostState) { final Service service = this; try { AgentControlClient agentControlClient = ((AgentControlClientProvider) getHost()) .getAgentControlClient(); agentControlClient.setIpAndPort(hostState.hostAddress, hostState.agentPort); agentControlClient.ping(new AsyncMethodCallback<AgentControl.AsyncClient.ping_call>() { @Override public void onComplete(AgentControl.AsyncClient.ping_call pingCall) { updateHostState(maintenance, hostState, AgentState.ACTIVE); } @Override public void onError(Exception e) { ServiceUtils.logInfo(service, "Failed to ping " + hostState.hostAddress + ", will be marked as missing:" + e.getMessage()); updateHostState(maintenance, hostState, AgentState.MISSING); } }); } catch (Exception ex) { ServiceUtils.logWarning(this, "Unexpected exception while pinging " + hostState.hostAddress + ", will be " + "marked as missing:" + ex.getMessage()); updateHostState(maintenance, hostState, AgentState.MISSING); } }