Example usage for io.netty.channel ChannelFuture addListener

List of usage examples for io.netty.channel ChannelFuture addListener

Introduction

In this page you can find the example usage for io.netty.channel ChannelFuture addListener.

Prototype

@Override
    ChannelFuture addListener(GenericFutureListener<? extends Future<? super Void>> listener);

Source Link

Usage

From source file:io.crate.mqtt.protocol.MqttProcessor.java

public void handleDisconnect(Channel channel) throws InterruptedException {
    ChannelFuture closeFuture = channel.flush().close();
    if (LOGGER.isDebugEnabled()) {
        closeFuture.addListener(cf -> LOGGER.debug("Client closed connection by sending DISCONNECT"));
    }// w  w w . j a  v  a2s .c  o  m
}

From source file:io.crate.protocols.http.HttpBlobHandler.java

License:Apache License

private void sendResponse(HttpResponse response) {
    ChannelFuture cf = ctx.channel().writeAndFlush(response);
    if (currentMessage != null && !HttpUtil.isKeepAlive(currentMessage)) {
        cf.addListener(ChannelFutureListener.CLOSE);
    }/*from w  w w  .  jav a 2  s.  c om*/
}

From source file:io.crate.protocols.http.HttpBlobHandler.java

License:Apache License

private void partialContentResponse(String range, HttpRequest request, String index, final String digest)
        throws IOException {
    assert range != null : "Getting partial response but no byte-range is not present.";
    Matcher matcher = CONTENT_RANGE_PATTERN.matcher(range);
    if (!matcher.matches()) {
        LOGGER.warn("Invalid byte-range: {}; returning full content", range);
        fullContentResponse(request, index, digest);
        return;/*from   w  w w  .j  av  a  2  s  .  co  m*/
    }
    BlobShard blobShard = localBlobShard(index, digest);

    final RandomAccessFile raf = blobShard.blobContainer().getRandomAccessFile(digest);
    long start;
    long end;
    try {
        try {
            start = Long.parseLong(matcher.group(1));
            if (start > raf.length()) {
                LOGGER.warn("416 Requested Range not satisfiable");
                simpleResponse(HttpResponseStatus.REQUESTED_RANGE_NOT_SATISFIABLE);
                raf.close();
                return;
            }
            end = raf.length() - 1;
            if (!matcher.group(2).equals("")) {
                end = Long.parseLong(matcher.group(2));
            }
        } catch (NumberFormatException ex) {
            LOGGER.error("Couldn't parse Range Header", ex);
            start = 0;
            end = raf.length();
        }

        DefaultHttpResponse response = new DefaultHttpResponse(HTTP_1_1, PARTIAL_CONTENT);
        maybeSetConnectionCloseHeader(response);
        HttpUtil.setContentLength(response, end - start + 1);
        response.headers().set(HttpHeaderNames.CONTENT_RANGE,
                "bytes " + start + "-" + end + "/" + raf.length());
        setDefaultGetHeaders(response);

        ctx.channel().write(response);
        ChannelFuture writeFuture = transferFile(digest, raf, start, end - start + 1);
        if (!HttpUtil.isKeepAlive(request)) {
            writeFuture.addListener(ChannelFutureListener.CLOSE);
        }
    } catch (Throwable t) {
        /*
         * Make sure RandomAccessFile is closed when exception is raised.
         * In case of success, the ChannelFutureListener in "transferFile" will take care
         * that the resources are released.
         */
        raf.close();
        throw t;
    }
}

From source file:io.crate.protocols.http.HttpBlobHandler.java

License:Apache License

private void fullContentResponse(HttpRequest request, String index, final String digest) throws IOException {
    BlobShard blobShard = localBlobShard(index, digest);
    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.OK);
    final RandomAccessFile raf = blobShard.blobContainer().getRandomAccessFile(digest);
    try {/*  ww w  .  j  av a  2s  .c  o m*/
        HttpUtil.setContentLength(response, raf.length());
        setDefaultGetHeaders(response);
        LOGGER.trace("HttpResponse: {}", response);
        Channel channel = ctx.channel();
        channel.write(response);
        ChannelFuture writeFuture = transferFile(digest, raf, 0, raf.length());
        if (!HttpUtil.isKeepAlive(request)) {
            writeFuture.addListener(ChannelFutureListener.CLOSE);
        }
    } catch (Throwable t) {
        /*
         * Make sure RandomAccessFile is closed when exception is raised.
         * In case of success, the ChannelFutureListener in "transferFile" will take care
         * that the resources are released.
         */
        raf.close();
        throw t;
    }
}

From source file:io.crate.protocols.http.HttpBlobHandler.java

License:Apache License

private ChannelFuture transferFile(final String digest, RandomAccessFile raf, long position, long count)
        throws IOException {

    Channel channel = ctx.channel();
    final ChannelFuture fileFuture;
    final ChannelFuture endMarkerFuture;
    if (sslEnabled) {
        HttpChunkedInput httpChunkedInput = new HttpChunkedInput(
                new ChunkedFile(raf, 0, count, HTTPS_CHUNK_SIZE));
        fileFuture = channel.writeAndFlush(httpChunkedInput, ctx.newProgressivePromise());
        // HttpChunkedInput also writes the end marker (LastHttpContent) for us.
        endMarkerFuture = fileFuture;//from  w  w w.j a v  a  2  s  .co m
    } else {
        FileRegion region = new DefaultFileRegion(raf.getChannel(), position, count);
        fileFuture = channel.write(region, ctx.newProgressivePromise());
        // Flushes and sets the ending marker
        endMarkerFuture = channel.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
    }

    fileFuture.addListener(new ChannelProgressiveFutureListener() {
        @Override
        public void operationProgressed(ChannelProgressiveFuture future, long progress, long total)
                throws Exception {
            LOGGER.debug("transferFile digest={} progress={} total={}", digest, progress, total);
        }

        @Override
        public void operationComplete(ChannelProgressiveFuture future) throws Exception {
            LOGGER.trace("transferFile operationComplete");
        }
    });

    return endMarkerFuture;
}

From source file:io.crate.protocols.postgres.Messages.java

License:Apache License

public static ChannelFuture sendAuthenticationOK(Channel channel) {
    ByteBuf buffer = channel.alloc().buffer(9);
    buffer.writeByte('R');
    buffer.writeInt(8); // size excluding char
    buffer.writeInt(0);/*from  www  .j a  v  a 2  s  .  com*/
    ChannelFuture channelFuture = channel.writeAndFlush(buffer);
    if (LOGGER.isTraceEnabled()) {
        channelFuture.addListener((ChannelFutureListener) future -> LOGGER.trace("sentAuthenticationOK"));
    }
    return channelFuture;
}

From source file:io.crate.protocols.postgres.Messages.java

License:Apache License

/**
 * | 'C' | int32 len | str commandTag/*from   ww  w  . j av a 2s . c  o m*/
 * @param query    :the query
 * @param rowCount : number of rows in the result set or number of rows affected by the DML statement
 */
static ChannelFuture sendCommandComplete(Channel channel, String query, long rowCount) {
    query = query.trim().split(" ", 2)[0].toUpperCase(Locale.ENGLISH);
    String commandTag;
    /*
     * from https://www.postgresql.org/docs/current/static/protocol-message-formats.html:
     *
     * For an INSERT command, the tag is INSERT oid rows, where rows is the number of rows inserted.
     * oid is the object ID of the inserted row if rows is 1 and the target table has OIDs; otherwise oid is 0.
     */
    if ("BEGIN".equals(query)) {
        commandTag = "BEGIN";
    } else if ("INSERT".equals(query)) {
        commandTag = "INSERT 0 " + rowCount;
    } else {
        commandTag = query + " " + rowCount;
    }

    byte[] commandTagBytes = commandTag.getBytes(StandardCharsets.UTF_8);
    int length = 4 + commandTagBytes.length + 1;
    ByteBuf buffer = channel.alloc().buffer(length + 1);
    buffer.writeByte('C');
    buffer.writeInt(length);
    writeCString(buffer, commandTagBytes);
    ChannelFuture channelFuture = channel.writeAndFlush(buffer);
    if (LOGGER.isTraceEnabled()) {
        channelFuture.addListener((ChannelFutureListener) future -> LOGGER.trace("sentCommandComplete"));
    }
    return channelFuture;
}

From source file:io.crate.protocols.postgres.Messages.java

License:Apache License

