Example usage for io.netty.channel ChannelHandlerContext flush

List of usage examples for io.netty.channel ChannelHandlerContext flush

Introduction

In this page you can find the example usage for io.netty.channel ChannelHandlerContext flush.

Prototype

@Override
    ChannelHandlerContext flush();

Source Link

Usage

From source file:com.yahoo.pulsar.broker.service.Consumer.java

License:Apache License

/**
 * Dispatch a list of entries to the consumer.
 *
 * @return a promise that can be use to track when all the data has been written into the socket
 *//* w  w w  . ja v  a 2s . c  om*/
public Pair<ChannelPromise, Integer> sendMessages(final List<Entry> entries) {
    final ChannelHandlerContext ctx = cnx.ctx();
    final MutablePair<ChannelPromise, Integer> sentMessages = new MutablePair<ChannelPromise, Integer>();
    final ChannelPromise writePromise = ctx.newPromise();
    sentMessages.setLeft(writePromise);
    if (entries.isEmpty()) {
        if (log.isDebugEnabled()) {
            log.debug("[{}] List of messages is empty, triggering write future immediately for consumerId {}",
                    subscription, consumerId);
        }
        writePromise.setSuccess();
        sentMessages.setRight(0);
        return sentMessages;
    }

    sentMessages.setRight(updatePermitsAndPendingAcks(entries));

    ctx.channel().eventLoop().execute(() -> {
        for (int i = 0; i < entries.size(); i++) {
            Entry entry = entries.get(i);
            PositionImpl pos = (PositionImpl) entry.getPosition();
            MessageIdData.Builder messageIdBuilder = MessageIdData.newBuilder();
            MessageIdData messageId = messageIdBuilder.setLedgerId(pos.getLedgerId())
                    .setEntryId(pos.getEntryId()).build();

            ByteBuf metadataAndPayload = entry.getDataBuffer();

            // skip checksum by incrementing reader-index if consumer-client doesn't support checksum verification
            if (cnx.getRemoteEndpointProtocolVersion() < ProtocolVersion.v6.getNumber()) {
                readChecksum(metadataAndPayload);
            }

            // stats
            msgOut.recordEvent(metadataAndPayload.readableBytes());

            if (log.isDebugEnabled()) {
                log.debug("[{}] Sending message to consumerId {}, entry id {}", subscription, consumerId,
                        pos.getEntryId());
            }

            // We only want to pass the "real" promise on the last entry written
            ChannelPromise promise = ctx.voidPromise();
            if (i == (entries.size() - 1)) {
                promise = writePromise;
            }
            ctx.write(Commands.newMessage(consumerId, messageId, metadataAndPayload), promise);
            messageId.recycle();
            messageIdBuilder.recycle();
        }

        ctx.flush();
    });

    return sentMessages;
}

From source file:Communicate.InputServerHandler.java

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {

    // inititate handshake
    Message self = Core.Node.getSelf();

    XStream xs = new XStream(new StaxDriver());
    String xml = xs.toXML(self);//ww w .jav a 2  s . c  om

    System.out.println("sending first handshake: " + xml);
    ctx.write(xml + "\r\n");
    ctx.flush();

}

From source file:de.jpaw.bonaparte.netty.testServer.TestServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, BonaPortable request) throws Exception {
    // String cipher;
    SslHandler sslH = ctx.pipeline().get(SslHandler.class);
    if (sslH != null) {
        SSLSession session = sslH.engine().getSession();
        // cipher = " (with cipher " + session.getCipherSuite() + ")";
        SessionInfo.logSessionInfo(session, "Client");
    } else {/*from   w  w  w  .jav  a 2s .  c o m*/
        // cipher = " (unencrypted)";
    }
    // logger.info("Received an object of type " + request.getClass().getCanonicalName() + cipher);
    Request myRequest = (Request) request;
    Response myResponse = new Response();

    myResponse.setSerialNo(myRequest.getSerialNo());
    myResponse.setUniqueId(myRequest.getUniqueId());
    myResponse.setThreadNo(thisThreadId);
    myResponse.setSerialInThread(0); // counterInThread.incrementAndGet());  => locking issue!
    myResponse.setWhenReceiced(new LocalDateTime());

    if (myRequest.getDuration() > 0) {
        Thread.sleep(myRequest.getDuration());
    }

    ctx.write(myResponse);
    ctx.flush();
}

From source file:divconq.net.ssl.SslHandler.java

License:Apache License

@Override
public void flush(ChannelHandlerContext ctx) throws Exception {
    // Do not encrypt the first write request if this handler is
    // created with startTLS flag turned on.
    if (startTls && !sentFirstMessage) {
        sentFirstMessage = true;//w w w.ja v a2  s. c  o  m
        pendingUnencryptedWrites.removeAndWriteAll();
        ctx.flush();
        return;
    }
    if (pendingUnencryptedWrites.isEmpty()) {
        pendingUnencryptedWrites.add(Unpooled.EMPTY_BUFFER, ctx.voidPromise());
    }
    if (!handshakePromise.isDone()) {
        flushedBeforeHandshakeDone = true;
    }
    wrap(ctx, false);
    ctx.flush();
}

From source file:divconq.net.ssl.SslHandler.java

License:Apache License

@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
    if (needsFlush) {
        needsFlush = false;// ww w .j av  a 2  s.co m
        ctx.flush();
    }

    // if not auto reading but no handshake, then read anyway
    if (!handshakePromise.isDone() && !ctx.channel().config().isAutoRead()) {
        ctx.read();
    }

    super.channelReadComplete(ctx);
}

From source file:eu.smartenit.sbox.interfaces.intersbox.server.InterSBoxServerH.java

License:Apache License

@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
    String host = ((InetSocketAddress) ctx.channel().remoteAddress()).getAddress().getHostAddress();
    int port = ((InetSocketAddress) ctx.channel().remoteAddress()).getPort();
    logger.debug("Server readcomplete from host:" + host + ":" + port);
    ctx.flush();
}

From source file:fslib.net.FSChannelHandler.java

License:Open Source License

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    cause.printStackTrace();//w ww  . j  a  va 2  s  .  co  m
    ctx.flush();
}

From source file:gameconsole.GameConsole.java

public void handleRequest(OutputStream output, HttpHeaders clientheaders, Map<String, String> serverheaders,
        AtomicReference<HttpResponseStatus> status, String path, String post, ChannelHandlerContext ctx)
        throws IOException, InterruptedException {
    String contentTypeHeader = clientheaders.get("content-type");
    serverheaders.put("X-Robots-Tag", "noindex, nofollow");

    if (path.endsWith("service=config")) {
        JSONObject config = new JSONObject();
        config.put("authmethod", "password");

        //config.put("authmethod", "none");
        //config.put("authmethod", "url");
        //config.put("authmethodarg1", "");
        JSONArray endpoints = new JSONArray();
        endpoints.put("/service");
        config.put("endpoints", endpoints);
        byte[] s = config.toString().getBytes("UTF-8");
        output.write(s);//from  w  w w  .  ja v a  2  s .  co  m

        status.set(HttpResponseStatus.OK);
        serverheaders.put("cache-control", "max-age=120");
        return;
    }
    if (contentTypeHeader == null || !contentTypeHeader.startsWith("application/json")) {
        status.set(HttpResponseStatus.BAD_REQUEST);
        return;
    }
    if (post.isEmpty()) {
        status.set(HttpResponseStatus.BAD_REQUEST);
        return;
    }
    JSONObject incoming = new JSONObject(post);

    if (path.endsWith("service=password")) {
        String username = incoming.optString("username", "");
        String password = incoming.optString("password", "");
        String random = incoming.optString("random", "");

        JSONObject auth = new JSONObject();
        if (username.isEmpty() || password.isEmpty() || random.isEmpty()) {
            auth.put("random", "THIS_MUST_BE_RANDOM_FOR_EVERY_USER");
        } else {
            if (username.equals("root") && password.equals("root")) {
                auth.put("session_token", "token");
                JSONArray permissions = new JSONArray();
                permissions.put("servers.admin");
                permissions.put("servers.view");
                permissions.put("servers.log");
                permissions.put("servers.admin");
                auth.put("permissions", permissions);
            } else {
                auth.put("error", "Invalid username or password");
            }
        }
        byte[] s = auth.toString().getBytes("UTF-8");
        output.write(s);

        status.set(HttpResponseStatus.OK);
        return;
    }

    String target = incoming.optString("target", "server");
    String action = incoming.optString("action", "");
    StringBuilder b = this.strings.get();
    b.setLength(0);

    switch (target) {
    case "server": {
        String server = incoming.optString("server", "");
        Logger.getLogger(GameConsole.class.getName()).log(Level.INFO, "Request: {0}: {1}: {2}",
                new Object[] { target, action, server });

        if (!this.servers.containsKey(server)) {
            status.set(HttpResponseStatus.NOT_FOUND);
            return;
        }
        final Server s = this.servers.get(server);

        switch (action) {
        case "start": {
            synchronized (s) {
                JSONObject obj = new JSONObject();
                if (!s.isRunning()) {
                    s.start();
                    obj.put("stage-changed", "now");
                }

                obj.put("state", s.isRunning() ? "started" : "stopped");
                obj.put("server-id", server);
                obj.put("readIndex", s.getCurrentWriteIndex());
                obj.put("bufSize", s.getBufferSize());
                b.append(obj.toString());
            }
        }
            break;
        case "stop": {
            synchronized (s) {
                if (s.isRunning()) {
                    s.stop();
                }
                JSONObject obj = new JSONObject();
                obj.put("state", s.isRunning() ? "started" : "stopped");
                obj.put("server-id", server);
                obj.put("readIndex", s.getCurrentWriteIndex());
                obj.put("bufSize", s.getBufferSize());
                b.append(obj.toString());
            }
        }
            break;
        case "settings": {
            synchronized (s) {
                JSONObject obj = new JSONObject();
                obj.put("state", s.isRunning() ? "started" : "stopped");
                obj.put("server-id", server);
                obj.put("readIndex", s.getCurrentWriteIndex());
                obj.put("bufSize", s.getBufferSize());
                JSONArray arr = new JSONArray();
                for (Map.Entry<Setting, String> se : s.settings.entrySet()) {
                    JSONObject obj1 = new JSONObject();
                    obj1.put("name", se.getKey().getName());
                    obj1.put("fieldtype", se.getKey().getFieldType());
                    obj1.put("type", se.getKey().getType());
                    obj1.put("description", se.getKey().getName());
                    arr.put(obj1);
                }
                obj.put("settings", arr);
                b.append(obj.toString());
            }
        }
            break;
        case "log": {
            synchronized (s) {
                JSONObject obj = new JSONObject();
                obj.put("state", s.isRunning() ? "started" : "stopped");
                obj.put("server-id", server);

                long clientIndex = incoming.optLong("readIndex", 0);
                long serverIndex = s.getCurrentWriteIndex();
                if (clientIndex > serverIndex) {
                    clientIndex = 0;
                }
                //                            long bufferSize = s.getCurrentBufferSize();
                //                            long newIndex;
                //                            long readBytes;

                byte[] clientBuff = this.clientbuff.get();

                //                            if (clientIndex <= serverIndex - bufferSize) {
                //                                clientIndex = serverIndex - bufferSize + 1;
                //                                newIndex = s.readBytes(clientBuff, 0, clientBuff.length, clientIndex, false, 0);
                //                                readBytes = clientBuff.length;
                //                            } else {
                //                                newIndex = s.readBytes(clientBuff, 0, clientBuff.length, clientIndex, true, 2);
                //                                readBytes = Math.min(newIndex - clientIndex, clientBuff.length);
                //                                serverIndex = s.getCurrentWriteIndex();
                //                            }
                Logger.getLogger(GameConsole.class.getName()).log(Level.INFO,
                        "Request log files: {0} - {1} : {2}",
                        new Object[] { s.getLowestValidReadIndex(), s.getCurrentWriteIndex(), clientIndex });
                int r = s.readBytes(clientBuff, 0, clientBuff.length, clientIndex);
                if (r == -1) {
                    clientIndex = s.getLowestValidReadIndex();
                    r = s.readBytes(clientBuff, 0, clientBuff.length, clientIndex);
                    assert r > 0;
                } else if (r == 0 && incoming.optBoolean("blocking", false)) {
                    ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
                    ctx.flush();
                    r = s.readBytesBlocking(clientBuff, 0, clientBuff.length, clientIndex, 8);
                }

                if (r < 0) {
                    obj.put("log", "");
                    r = 0;
                } else {
                    obj.put("log",
                            new String(clientBuff, 0, (int) r).replace("\\", "\\\\").replace("\n", "\\n"));
                }
                obj.put("oldReadIndex", clientIndex);
                obj.put("nextReadIndex", clientIndex + r);
                obj.put("readIndex", serverIndex);

                b.append(obj.toString());
            }
        }
            break;
        case "forcestop": {
            synchronized (s) {
                if (s.isRunning()) {
                    s.forceStop();
                }
                JSONObject obj = new JSONObject();
                obj.put("state", s.isRunning() ? "started" : "stopped");
                obj.put("server-id", server);
                obj.put("readIndex", s.getCurrentWriteIndex());
                obj.put("bufSize", s.getBufferSize());
                b.append(obj.toString());
            }
        }
            break;
        case "status": {
            synchronized (s) {
                JSONObject obj = new JSONObject();
                obj.put("state", s.isRunning() ? "started" : "stopped");
                obj.put("server-id", server);
                obj.put("server-name", "Unknown server");
                obj.put("readIndex", s.getCurrentWriteIndex());
                obj.put("bufSize", s.getBufferSize());
                b.append(obj.toString());
            }
        }
            break;
        case "command": {
            synchronized (s) {
                if (s.isRunning()) {
                    s.sendCommand(incoming.optString("command", ""));
                }
                JSONObject obj = new JSONObject();
                obj.put("state", s.isRunning() ? "started" : "stopped");
                obj.put("server-id", server);
                obj.put("readIndex", s.getCurrentWriteIndex());
                obj.put("bufSize", s.getBufferSize());
                b.append(obj.toString());
            }
        }
            break;

        default: {
            status.set(HttpResponseStatus.METHOD_NOT_ALLOWED);
        }
            return;
        }
    }
        break;
    case "management": {
        Logger.getLogger(GameConsole.class.getName()).log(Level.INFO, "Request: {0}: {1}",
                new Object[] { target, action });
        switch (action) {
        case "servers": {

            JSONObject obj = new JSONObject();
            JSONArray array = new JSONArray();
            for (String serverName : servers.keySet()) {
                array.put(serverName);
            }
            obj.put("servers", array);
            b.append(obj.toString());

        }
            break;
        case "status": {

            JSONObject obj = new JSONObject();
            for (Map.Entry<String, Server> serverName : servers.entrySet()) {
                JSONObject obj1 = new JSONObject();
                final Server server = serverName.getValue();
                synchronized (server) {
                    obj1.put("state", server.isRunning() ? "started" : "stopped");
                    obj1.put("server-id", serverName.getKey());
                    obj1.put("readIndex", server.getCurrentWriteIndex());
                    obj1.put("bufSize", server.getBufferSize());
                    obj1.put("exitCode", 0);
                    obj1.put("smalldescription", serverName.getKey());
                }
                obj.put(serverName.getKey(), obj1);
            }
            b.append(obj.toString());

        }
            break;
        default:
            status.set(HttpResponseStatus.METHOD_NOT_ALLOWED);
            return;

        }
    }
        break;
    default:
        Logger.getLogger(GameConsole.class.getName()).log(Level.INFO, "Request: {0}", new Object[] { target });
        status.set(HttpResponseStatus.METHOD_NOT_ALLOWED);
        return;
    }

    byte[] temp = b.toString().getBytes(Charset.forName("UTF-8"));
    serverheaders.put("Content-type", "application/json; charset=utf-8");
    //rverheaders.put("Content-lenght", String.valueOf(temp.length));
    output.write(temp);
    status.set(HttpResponseStatus.OK);
}

From source file:in.voidma.lemming.traffic.TrafficLatencyHandler.java

License:Open Source License

@Override
public void flush(ChannelHandlerContext ctx) throws Exception {
    if (outBound) {
        timer.newTimeout(new TimerTask() {
            @Override//from   ww w  .  j  a va 2s. com
            public void run(Timeout timeout) throws Exception {
                ctx.flush();
            }
        }, TimeLagMS, TimeUnit.MILLISECONDS);
    }
}

From source file:inn.eatery.server.ServerHandler.java

License:Apache License

@Override
public void channelReadComplete(ChannelHandlerContext ctx) {
    ctx.flush();
    l.info("channel read complete");

    /*// w  w w . j  ava  2 s  .  c  o m
     * ByteBuf fullcontent = content.copy( 0, content.capacity() ); content.release();
     * 
     * 
     * l.info("read complete {}", fullcontent.toString( CharsetUtil.UTF_8 ) );
     * 
     * fullcontent.release(); reset();
     */
}