Search in sources :

Example 11 with Actor

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

the class AsyncFile method read.

public IPromise<AsyncFileIOEvent> read(long position, int chunkSize, ByteBuffer target) {
    if (fileChannel == null)
        throw new RuntimeException("file not opened");
    Actor sender = Actor.current();
    Promise p = new Promise();
    if (target == null) {
        target = ByteBuffer.allocate(chunkSize);
    }
    final long bufferStartPos = target.position();
    final ByteBuffer finalTarget = target;
    fileChannel.read(target, position, target, new CompletionHandler<Integer, ByteBuffer>() {

        @Override
        public void completed(Integer result, ByteBuffer attachment) {
            // FIXME: how to handle incomplete read. (currently burden on reader)
            long newPos = position + finalTarget.limit() - bufferStartPos;
            if (result < 0)
                newPos = -1;
            attachment.flip();
            p.resolve(new AsyncFileIOEvent(newPos, result, finalTarget));
        }

        @Override
        public void failed(Throwable exc, ByteBuffer attachment) {
            p.reject(exc);
        }
    });
    return p;
}
Also used : Promise(org.nustaq.kontraktor.Promise) IPromise(org.nustaq.kontraktor.IPromise) Actor(org.nustaq.kontraktor.Actor) ByteBuffer(java.nio.ByteBuffer)

Example 12 with Actor

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

the class AsyncServerSocket method receiveLoop.

public void receiveLoop() {
    Actor actor = Actor.current();
    if (t == null)
        t = Thread.currentThread();
    else {
        if (t != Thread.currentThread()) {
            System.out.println("FATAL");
            System.exit(-1);
        }
    }
    boolean hadStuff = false;
    int iterCount = 10;
    do {
        try {
            selector.selectNow();
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            for (Iterator<SelectionKey> iterator = selectionKeys.iterator(); iterator.hasNext(); ) {
                SelectionKey key = iterator.next();
                try {
                    if (key == serverkey) {
                        if (key.isAcceptable()) {
                            SocketChannel accept = socket.accept();
                            if (accept != null) {
                                hadStuff = true;
                                accept.configureBlocking(false);
                                SelectionKey newKey = accept.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);
                                AsyncSocketConnection con = connectionFactory.apply(key, accept);
                                newKey.attach(con);
                            }
                        }
                    } else {
                        SocketChannel client = (SocketChannel) key.channel();
                        int written = 0;
                        if (key.isWritable()) {
                            AsyncSocketConnection con = (AsyncSocketConnection) key.attachment();
                            ByteBuffer writingBuffer = con.getWritingBuffer();
                            if (writingBuffer != null) {
                                hadStuff = true;
                                try {
                                    written = con.chan.write(writingBuffer);
                                    if (written < 0) {
                                        iterator.remove();
                                        key.cancel();
                                        // closed
                                        con.writeFinished("disconnected");
                                    } else if (writingBuffer.remaining() == 0) {
                                        iterator.remove();
                                        con.writeFinished(null);
                                    }
                                } catch (IOException ioe) {
                                    iterator.remove();
                                    key.cancel();
                                    con.writeFinished("disconnected");
                                }
                            }
                        }
                        if (key.isReadable() && written == 0) {
                            iterator.remove();
                            AsyncSocketConnection con = (AsyncSocketConnection) key.attachment();
                            if (con == null || con.isClosed()) {
                                Log.Lg.warn(this, "con is null " + key);
                            } else {
                                hadStuff = true;
                                try {
                                    if (!con.readData()) {
                                    // yield ?
                                    }
                                } catch (Exception ioe) {
                                    if (ioe instanceof EOFException) {
                                        Log.Info(this, "" + ioe);
                                    } else {
                                        Log.Info(this, ioe);
                                    }
                                    con.closed(ioe);
                                    key.cancel();
                                    try {
                                        client.close();
                                    } catch (IOException e) {
                                        Log.Warn(this, e);
                                    }
                                }
                            }
                        }
                    }
                } catch (Throwable e) {
                    Log.Warn(this, e, "");
                }
            }
        } catch (Throwable e) {
            Log.Warn(this, e, "");
            Actors.reject(e);
        }
    } while (iterCount-- > 0 && hadStuff);
    if (!isClosed()) {
        if (hadStuff) {
            actor.execute(() -> receiveLoop());
        } else {
            actor.delayed(1, () -> receiveLoop());
        }
    } else {
        // close open connections
        try {
            selector.selectNow();
            Actors.SubmitDelayed(TCPServerConnector.DELAY_MS_TILL_CLOSE, () -> {
                selector.selectedKeys().forEach(key -> {
                    try {
                        key.channel().close();
                    } catch (IOException e) {
                        Log.Warn(this, e);
                    }
                });
            });
        } catch (IOException e) {
            Log.Warn(this, e);
        }
    }
}
Also used : SelectionKey(java.nio.channels.SelectionKey) ServerSocketChannel(java.nio.channels.ServerSocketChannel) SocketChannel(java.nio.channels.SocketChannel) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) IOException(java.io.IOException) EOFException(java.io.EOFException) Actor(org.nustaq.kontraktor.Actor) EOFException(java.io.EOFException)

Example 13 with Actor

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

the class UntypedSampleServiceClient method main.

