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

com.fitbur.github.dockerjava.jaxrs.async.AbstractCallbackNotifier Maven / Gradle / Ivy

There is a newer version: 1.0.0
Show newest version
/*
 * Created on 17.06.2015
 */
package com.fitbur.github.dockerjava.jaxrs.async;

import static com.fitbur.google.com.fitburmon.base.Preconditions.checkNotNull;

import java.io.InputStream;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import javax.ws.rs.ProcessingException;
import javax.ws.rs.client.Invocation.Builder;
import javax.ws.rs.core.Response;

import com.fitbur.github.dockerjava.api.async.ResultCallback;
import com.fitbur.github.dockerjava.core.async.ResponseStreamProcessor;
import com.fitbur.github.dockerjava.jaxrs.util.WrappedResponseInputStream;

public abstract class AbstractCallbackNotifier implements Callable {

    private final ResponseStreamProcessor responseStreamProcessor;

    private final ResultCallback resultCallback;

    protected final Builder requestBuilder;

    protected AbstractCallbackNotifier(ResponseStreamProcessor responseStreamProcessor,
            ResultCallback resultCallback, Builder requestBuilder) {
        checkNotNull(requestBuilder, "An WebTarget must be provided");
        checkNotNull(responseStreamProcessor, "A ResponseStreamProcessor must be provided");
        this.responseStreamProcessor = responseStreamProcessor;
        this.resultCallback = resultCallback;
        this.requestBuilder = requestBuilder;
    }

    @Override
    public Void call() throws Exception {

        Response response = null;

        try {
            response = response();
        } catch (ProcessingException e) {
            if (resultCallback != null) {
                resultCallback.onError(e.getCause());
            }
            return null;
        } catch (Exception e) {
            if (resultCallback != null) {
                resultCallback.onError(e);
            }
            return null;
        }

        try {
            InputStream inputStream = new WrappedResponseInputStream(response);

            if (resultCallback != null)
                responseStreamProcessor.processResponseStream(inputStream, resultCallback);

            return null;
        } catch (Exception e) {
            if (resultCallback != null) {
                resultCallback.onError(e);
            }

            return null;
        }
    }

    protected abstract Response response();

    public static  Future startAsyncProcessing(AbstractCallbackNotifier callbackNotifier) {

        ExecutorService executorService = Executors.newSingleThreadExecutor();
        Future response = executorService.submit(callbackNotifier);
        executorService.shutdown();
        return response;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy