Search in sources :

Example 56 with Promise

use of org.nustaq.kontraktor.Promise in project kontraktor by RuedigerMoeller.

the class ActorClient method connect.

public IPromise<T> connect(int qsiz, Consumer<Actor> discon) {
    Promise<T> result = new Promise<>();
    try {
        client.connect(writesocket -> {
            Actor facadeProxy = Actors.AsActor(facadeClass, new RemoteScheduler(qsiz));
            facadeProxy.__remoteId = 1;
            AtomicReference<ObjectSocket> socketRef = new AtomicReference<>(writesocket);
            ConnectionRegistry reg = new ConnectionRegistry(coding) {

                @Override
                public Actor getFacadeProxy() {
                    return facadeProxy;
                }

                @Override
                public AtomicReference<ObjectSocket> getWriteObjectSocket() {
                    return socketRef;
                }
            };
            reg.setDisconnectHandler(discon);
            if (coding.getCrossPlatformShortClazzNames() != null)
                reg.getConf().registerCrossPlatformClassMappingUseSimpleName(coding.getCrossPlatformShortClazzNames());
            writesocket.setConf(reg.getConf());
            // ensure running in actor thread
            Actor.current();
            ObjectSink objectSink = new ObjectSink() {

                @Override
                public void receiveObject(ObjectSink sink, Object received, List<IPromise> createdFutures, Object securityContext) {
                    try {
                        reg.receiveObject(socketRef.get(), sink, received, createdFutures, securityContext);
                    } catch (Exception e) {
                        FSTUtil.rethrow(e);
                    }
                }

                @Override
                public void sinkClosed() {
                    reg.disconnect();
                }
            };
            reg.registerRemoteRefDirect(facadeProxy);
            poller.get().scheduleSendLoop(reg).then(() -> {
                objectSink.sinkClosed();
            });
            result.resolve((T) facadeProxy);
            return objectSink;
        });
    } catch (Exception e) {
        if (!result.isSettled())
            result.reject(e);
        else
            e.printStackTrace();
    }
    return result;
}
Also used : RemoteScheduler(org.nustaq.kontraktor.impl.RemoteScheduler) AtomicReference(java.util.concurrent.atomic.AtomicReference) IPromise(org.nustaq.kontraktor.IPromise) Promise(org.nustaq.kontraktor.Promise) Actor(org.nustaq.kontraktor.Actor) List(java.util.List)

Example 57 with Promise

use of org.nustaq.kontraktor.Promise in project kontraktor by RuedigerMoeller.

the class AsyncHttpActor method getContent.

public IPromise<String> getContent(String url, String... headers) {
    if (url == null || url.trim().length() == 0) {
        return reject("invalid url");
    }
    if (!url.startsWith("http")) {
        url = "http://" + url;
    }
    int idx = url.indexOf("#");
    if (idx > 0) {
        url = url.substring(0, idx);
    }
    Promise res = new Promise();
    try {
        get(url, headers).then((response, err) -> {
            if (err != null) {
                res.reject(err);
                return;
            }
            if (response.getStatusLine().getStatusCode() != 200) {
                res.reject(response.getStatusLine().getStatusCode());
                return;
            }
            try {
                res.resolve(readContentString(response));
            } catch (Throwable e) {
                Log.Warn(this, e);
                res.reject(e);
            }
        });
    } catch (Throwable t) {
        t.printStackTrace();
        res.reject(t);
    }
    return res;
}
Also used : IPromise(org.nustaq.kontraktor.IPromise) Promise(org.nustaq.kontraktor.Promise)

Example 58 with Promise

use of org.nustaq.kontraktor.Promise in project kontraktor by RuedigerMoeller.

the class AsyncHttpActor method getContentBytes.

public IPromise<byte[]> getContentBytes(String url, String... headers) {
    if (url == null || url.trim().length() == 0) {
        return reject("invalid url");
    }
    if (!url.startsWith("http")) {
        url = "http://" + url;
    }
    int idx = url.indexOf("#");
    if (idx > 0) {
        url = url.substring(0, idx);
    }
    Promise res = new Promise();
    try {
        get(url, headers).then((response, err) -> {
            if (err != null) {
                res.reject(err);
                return;
            }
            if (response.getStatusLine().getStatusCode() != 200) {
                res.reject(response.getStatusLine().getStatusCode());
                return;
            }
            String enc = null;
            Header[] heads = response.getHeaders("Content-Encoding");
            if (heads != null) {
                for (int i = 0; i < heads.length; i++) {
                    Header header = heads[i];
                    HeaderElement[] elements = header.getElements();
                    if (elements != null) {
                        for (int j = 0; j < elements.length; j++) {
                            HeaderElement element = elements[j];
                            if (enc != null)
                                Log.Error(AsyncHttpActor.class, "unexpected encoding header");
                            enc = element.getName();
                        }
                    }
                }
            }
            try {
                res.resolve(readContentBytes(response, enc));
            } catch (Throwable e) {
                Log.Warn(this, e);
                res.reject(e);
            }
        });
    } catch (Throwable t) {
        t.printStackTrace();
        res.reject(t);
    }
    return res;
}
Also used : IPromise(org.nustaq.kontraktor.IPromise) Promise(org.nustaq.kontraktor.Promise)

