Example usage for io.netty.channel Channel alloc

List of usage examples for io.netty.channel Channel alloc

Introduction

In this page you can find the example usage for io.netty.channel Channel alloc.

Prototype

ByteBufAllocator alloc();

Source Link

Document

Return the assigned ByteBufAllocator which will be used to allocate ByteBuf s.

Usage

From source file:alluxio.worker.netty.DataServerBlockReadHandler.java

License:Apache License

@Override
protected DataBuffer getDataBuffer(Channel channel, long offset, int len) throws IOException {
    BlockReader blockReader = ((BlockReadRequestInternal) mRequest).mBlockReader;
    Preconditions.checkArgument(blockReader.getChannel() instanceof FileChannel,
            "Only FileChannel is supported!");
    switch (mTransferType) {
    case MAPPED:/*w  w  w.  jav a2s  . c o  m*/
        ByteBuf buf = channel.alloc().buffer(len, len);
        try {
            FileChannel fileChannel = (FileChannel) blockReader.getChannel();
            Preconditions.checkState(fileChannel.position() == offset);
            while (buf.writableBytes() > 0 && buf.writeBytes(fileChannel, buf.writableBytes()) != -1) {
            }
            return new DataNettyBufferV2(buf);
        } catch (Throwable e) {
            buf.release();
            throw e;
        }
    case TRANSFER: // intend to fall through as TRANSFER is the default type.
    default:
        return new DataFileChannel((FileChannel) blockReader.getChannel(), offset, len);
    }
}

From source file:alluxio.worker.netty.DataServerUfsBlockReadHandler.java

License:Apache License

@Override
protected DataBuffer getDataBuffer(Channel channel, long offset, int len) throws IOException {
    BlockReader blockReader = ((UfsBlockReadRequestInternal) mRequest).mBlockReader;
    // This buf is released by netty.
    ByteBuf buf = channel.alloc().buffer(len, len);
    try {/*from  ww  w  . j a  v  a2 s  .  com*/
        while (buf.writableBytes() > 0 && blockReader.transferTo(buf) != -1) {
        }
        return new DataNettyBufferV2(buf);
    } catch (Throwable e) {
        buf.release();
        throw e;
    }
}

From source file:alluxio.worker.netty.DataServerUFSFileReadHandler.java

License:Apache License

@Override
protected DataBuffer getDataBuffer(Channel channel, long offset, int len) throws IOException {
    ByteBuf buf = channel.alloc().buffer(len, len);
    try {/*  www.  j av  a 2  s.c o  m*/
        InputStream in = ((FileReadRequestInternal) mRequest).mInputStream;
        if (in != null) { // if we have not reached the end of the file
            while (buf.writableBytes() > 0 && buf.writeBytes(in, buf.writableBytes()) != -1) {
            }
        }
        if (buf.readableBytes() == 0) {
            buf.release();
            return null;
        }
        return new DataNettyBufferV2(buf);
    } catch (Throwable e) {
        buf.release();
        throw e;
    }
}

From source file:com.addthis.meshy.SourceHandler.java

License:Apache License

protected boolean sendToSingleTarget(Channel channel, byte[] data) {
    int sendType = MeshyConstants.KEY_EXISTING;
    final ByteBufAllocator alloc = channel.alloc();
    final ByteBuf buffer = allocateSendBuffer(alloc, sendType, session, data);

    final int reportBytes = data.length;
    log.trace("{} send {} to {}", this, buffer.capacity(), channel);
    channel.writeAndFlush(buffer.duplicate().retain()).addListener(ignored -> {
        master.sentBytes(reportBytes);//ww  w .  jav  a 2 s.  com
    });
    buffer.release();
    return true;
}

From source file:com.agrn.senqm.network.connection.Connection.java

License:Open Source License

public void sendMessage(String message) {
    Channel channel = channelFuture.channel();

    ByteBuf buffer = channel.alloc().buffer(message.length());
    for (char character : message.toCharArray())
        buffer.writeChar(character);/*from   ww  w.  ja  v  a2 s .  c  o  m*/

    channel.writeAndFlush(buffer);
}

From source file:com.ahanda.techops.noty.clientTest.ClientHandler.java

License:Apache License

private void getEvents(Channel ch, FullHttpResponse resp) {
    StringWriter estr = new StringWriter();
    getEvents.write(estr);//from  w  w  w  .  ja  v  a2s.  c  om
    String contentStr = estr.toString();

    FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/events/get",
            ch.alloc().buffer().writeBytes(contentStr.getBytes()));

    request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);
    request.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/json");

    request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, request.content().readableBytes());
    // Set some example cookies.
    request.headers().set(HttpHeaders.Names.COOKIE, ClientCookieEncoder.encode(sessCookies));

    l.info("getevents bytes {}", request.content().readableBytes());

    // Send the HTTP request.
    ch.writeAndFlush(request);
}

From source file:com.ahanda.techops.noty.clientTest.ClientHandler.java

License:Apache License