public static void main(String[] args) {
    Actor remote = (Actor) new WebSocketConnectable().actorClass(Actor.class).url("ws://localhost:3998").serType(SerializerType.JsonNoRef).connect((x, y) -> System.out.println("disconnect " + x + " " + y)).await();
    remote.ask("withPromise", "Hello").then((r, e) -> System.out.println(r + " " + e));
    remote.tell("withCallback", "Hi", (Callback) (r, e) -> System.out.println("callback:" + r + " " + e));
    remote.ask("withCallbackAndPromise", "Hi CB+P ", (Callback) (r, e) -> System.out.println("callback:" + r + " " + e)).then((r, e) -> System.out.println(r + " " + e));
    remote.ask("getSingletonSubservice", "lol").then((subremote, err) -> {
        Actor subrem = (Actor) subremote;
        subrem.tell("voidFun");
        subrem.ask("withCallbackAndPromise", "Hi sub", (Callback) (r, e) -> System.out.println("from sub" + r + " " + e));
    });
}
Also used : Callback(org.nustaq.kontraktor.Callback) SerializerType(org.nustaq.kontraktor.remoting.encoding.SerializerType) Actor(org.nustaq.kontraktor.Actor) WebSocketConnectable(org.nustaq.kontraktor.remoting.websockets.WebSocketConnectable) Callback(org.nustaq.kontraktor.Callback) Actor(org.nustaq.kontraktor.Actor) WebSocketConnectable(org.nustaq.kontraktor.remoting.websockets.WebSocketConnectable)

Example 14 with Actor

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

the class HoardeTest method testGenericAct.

private void testGenericAct(ArrayList toEncode, int threads, int max, boolean verify) throws InterruptedException {
    int actcount = 0;
    Hoarde<DecAct> oc = new Hoarde<DecAct>(threads, DecAct.class);
    oc.each(dec -> dec.init());
    AtomicInteger count = new AtomicInteger(0);
    AtomicInteger lastVal = new AtomicInteger(-1);
    while (actcount < max) {
        long tim = System.currentTimeMillis();
        for (int i = 0; i < toEncode.size(); i++) {
            HashMap<Object, Object> toEnc = (HashMap<Object, Object>) toEncode.get(i);
            oc.ordered(act -> {
                return act.decode(toEnc);
            }).then((r, e) -> {
                count.incrementAndGet();
                if (verify) {
                    HashMap o = (HashMap) FSTConfiguration.getDefaultConfiguration().asObject((byte[]) r);
                    Integer value = (Integer) ((Object[]) o.get("VALUE"))[0];
                    if (lastVal.get() != value.intValue() - 1)
                        System.out.println("ERROR " + value + " " + lastVal);
                    lastVal.set(value.intValue());
                }
            });
        }
        while (count.get() < 1000000) {
            LockSupport.parkNanos(1000 * 1000);
        }
        System.out.println("time Actor: " + (System.currentTimeMillis() - tim) + " " + count.get());
        count.set(0);
        actcount++;
    }
    oc.each((act) -> act.stop());
}
Also used : LockSupport(java.util.concurrent.locks.LockSupport) IPromise(org.nustaq.kontraktor.IPromise) Hoarde(org.nustaq.kontraktor.util.Hoarde) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Actor(org.nustaq.kontraktor.Actor) FSTConfiguration(org.nustaq.serialization.FSTConfiguration) Test(org.junit.Test) Promise(org.nustaq.kontraktor.Promise) HashMap(java.util.HashMap) Serializable(java.io.Serializable) ArrayList(java.util.ArrayList) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) HashMap(java.util.HashMap) Hoarde(org.nustaq.kontraktor.util.Hoarde)

Example 15 with Actor

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

the class HttpMonitor method getMonitorableKeys.

public IPromise<String[]> getMonitorableKeys(String simpleClzName) {
    ArrayList<String> result = new ArrayList();
    monitored.entrySet().forEach((entry) -> {
        Monitorable mon = entry.getValue();
        if (mon instanceof Actor)
            mon = ((Actor) mon).getActor();
        if (entry.getValue() != null && mon.getClass().getSimpleName().equals(simpleClzName)) {
            result.add(entry.getKey());
        }
    });
    String[] res = new String[result.size()];
    result.toArray(res);
    return new Promise(res);
}
Also used : Monitorable(org.nustaq.kontraktor.monitoring.Monitorable) IPromise(org.nustaq.kontraktor.IPromise) Promise(org.nustaq.kontraktor.Promise) Actor(org.nustaq.kontraktor.Actor) ArrayList(java.util.ArrayList)

Aggregations

Actor (org.nustaq.kontraktor.Actor)18 IPromise (org.nustaq.kontraktor.IPromise)8 Promise (org.nustaq.kontraktor.Promise)8 ByteBuffer (java.nio.ByteBuffer)4 IOException (java.io.IOException)2 ArrayList (java.util.ArrayList)2 HashMap (java.util.HashMap)2 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)2 Actors (org.nustaq.kontraktor.Actors)2 TCPNIOPublisher (org.nustaq.kontraktor.remoting.tcp.TCPNIOPublisher)2 WebSocketConnectable (org.nustaq.kontraktor.remoting.websockets.WebSocketConnectable)2 Pair (org.nustaq.kontraktor.util.Pair)2 Handlers (io.undertow.Handlers)1 Undertow (io.undertow.Undertow)1 PathHandler (io.undertow.server.handlers.PathHandler)1 io.undertow.websockets.core (io.undertow.websockets.core)1 WebSocketHttpExchange (io.undertow.websockets.spi.WebSocketHttpExchange)1 EOFException (java.io.EOFException)1 Serializable (java.io.Serializable)1 java.lang.ref (java.lang.ref)1