Example 59 with Promise

use of org.nustaq.kontraktor.Promise in project kontraktor by RuedigerMoeller.

the class AsyncHttpActor method get.

public IPromise<HttpResponse> get(String url, String... headers) {
    Promise res = new Promise();
    if (url == null) {
        int debug = 1;
    }
    try {
        String cleanedUrl = tryCleanUpUrl(url);
        HttpGet req = new HttpGet(cleanedUrl);
        setHeaders(req, headers);
        beChrome(req);
        getClient().execute(req, new FutureCallback<HttpResponse>() {

            @Override
            public void completed(HttpResponse result) {
                // switch to actor thread
                execute(() -> res.resolve(result));
            }

            @Override
            public void failed(Exception ex) {
                // switch to actor thread
                execute(() -> res.reject(ex));
            }

            @Override
            public void cancelled() {
                // switch to actor thread
                execute(() -> res.reject("cancelled"));
            }
        });
    } catch (Throwable th) {
        Log.Warn(this, "get fail " + th + " " + url);
        res.reject(th);
    }
    return res;
}
Also used : IPromise(org.nustaq.kontraktor.IPromise) Promise(org.nustaq.kontraktor.Promise) HttpGet(org.apache.http.client.methods.HttpGet) KeyManagementException(java.security.KeyManagementException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Example 60 with Promise

use of org.nustaq.kontraktor.Promise in project kontraktor by RuedigerMoeller.

the class AsyncHttpActor method postWithContext.

public IPromise<HttpResponse> postWithContext(String url, String postData, HttpContext ctx, String... headers) {
    Promise res = new Promise();
    if (url == null) {
        int debug = 1;
    }
    try {
        HttpPost req = new HttpPost(url);
        setHeaders(req, headers);
        beChrome(req);
        req.setEntity(new StringEntity(postData));
        getClient().execute(req, ctx, new FutureCallback<HttpResponse>() {

            @Override
            public void completed(HttpResponse result) {
                // switch to actor thread
                execute(() -> res.resolve(result));
            }

            @Override
            public void failed(Exception ex) {
                // switch to actor thread
                execute(() -> res.reject(ex));
            }

            @Override
            public void cancelled() {
                // switch to actor thread
                execute(() -> res.reject("cancelled"));
            }
        });
    } catch (Throwable th) {
        Log.Warn(this, "get fail " + th + " " + url);
        res.reject(th);
    }
    return res;
}
Also used : IPromise(org.nustaq.kontraktor.IPromise) Promise(org.nustaq.kontraktor.Promise) HttpPost(org.apache.http.client.methods.HttpPost) StringEntity(org.apache.http.entity.StringEntity) KeyManagementException(java.security.KeyManagementException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Aggregations

Promise (org.nustaq.kontraktor.Promise)67 IPromise (org.nustaq.kontraktor.IPromise)62 Test (org.junit.Test)10 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)9 Actor (org.nustaq.kontraktor.Actor)6 Remoted (org.nustaq.kontraktor.annotations.Remoted)6 IOException (java.io.IOException)4 Actors (org.nustaq.kontraktor.Actors)4 RateMeasure (org.nustaq.kontraktor.util.RateMeasure)4 JsonObject (com.eclipsesource.json.JsonObject)3 ByteBuffer (java.nio.ByteBuffer)3 KeyManagementException (java.security.KeyManagementException)3 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)3 CertificateException (java.security.cert.CertificateException)3 CountDownLatch (java.util.concurrent.CountDownLatch)3 Consumer (java.util.function.Consumer)3 ActorServer (org.nustaq.kontraktor.remoting.base.ActorServer)3 TCPConnectable (org.nustaq.kontraktor.remoting.tcp.TCPConnectable)3 TableSpaceActor (org.nustaq.reallive.impl.tablespace.TableSpaceActor)3 EOFException (java.io.EOFException)2