All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.dongliu.prettypb.rpc.client.ClientCallTask Maven / Gradle / Ivy

There is a newer version: 0.3.5
Show newest version
package net.dongliu.prettypb.rpc.client;

import net.dongliu.prettypb.rpc.common.MethodInfo;
import net.dongliu.prettypb.rpc.common.Task;
import net.dongliu.prettypb.rpc.exception.ServiceException;
import net.dongliu.prettypb.runtime.include.RpcCallback;

import java.util.concurrent.TimeoutException;

/**
 * client rpc request task
 *
 * @author Dong Liu
 */
public class ClientCallTask extends Task {

    private final RpcCallback callback;
    private final MethodInfo methodInfo;

    /**
     * not null if error happened
     */
    private volatile Exception exception;

    public ClientCallTask(int correlationId, MethodInfo methodInfo, RpcCallback callback,
                          int timeout) {
        super(correlationId, timeout, System.currentTimeMillis());
        this.methodInfo = methodInfo;
        this.callback = callback;
    }

    public void handleResponse(Object response) {
        callback.onFinished(response);
    }

    public void handleFailure(Exception e) {
        this.exception = e;
        callback.onError(e);
    }

    public MethodInfo getMethodInfo() {
        return methodInfo;
    }

    public RpcCallback getCallback() {
        return callback;
    }

    /**
     * exception mes
     *
     * @return null if succeed, msg if failed
     */
    public Exception getException() {
        return exception;
    }

    public boolean isAsync() {
        return methodInfo.getServiceInfo().isAsync();
    }

    @Override
    public void onTimeout() {
        callback.onError(new TimeoutException("rpc call timeout"));
    }

    @Override
    public void onClosed() {
        handleFailure(new ServiceException("Rpc channel closed"));
    }
}