List of usage examples for io.netty.buffer Unpooled EMPTY_BUFFER
ByteBuf EMPTY_BUFFER
To view the source code for io.netty.buffer Unpooled EMPTY_BUFFER.
Click Source Link
From source file:org.elasticsearch.hadoop.transport.netty4.Netty4Utils.java
License:Apache License
/** * Turns the given BytesReference into a ByteBuf. Note: the returned ByteBuf will reference the internal * pages of the BytesReference. Don't free the bytes of reference before the ByteBuf goes out of scope. *//* w w w.j a v a 2 s . c o m*/ public static ByteBuf toByteBuf(final BytesReference reference) { if (reference.length() == 0) { return Unpooled.EMPTY_BUFFER; } if (reference instanceof ByteBufBytesReference) { return ((ByteBufBytesReference) reference).toByteBuf(); } else { final BytesRefIterator iterator = reference.iterator(); // usually we have one, two, or three components // from the header, the message, and a buffer final List<ByteBuf> buffers = new ArrayList<>(3); try { BytesRef slice; while ((slice = iterator.next()) != null) { buffers.add(Unpooled.wrappedBuffer(slice.bytes, slice.offset, slice.length)); } final CompositeByteBuf composite = Unpooled.compositeBuffer(buffers.size()); composite.addComponents(true, buffers); return composite; } catch (IOException ex) { throw new AssertionError("no IO happens here", ex); } } }
From source file:org.elasticsearch.http.netty4.Netty4HttpServerTransportTests.java
License:Apache License
/** * Test that {@link Netty4HttpServerTransport} supports the "Expect: 100-continue" HTTP header *///from w w w .j ava 2 s.c o m public void testExpectContinueHeader() throws Exception { try (Netty4HttpServerTransport transport = new Netty4HttpServerTransport(Settings.EMPTY, networkService, bigArrays, threadPool)) { transport.httpServerAdapter((request, channel, context) -> channel.sendResponse( new BytesRestResponse(OK, BytesRestResponse.TEXT_CONTENT_TYPE, new BytesArray("done")))); transport.start(); InetSocketTransportAddress remoteAddress = (InetSocketTransportAddress) randomFrom( transport.boundAddress().boundAddresses()); try (Netty4HttpClient client = new Netty4HttpClient()) { FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/"); HttpUtil.set100ContinueExpected(request, true); HttpUtil.setContentLength(request, 10); FullHttpResponse response = client.post(remoteAddress.address(), request); assertThat(response.status(), is(HttpResponseStatus.CONTINUE)); request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/", Unpooled.EMPTY_BUFFER); response = client.post(remoteAddress.address(), request); assertThat(response.status(), is(HttpResponseStatus.OK)); assertThat(new String(ByteBufUtil.getBytes(response.content()), StandardCharsets.UTF_8), is("done")); } } }
From source file:org.elasticsearch.http.nio.ByteBufUtils.java
License:Apache License
/** * Turns the given BytesReference into a ByteBuf. Note: the returned ByteBuf will reference the internal * pages of the BytesReference. Don't free the bytes of reference before the ByteBuf goes out of scope. *//*ww w. j a va 2 s . co m*/ static ByteBuf toByteBuf(final BytesReference reference) { if (reference.length() == 0) { return Unpooled.EMPTY_BUFFER; } if (reference instanceof ByteBufBytesReference) { return ((ByteBufBytesReference) reference).toByteBuf(); } else { final BytesRefIterator iterator = reference.iterator(); // usually we have one, two, or three components from the header, the message, and a buffer final List<ByteBuf> buffers = new ArrayList<>(3); try { BytesRef slice; while ((slice = iterator.next()) != null) { buffers.add(Unpooled.wrappedBuffer(slice.bytes, slice.offset, slice.length)); } final CompositeByteBuf composite = Unpooled.compositeBuffer(buffers.size()); composite.addComponents(true, buffers); return composite; } catch (IOException ex) { throw new AssertionError("no IO happens here", ex); } } }
From source file:org.elasticsearch.http.nio.NioHttpChannel.java
License:Apache License
@Override public void sendResponse(RestResponse response) { // if the response object was created upstream, then use it; // otherwise, create a new one ByteBuf buffer = ByteBufUtils.toByteBuf(response.content()); final FullHttpResponse resp; if (HttpMethod.HEAD.equals(nettyRequest.method())) { resp = newResponse(Unpooled.EMPTY_BUFFER); } else {//from www. ja v a2s . c o m resp = newResponse(buffer); } resp.setStatus(getStatus(response.status())); String opaque = nettyRequest.headers().get("X-Opaque-Id"); if (opaque != null) { setHeaderField(resp, "X-Opaque-Id", opaque); } // Add all custom headers addCustomHeaders(resp, response.getHeaders()); addCustomHeaders(resp, threadContext.getResponseHeaders()); ArrayList<Releasable> toClose = new ArrayList<>(3); boolean success = false; try { // If our response doesn't specify a content-type header, set one setHeaderField(resp, HttpHeaderNames.CONTENT_TYPE.toString(), response.contentType(), false); // If our response has no content-length, calculate and set one setHeaderField(resp, HttpHeaderNames.CONTENT_LENGTH.toString(), String.valueOf(buffer.readableBytes()), false); addCookies(resp); BytesReference content = response.content(); if (content instanceof Releasable) { toClose.add((Releasable) content); } BytesStreamOutput bytesStreamOutput = bytesOutputOrNull(); if (bytesStreamOutput instanceof ReleasableBytesStreamOutput) { toClose.add((Releasable) bytesStreamOutput); } if (isCloseConnection()) { toClose.add(nioChannel::close); } BiConsumer<Void, Exception> listener = (aVoid, ex) -> Releasables.close(toClose); nioChannel.getContext().sendMessage(new NioHttpResponse(sequence, resp), listener); success = true; } finally { if (success == false) { Releasables.close(toClose); } } }
From source file:org.elasticsearch.http.nio.NioHttpServerTransportTests.java
License:Apache License
private void runExpectHeaderTest(final Settings settings, final String expectation, final int contentLength, final HttpResponseStatus expectedStatus) throws InterruptedException { final HttpServerTransport.Dispatcher dispatcher = new HttpServerTransport.Dispatcher() { @Override//from ww w. j av a2s .c o m public void dispatchRequest(RestRequest request, RestChannel channel, ThreadContext threadContext) { channel.sendResponse( new BytesRestResponse(OK, BytesRestResponse.TEXT_CONTENT_TYPE, new BytesArray("done"))); } @Override public void dispatchBadRequest(RestRequest request, RestChannel channel, ThreadContext threadContext, Throwable cause) { throw new AssertionError(); } }; try (NioHttpServerTransport transport = new NioHttpServerTransport(settings, networkService, bigArrays, pageRecycler, threadPool, xContentRegistry(), dispatcher)) { transport.start(); final TransportAddress remoteAddress = randomFrom(transport.boundAddress().boundAddresses()); try (NioHttpClient client = new NioHttpClient()) { final FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/"); request.headers().set(HttpHeaderNames.EXPECT, expectation); HttpUtil.setContentLength(request, contentLength); final FullHttpResponse response = client.post(remoteAddress.address(), request); try { assertThat(response.status(), equalTo(expectedStatus)); if (expectedStatus.equals(HttpResponseStatus.CONTINUE)) { final FullHttpRequest continuationRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/", Unpooled.EMPTY_BUFFER); final FullHttpResponse continuationResponse = client.post(remoteAddress.address(), continuationRequest); try { assertThat(continuationResponse.status(), is(HttpResponseStatus.OK)); assertThat(new String(ByteBufUtil.getBytes(continuationResponse.content()), StandardCharsets.UTF_8), is("done")); } finally { continuationResponse.release(); } } } finally { response.release(); } } } }
From source file:org.elasticsearch.http.nio.PagedByteBuf.java
License:Apache License
static ByteBuf byteBufFromPages(InboundChannelBuffer.Page[] pages) { int componentCount = pages.length; if (componentCount == 0) { return Unpooled.EMPTY_BUFFER; } else if (componentCount == 1) { return byteBufFromPage(pages[0]); } else {// w ww . j ava 2 s . c om int maxComponents = Math.max(16, componentCount); final List<ByteBuf> components = new ArrayList<>(componentCount); for (InboundChannelBuffer.Page page : pages) { components.add(byteBufFromPage(page)); } return new CompositeByteBuf(UnpooledByteBufAllocator.DEFAULT, false, maxComponents, components); } }
From source file:org.elasticsearch.transport.netty4.Netty4UtilsTests.java
License:Apache License
public void testToChannelBufferWithEmptyRef() throws IOException { ByteBuf buffer = Netty4Utils.toByteBuf(getRandomizedBytesReference(0)); assertSame(Unpooled.EMPTY_BUFFER, buffer); }
From source file:org.fiware.kiara.transport.http.HttpHandler.java
License:Open Source License
@Override public ListenableFuture<Void> send(TransportMessage message) { if (message == null) { throw new NullPointerException("message"); }/*from w w w . j a v a 2s.c om*/ if (state != State.CONNECTED || channel == null) { throw new IllegalStateException("state=" + state.toString() + " channel=" + channel); } HttpMessage httpMsg; boolean keepAlive = true; if (message instanceof HttpRequestMessage) { HttpRequestMessage msg = (HttpRequestMessage) message; httpMsg = msg.finalizeRequest(); if (logger.isDebugEnabled()) { logger.debug("SEND CONTENT: {}", HexDump.dumpHexString(msg.getPayload())); } } else if (message instanceof HttpResponseMessage) { HttpResponseMessage msg = (HttpResponseMessage) message; httpMsg = msg.finalizeResponse(); keepAlive = HttpHeaders.isKeepAlive(httpMsg); if (logger.isDebugEnabled()) { logger.debug("SEND CONTENT: {}", HexDump.dumpHexString(msg.getPayload())); } } else { throw new IllegalArgumentException("msg is neither of type HttpRequestMessage nor HttpResponseMessage"); } final HttpMessage httpMsgArg = httpMsg; final boolean keepAliveArg = keepAlive; ListenableFuture<Void> f = Global.executor.submit(new Callable<Void>() { @Override public Void call() throws Exception { if (SYNC_REQUEST_RESPONSE) { semaphore.acquireUninterruptibly(); canSend.set(false); } final ChannelFuture result = channel.writeAndFlush(httpMsgArg); if (!keepAliveArg) { // If keep-alive is off, close the connection once the content is fully written. channel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); } result.syncUninterruptibly(); return null; } }); return f; }
From source file:org.glassfish.jersey.netty.connector.internal.JerseyChunkedInput.java
License:Open Source License
@Override public ByteBuf readChunk(ByteBufAllocator allocator) throws Exception { if (!open) {/*from w w w . j a v a 2 s .c om*/ return null; } ByteBuffer top = queue.poll(READ_TIMEOUT, TimeUnit.MILLISECONDS); if (top == null) { // returning empty buffer instead of null causes flush (which is needed for BroadcasterTest and others..). return Unpooled.EMPTY_BUFFER; } if (top == VOID) { open = false; return null; } int topRemaining = top.remaining(); ByteBuf buffer = allocator.buffer(topRemaining); buffer.setBytes(0, top); buffer.setIndex(0, topRemaining); if (top.remaining() > 0) { queue.addFirst(top); } offset += topRemaining; return buffer; }
From source file:org.graylog2.inputs.syslog.tcp.SyslogTCPFramingRouterHandlerTest.java
License:Open Source License
@Test public void testMessageReceivedWithEmptyBuffer() { final ByteBuf emptyBuffer = Unpooled.EMPTY_BUFFER; assertThat(channel.writeInbound(emptyBuffer)).isTrue(); assertThat((ByteBuf) channel.readInbound()).isEqualTo(emptyBuffer); assertThat((ByteBuf) channel.readInbound()).isNull(); }