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

ch.loway.oss.ari4java.tools.AriAsyncHandler Maven / Gradle / Ivy

There is a newer version: 0.17.0
Show newest version

package ch.loway.oss.ari4java.tools;

import com.fasterxml.jackson.core.type.TypeReference;

/**
 * Delegate for handling asynchronous ARI responses.
 * 
 * 
 */
public class AriAsyncHandler implements HttpResponseHandler {
    private final AriCallback callback;
    private Class klazz;
    private TypeReference klazzType;
    private long lastResponseTime = 0;

    public AriAsyncHandler(AriCallback callback, Class klazz) {
        this.callback = callback;
        this.klazz = klazz;
    }

    public AriAsyncHandler(AriCallback callback, TypeReference klazzType) {
        this.callback = callback;
        this.klazzType = klazzType;
    }

    public AriCallback getCallback() {
        return callback;
    }

    void handleResponse(String json) {
        try {
            T result;
            if (Void.class.equals(klazz)) {
                result = null;
            } else if (klazz != null) {
                result = BaseAriAction.deserializeJson(json, klazz);
            } else {
                result = BaseAriAction.deserializeJson(json, klazzType);
            }
            this.callback.onSuccess(result);
        } catch (RestException e) {
            this.callback.onFailure(e);
        }
    }

    @Override
    public void onChReadyToWrite() {
        lastResponseTime = System.currentTimeMillis();
        connectionEvent(AriConnectionEvent.WS_CONNECTED);
    }

    private void connectionEvent(AriConnectionEvent event) {
        if (this.callback instanceof AriWSCallback) {
            ((AriWSCallback) this.callback).onConnectionEvent(event);
        }
    }

    @Override
    public void onResponseReceived() {
        lastResponseTime = System.currentTimeMillis();
    }

    @Override
    public void onDisconnect() {
        connectionEvent(AriConnectionEvent.WS_DISCONNECTED);
    }

    @Override
    public void onSuccess(String response) {
        handleResponse(response);
    }

    @Override
    public void onSuccess(byte[] response) {
        this.callback.onSuccess((T) response);
    }

    @Override
    public void onFailure(Throwable e) {
        if (e instanceof RestException) {
            this.callback.onFailure((RestException) e);
        } else {
            this.callback.onFailure(new RestException(e));
        }
    }

    @Override
    public long getLastResponseTime() {
        return lastResponseTime;
    }

    @Override
    public Class getType() {
        return klazz;
    }
}

// $Log$
//




© 2015 - 2024 Weber Informatics LLC | Privacy Policy