/**
 * ReadyForQuery (B)/*from  w  w w  . j av  a 2  s . c  o m*/
 * <p>
 * Byte1('Z')
 * Identifies the message type. ReadyForQuery is sent whenever the
 * backend is ready for a new query cycle.
 * <p>
 * Int32(5)
 * Length of message contents in bytes, including self.
 * <p>
 * Byte1
 * Current backend transaction status indicator. Possible values are
 * 'I' if idle (not in a transaction block); 'T' if in a transaction
 * block; or 'E' if in a failed transaction block (queries will be
 * rejected until block is ended).
 */
static void sendReadyForQuery(Channel channel) {
    ByteBuf buffer = channel.alloc().buffer(6);
    buffer.writeByte('Z');
    buffer.writeInt(5);
    buffer.writeByte('I');
    ChannelFuture channelFuture = channel.writeAndFlush(buffer);
    if (LOGGER.isTraceEnabled()) {
        channelFuture.addListener((ChannelFutureListener) future -> LOGGER.trace("sentReadyForQuery"));
    }
}

From source file:io.crate.protocols.postgres.Messages.java

License:Apache License

/**
 * | 'S' | int32 len | str name | str value
 * <p>/* w w  w.j  av  a 2s  .  c om*/
 * See https://www.postgresql.org/docs/9.2/static/protocol-flow.html#PROTOCOL-ASYNC
 * <p>
 * > At present there is a hard-wired set of parameters for which ParameterStatus will be generated: they are
 * <p>
 * - server_version,
 * - server_encoding,
 * - client_encoding,
 * - application_name,
 * - is_superuser,
 * - session_authorization,
 * - DateStyle,
 * - IntervalStyle,
 * - TimeZone,
 * - integer_datetimes,
 * - standard_conforming_string
 */
static void sendParameterStatus(Channel channel, final String name, final String value) {
    byte[] nameBytes = name.getBytes(StandardCharsets.UTF_8);
    byte[] valueBytes = value.getBytes(StandardCharsets.UTF_8);

    int length = 4 + nameBytes.length + 1 + valueBytes.length + 1;
    ByteBuf buffer = channel.alloc().buffer(length + 1);
    buffer.writeByte('S');
    buffer.writeInt(length);
    writeCString(buffer, nameBytes);
    writeCString(buffer, valueBytes);
    ChannelFuture channelFuture = channel.write(buffer);
    if (LOGGER.isTraceEnabled()) {
        channelFuture.addListener(
                (ChannelFutureListener) future -> LOGGER.trace("sentParameterStatus {}={}", name, value));
    }
}

From source file:io.crate.protocols.postgres.Messages.java

License:Apache License

/**
 * 'E' | int32 len | char code | str value | \0 | char code | str value | \0 | ... | \0
 * <p>/* w  w w.j  a  v a2  s  . c  om*/
 * char code / str value -> key-value fields
 * example error fields are: message, detail, hint, error position
 * <p>
 * See https://www.postgresql.org/docs/9.2/static/protocol-error-fields.html for a list of error codes
 */
private static ChannelFuture sendErrorResponse(Channel channel, String message, byte[] msg, byte[] severity,
        byte[] lineNumber, byte[] fileName, byte[] methodName, byte[] errorCode) {
    int length = 4 + 1 + (severity.length + 1) + 1 + (msg.length + 1) + 1 + (errorCode.length + 1)
            + (fileName != null ? 1 + (fileName.length + 1) : 0)
            + (lineNumber != null ? 1 + (lineNumber.length + 1) : 0)
            + (methodName != null ? 1 + (methodName.length + 1) : 0) + 1;
    ByteBuf buffer = channel.alloc().buffer(length + 1);
    buffer.writeByte('E');
    buffer.writeInt(length);
    buffer.writeByte('S');
    writeCString(buffer, severity);
    buffer.writeByte('M');
    writeCString(buffer, msg);
    buffer.writeByte(('C'));
    writeCString(buffer, errorCode);
    if (fileName != null) {
        buffer.writeByte('F');
        writeCString(buffer, fileName);
    }
    if (lineNumber != null) {
        buffer.writeByte('L');
        writeCString(buffer, lineNumber);
    }
    if (methodName != null) {
        buffer.writeByte('R');
        writeCString(buffer, methodName);
    }
    buffer.writeByte(0);
    ChannelFuture channelFuture = channel.writeAndFlush(buffer);
    if (LOGGER.isTraceEnabled()) {
        channelFuture.addListener(
                (ChannelFutureListener) future -> LOGGER.trace("sentErrorResponse msg={}", message));
    }
    return channelFuture;
}