public void login(Channel ch, JSONObject credential) {
    StringWriter estr = new StringWriter();
    credential.write(estr);/*from   w w w.  j ava2s  .com*/
    String contentStr = estr.toString();
    FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/login",
            ch.alloc().buffer().writeBytes(contentStr.getBytes()));

    request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);
    request.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/json");
    if (sessCookies != null)
        request.headers().set(HttpHeaders.Names.COOKIE, ClientCookieEncoder.encode(sessCookies));

    request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, request.content().readableBytes());

    l.info("login request {}", request);

    // Send the HTTP request.
    ch.writeAndFlush(request);
}

From source file:com.ahanda.techops.noty.clientTest.ClientHandler.java

License:Apache License

public void pubEvent(Channel ch, JSONObject e, FullHttpResponse resp) {
    // Prepare the HTTP request.
    JSONArray es = new JSONArray();
    es.put(e);/* w  w w  . j a  v a2 s. co  m*/

    StringWriter estr = new StringWriter();
    es.write(estr);
    String contentStr = estr.toString();
    FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/events",
            ch.alloc().buffer().writeBytes(contentStr.getBytes()));

    request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);
    request.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/json");

    request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, request.content().readableBytes());
    // Set some example cookies.
    request.headers().set(HttpHeaders.Names.COOKIE, ClientCookieEncoder.encode(sessCookies));

    l.info("PUB Event request {}", request);

    // Send the HTTP request.
    ch.writeAndFlush(request);
}

From source file:com.facebook.nifty.core.TNiftyTransport.java

License:Apache License

public TNiftyTransport(Channel channel, ThriftMessage in) {
    this.channel = channel;
    this.in = in;
    this.out = channel.alloc().heapBuffer(DEFAULT_OUTPUT_BUFFER_SIZE);

    in.getBuffer().retain();//w w w .  j a  v a  2s.  c om
    out.retain();
}

From source file:com.google.devtools.build.lib.remote.blobstore.http.HttpBlobStore.java

License:Open Source License

public HttpBlobStore(URI uri, int timeoutMillis, @Nullable final Credentials creds) throws Exception {
    boolean useTls = uri.getScheme().equals("https");
    if (uri.getPort() == -1) {
        int port = useTls ? 443 : 80;
        uri = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), port, uri.getPath(), uri.getQuery(),
                uri.getFragment());//from w  w w. ja va 2  s  . co  m
    }
    this.uri = uri;
    final SslContext sslCtx;
    if (useTls) {
        // OpenSsl gives us a > 2x speed improvement on fast networks, but requires netty tcnative
        // to be there which is not available on all platforms and environments.
        SslProvider sslProvider = OpenSsl.isAvailable() ? SslProvider.OPENSSL : SslProvider.JDK;
        sslCtx = SslContextBuilder.forClient().sslProvider(sslProvider).build();
    } else {
        sslCtx = null;
    }
    Bootstrap clientBootstrap = new Bootstrap().channel(NioSocketChannel.class)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, timeoutMillis).group(eventLoop)
            .remoteAddress(uri.getHost(), uri.getPort());
    downloadChannels = new SimpleChannelPool(clientBootstrap, new ChannelPoolHandler() {
        @Override
        public void channelReleased(Channel ch) {
            ch.pipeline().remove("read-timeout-handler");
        }

        @Override
        public void channelAcquired(Channel ch) {
            ch.pipeline().addFirst("read-timeout-handler", new ReadTimeoutHandler(timeoutMillis));
        }

        @Override
        public void channelCreated(Channel ch) {
            ChannelPipeline p = ch.pipeline();
            p.addFirst("read-timeout-handler", new ReadTimeoutHandler(timeoutMillis));
            if (sslCtx != null) {
                SSLEngine engine = sslCtx.newEngine(ch.alloc());
                engine.setUseClientMode(true);
                p.addFirst(new SslHandler(engine));
            }
            p.addLast(new HttpClientCodec());
            p.addLast(new HttpDownloadHandler(creds));
        }
    });
    uploadChannels = new SimpleChannelPool(clientBootstrap, new ChannelPoolHandler() {
        @Override
        public void channelReleased(Channel ch) {
        }

        @Override
        public void channelAcquired(Channel ch) {
        }

        @Override
        public void channelCreated(Channel ch) {
            ChannelPipeline p = ch.pipeline();
            if (sslCtx != null) {
                SSLEngine engine = sslCtx.newEngine(ch.alloc());
                engine.setUseClientMode(true);
                p.addFirst(new SslHandler(engine));
            }
            p.addLast(new HttpResponseDecoder());
            // The 10KiB limit was chosen at random. We only expect HTTP servers to respond with
            // an error message in the body and that should always be less than 10KiB.
            p.addLast(new HttpObjectAggregator(10 * 1024));
            p.addLast(new HttpRequestEncoder());
            p.addLast(new ChunkedWriteHandler());
            p.addLast(new HttpUploadHandler(creds));
        }
    });
    this.creds = creds;
}