Example usage for org.apache.thrift.async AsyncMethodCallback onError

List of usage examples for org.apache.thrift.async AsyncMethodCallback onError

Introduction

In this page you can find the example usage for org.apache.thrift.async AsyncMethodCallback onError.

Prototype

void onError(Exception exception);

Source Link

Document

This method will be called when there is either an unexpected client-side exception like an IOException or else when the remote method raises an exception, either declared in the IDL or due to an unexpected server-side error.

Usage

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/*from  w  w  w . j  av  a2s  . c  o 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.ThriftClientCodec.java

License:Apache License

@SuppressWarnings({ "rawtypes", "unchecked" })
@Override/*  w  ww . j  a  v a 2  s.co m*/
public <T> void prepareRequest(Method method, Object[] args, Promise<T> resultPromise) {
    requireNonNull(method, "method");
    requireNonNull(resultPromise, "resultPromise");
    final ThriftMethod thriftMethod = methodMap.get(method.getName());
    if (thriftMethod == null) {
        throw new IllegalStateException("Thrift method not found: " + method.getName());
    }

    if (isAsyncClient) {
        AsyncMethodCallback callback = ThriftMethod.asyncCallback(args);
        if (callback != null) {
            resultPromise.addListener(future -> {
                if (future.isSuccess()) {
                    callback.onComplete(future.getNow());
                } else {
                    Exception decodedException = decodeException(future.cause(),
                            thriftMethod.declaredThrowableException());
                    callback.onError(decodedException);
                }
            });
        }
    }
}

From source file:com.linecorp.armeria.client.thrift.ThriftClientInvocationHandler.java

License:Apache License

private static void invokeOnError(AsyncMethodCallback<Object> callback, Throwable cause) {
    callback.onError(cause instanceof Exception ? (Exception) cause : new UndeclaredThrowableException(cause));
}

From source file:com.twitter.common.thrift.callers.CallerDecorator.java

License:Apache License

/**
 * Convenience method for invoking the method and shunting the capture into the callback if
 * the call is asynchronous.//w  w w .j  a v a  2s.  co m
 *
 * @param method The method being invoked.
 * @param args The arguments to call {@code method} with.
 * @param callback The callback to use if the method is asynchronous.
 * @param capture The result capture to notify of the call result.
 * @param connectTimeoutOverride Optional override for the default connection timeout.
 * @return The return value from invoking the method.
 * @throws Throwable Exception, as prescribed by the method's contract.
 */
protected final Object invoke(Method method, Object[] args, @Nullable AsyncMethodCallback callback,
        @Nullable final ResultCapture capture, @Nullable Amount<Long, Time> connectTimeoutOverride)
        throws Throwable {

    // Swap the wrapped callback out for ours.
    if (callback != null) {
        callback = new WrappedMethodCallback(callback, capture);
    }

    try {
        Object result = decoratedCaller.call(method, args, callback, connectTimeoutOverride);
        if (callback == null && capture != null)
            capture.success();

        return result;
    } catch (Throwable t) {
        // We allow this one to go to both sync and async captures.
        if (callback != null) {
            callback.onError(t);
            return null;
        } else {
            if (capture != null)
                capture.fail(t);
            throw t;
        }
    }
}

From source file:com.twitter.common.thrift.callers.RetryingCaller.java

License:Apache License

@Override
public Object call(final Method method, final Object[] args, @Nullable final AsyncMethodCallback callback,
        @Nullable final Amount<Long, Time> connectTimeoutOverride) throws Throwable {
    final AtomicLong retryCounter = stats.get(method);
    final AtomicInteger attempts = new AtomicInteger();
    final List<Throwable> exceptions = Lists.newArrayList();

    final ResultCapture capture = new ResultCapture() {
        @Override/*  ww  w  . j  a  v a  2 s  .c o m*/
        public void success() {
            // No-op.
        }

        @Override
        public boolean fail(Throwable t) {
            if (!isRetryable(t)) {
                if (debug) {
                    LOG.warning(String.format(
                            "Call failed with un-retryable exception of [%s]: %s, previous exceptions: %s",
                            t.getClass().getName(), t.getMessage(), combineStackTraces(exceptions)));
                }

                return true;
            } else if (attempts.get() >= retries) {
                exceptions.add(t);

                if (debug) {
                    LOG.warning(String.format("Retried %d times, last error: %s, exceptions: %s",
                            attempts.get(), t, combineStackTraces(exceptions)));
                }

                return true;
            } else {
                exceptions.add(t);

                if (isAsync() && attempts.incrementAndGet() <= retries) {
                    try {
                        retryCounter.incrementAndGet();
                        // override connect timeout in ThriftCaller to prevent blocking for a connection
                        // for async retries (since this is within the callback in the selector thread)
                        invoke(method, args, callback, this, NONBLOCKING_TIMEOUT);
                    } catch (Throwable throwable) {
                        return fail(throwable);
                    }
                }

                return false;
            }
        }
    };

    boolean continueLoop;
    do {
        try {
            // If this is an async call, the looping will be handled within the capture.
            return invoke(method, args, callback, capture, connectTimeoutOverride);
        } catch (Throwable t) {
            if (!isRetryable(t)) {
                Throwable propagated = t;

                if (!exceptions.isEmpty() && (t instanceof TResourceExhaustedException)) {
                    // If we've been trucking along through retries that have had remote call failures
                    // and we suddenly can't immediately get a connection on the next retry, throw the
                    // previous remote call failure - the idea here is that the remote call failure is
                    // more interesting than a transient inability to get an immediate connection.
                    propagated = exceptions.remove(exceptions.size() - 1);
                }

                if (isAsync()) {
                    callback.onError(propagated);
                } else {
                    throw propagated;
                }
            }
        }

        continueLoop = !isAsync() && attempts.incrementAndGet() <= retries;
        if (continueLoop)
            retryCounter.incrementAndGet();
    } while (continueLoop);

    Throwable lastRetriedException = Iterables.getLast(exceptions);
    if (debug) {
        if (!exceptions.isEmpty()) {
            LOG.warning(String.format("Retried %d times, last error: %s, previous exceptions: %s",
                    attempts.get(), lastRetriedException, combineStackTraces(exceptions)));
        } else {
            LOG.warning(String.format("Retried 1 time, last error: %s", lastRetriedException));
        }
    }

    if (!isAsync())
        throw lastRetriedException;
    return null;
}

From source file:com.twitter.common.thrift.callers.ThriftCaller.java

License:Apache License

private static Object invokeMethod(Object target, Method method, Object[] args, AsyncMethodCallback callback,
        final ResultCapture capture) throws Throwable {

    // Swap the wrapped callback out for ours.
    if (callback != null) {
        callback = new WrappedMethodCallback(callback, capture);

        List<Object> argsList = Lists.newArrayList(args);
        argsList.add(callback);/*ww  w . j  a  va2  s  . c om*/
        args = argsList.toArray();
    }

    try {
        Object result = method.invoke(target, args);
        if (callback == null)
            capture.success();

        return result;
    } catch (InvocationTargetException t) {
        // We allow this one to go to both sync and async captures.
        if (callback != null) {
            callback.onError(t.getCause());
            return null;
        } else {
            capture.fail(t.getCause());
            throw t.getCause();
        }
    }
}

From source file:com.vmware.photon.controller.common.thrift.ClientProxyImpl.java

License:Open Source License

private void handleException(AsyncMethodCallback callback, Throwable cause) {
    checkNotNull(callback);/*from  ww w.  j  a va2 s .c  o m*/

    if (cause instanceof Exception) {
        callback.onError((Exception) cause);
    } else {
        callback.onError(new RuntimeException(cause));
    }
}

From source file:com.vmware.photon.controller.deployer.dcp.mock.AgentControlClientMock.java

License:Open Source License

@Override
public void provision(List<String> datastores, Set<String> imageDatastoreNames, boolean usedForVMs,
        List<String> networks, String hostAddress, int hostPort, double memoryOvercommit,
        String loggingEndpoint, String logLevel, StatsPluginConfig statsPluginConfig, boolean managementOnly,
        String ntpEndpoint, String hostId, String deploymentId,
        AsyncMethodCallback<AgentControl.AsyncClient.provision_call> handler) {

    logger.info("Host provision complete invocation");

    if (null != provisionFailure) {
        handler.onError(provisionFailure);

    } else if (null != provisionResultCode) {
        AgentControl.AsyncClient.provision_call provisionCall = mock(
                AgentControl.AsyncClient.provision_call.class);
        ProvisionResponse provisionResponse = new ProvisionResponse();
        provisionResponse.setResult(provisionResultCode);

        try {/*from w  w  w  .j  a  v  a2 s  . com*/
            when(provisionCall.getResult()).thenReturn(provisionResponse);
        } catch (TException e) {
            throw new RuntimeException("Failed to mock provisionCall.getResult");
        }

        handler.onComplete(provisionCall);

    } else {
        throw new IllegalStateException("No result or failure specified for provision");
    }
}

From source file:com.vmware.photon.controller.deployer.dcp.mock.AgentControlClientMock.java

License:Open Source License

@Override
public void upgrade(AsyncMethodCallback<AgentControl.AsyncClient.upgrade_call> handler) {

    logger.info("Host upgrade complete invocation");

    if (null != upgradeFailure) {
        handler.onError(upgradeFailure);

    } else if (null != upgradeResultCode) {
        AgentControl.AsyncClient.upgrade_call upgradeCall = mock(AgentControl.AsyncClient.upgrade_call.class);
        UpgradeResponse upgradeResponse = new UpgradeResponse();
        upgradeResponse.setResult(upgradeResultCode);

        try {/*  ww  w .  ja v a 2s  .c  o  m*/
            when(upgradeCall.getResult()).thenReturn(upgradeResponse);
        } catch (TException e) {
            throw new RuntimeException("Failed to mock upgradeCall.getResult");
        }

        handler.onComplete(upgradeCall);

    } else {
        throw new IllegalStateException("No result or failure specified for upgrade");
    }
}

From source file:com.vmware.photon.controller.deployer.dcp.mock.AgentControlClientMock.java

License:Open Source License

@Override
public void getAgentStatus(AsyncMethodCallback<AgentControl.AsyncClient.get_agent_status_call> handler) {

    logger.info("Agent get status complete invocation");

    if (null != getAgentStatusFailure) {
        handler.onError(getAgentStatusFailure);

    } else if (null != agentStatusCode) {
        AgentControl.AsyncClient.get_agent_status_call getAgentStatusCall = mock(
                AgentControl.AsyncClient.get_agent_status_call.class);
        AgentStatusResponse agentStatusResponse = new AgentStatusResponse();
        agentStatusResponse.setStatus(agentStatusCode);
        agentStatusResponse.setStatusIsSet(true);

        try {// w w  w  .j a  v a  2 s . co m
            when(getAgentStatusCall.getResult()).thenReturn(agentStatusResponse);
        } catch (TException e) {
            throw new RuntimeException("Failed to mock getAgentStatusCall.getResult");
        }

        handler.onComplete(getAgentStatusCall);

    } else {
        throw new IllegalStateException("No result or failure specified for getAgentStatus");
    }
}