List of usage examples for io.netty.buffer Unpooled wrappedBuffer
static <T> ByteBuf wrappedBuffer(int maxNumComponents, ByteWrapper<T> wrapper, T[] array)
From source file:com.twitter.http2.HttpFrameDecoderTest.java
License:Apache License
@Test public void testHttpHeadersFrameMultipleContinuations() throws Exception { int headerBlockLength = 16; int length = 5 + headerBlockLength; byte flags = 0x01 | 0x20; // END_STREAM | PRIORITY int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01; boolean exclusive = RANDOM.nextBoolean(); int dependency = RANDOM.nextInt() & 0x7FFFFFFF; int weight = RANDOM.nextInt() & 0xFF; ByteBuf headersFrame = headersFrame(length, flags, streamId); writePriorityFields(headersFrame, exclusive, dependency, weight); writeRandomData(headersFrame, headerBlockLength); ByteBuf continuationFrame1 = continuationFrame(0, (byte) 0x00, streamId); ByteBuf continuationFrame2 = continuationFrame(0, (byte) 0x04, streamId); // END_HEADERS decoder.decode(releaseLater(Unpooled.wrappedBuffer(headersFrame, continuationFrame1, continuationFrame2))); InOrder inOrder = inOrder(delegate); inOrder.verify(delegate).readHeadersFrame(streamId, true, false, exclusive, dependency, weight + 1); inOrder.verify(delegate).readHeaderBlock(headersFrame.slice(HTTP_FRAME_HEADER_SIZE + 5, headerBlockLength)); inOrder.verify(delegate).readHeaderBlockEnd(); verifyNoMoreInteractions(delegate);/* ww w .j a va2s . co m*/ }
From source file:com.twitter.http2.HttpFrameDecoderTest.java
License:Apache License
@Test public void testHttpPushPromiseFrameMultipleContinuations() throws Exception { int headerBlockLength = 16; int length = 4 + headerBlockLength; byte flags = 0; int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01; int promisedStreamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01; ByteBuf pushPromiseFrame = pushPromiseFrame(length, flags, streamId); pushPromiseFrame.writeInt(promisedStreamId); writeRandomData(pushPromiseFrame, headerBlockLength); ByteBuf continuationFrame1 = continuationFrame(0, (byte) 0x00, streamId); ByteBuf continuationFrame2 = continuationFrame(0, (byte) 0x04, streamId); // END_HEADERS decoder.decode(//from w w w . j ava2 s. c om releaseLater(Unpooled.wrappedBuffer(pushPromiseFrame, continuationFrame1, continuationFrame2))); InOrder inOrder = inOrder(delegate); inOrder.verify(delegate).readPushPromiseFrame(streamId, promisedStreamId); inOrder.verify(delegate) .readHeaderBlock(pushPromiseFrame.slice(HTTP_FRAME_HEADER_SIZE + 4, headerBlockLength)); inOrder.verify(delegate).readHeaderBlockEnd(); verifyNoMoreInteractions(delegate); }
From source file:com.uber.tchannel.handlers.TestMessageMultiplexer.java
License:Open Source License
@Test public void testMergeRequestMessage() { MessageDefragmenter mux = new MessageDefragmenter(); Map<Long, List<CallFrame>> map = mux.getCallFrames(); EmbeddedChannel channel = new EmbeddedChannel(mux); long id = 42; CallRequestFrame callRequestFrame = Fixtures.callRequest(id, true, new HashMap<String, String>() { {//w w w . jav a 2s. c o m put(TransportHeaders.ARG_SCHEME_KEY, ArgScheme.RAW.getScheme()); } }, Unpooled.wrappedBuffer( // arg1 size new byte[] { 0x00, 0x04 }, "arg1".getBytes(), new byte[] { 0x00, 0x00 })); channel.writeInbound(MessageCodec.encode(MessageCodec.encode(callRequestFrame))); assertEquals(1, map.size()); assertNotNull(map.get(id)); assertEquals(1, callRequestFrame.refCnt()); CallRequestContinueFrame firstCallRequestContinueFrame = Fixtures.callRequestContinue(id, true, Unpooled.wrappedBuffer( // arg2 size new byte[] { 0x00, 0x04 }, "arg2".getBytes())); channel.writeInbound(MessageCodec.encode(MessageCodec.encode(firstCallRequestContinueFrame))); assertEquals(1, map.size()); assertNotNull(map.get(id)); assertEquals(2, map.get(id).size()); assertEquals(1, callRequestFrame.refCnt()); assertEquals(1, firstCallRequestContinueFrame.refCnt()); CallRequestContinueFrame secondCallRequestContinueFrame = Fixtures.callRequestContinue(id, false, Unpooled.wrappedBuffer(new byte[] { 0x00, 0x00 }, // arg3 size new byte[] { 0x00, 0x04 }, "arg3".getBytes())); channel.writeInbound(MessageCodec.encode(MessageCodec.encode(secondCallRequestContinueFrame))); assertEquals(map.size(), 0); assertNull(map.get(id)); assertEquals(1, callRequestFrame.refCnt()); assertEquals(1, firstCallRequestContinueFrame.refCnt()); assertEquals(1, secondCallRequestContinueFrame.refCnt()); RawMessage fullMessage = channel.readInbound(); assertEquals(1, fullMessage.getArg1().refCnt()); assertEquals(1, fullMessage.getArg2().refCnt()); assertEquals(1, fullMessage.getArg3().refCnt()); assertNotNull(fullMessage); assertEquals(fullMessage.getArg1().toString(CharsetUtil.UTF_8), "arg1"); assertEquals(fullMessage.getArg2().toString(CharsetUtil.UTF_8), "arg2"); assertEquals(fullMessage.getArg3().toString(CharsetUtil.UTF_8), "arg3"); fullMessage.getArg1().release(); fullMessage.getArg2().release(); fullMessage.getArg3().release(); assertEquals(0, callRequestFrame.refCnt()); assertEquals(0, firstCallRequestContinueFrame.refCnt()); assertEquals(0, secondCallRequestContinueFrame.refCnt()); assertNull(channel.readInbound()); }
From source file:com.vmware.xenon.common.http.netty.NettyHttpServiceClient.java
License:Open Source License
private void doSendRequest(Operation op) { final Object originalBody = op.getBodyRaw(); try {//from ww w.j a v a 2 s .c om byte[] body = Utils.encodeBody(op); if (op.getContentLength() > getRequestPayloadSizeLimit()) { stopTracking(op); Exception e = new IllegalArgumentException("Content-Length " + op.getContentLength() + " is greater than max size allowed " + getRequestPayloadSizeLimit()); op.setBody(ServiceErrorResponse.create(e, Operation.STATUS_CODE_BAD_REQUEST)); op.fail(e); return; } String pathAndQuery; String path = op.getUri().getPath(); String query = op.getUri().getRawQuery(); String userInfo = op.getUri().getRawUserInfo(); path = path == null || path.isEmpty() ? "/" : path; if (query != null) { pathAndQuery = path + "?" + query; } else { pathAndQuery = path; } /** * NOTE: Pay close attention to calls that access the operation request headers, since * they will cause a memory allocation. We avoid the allocation by first checking if * the operation has any custom headers to begin with, then we check for the specific * header */ boolean hasRequestHeaders = op.hasRequestHeaders(); boolean useHttp2 = op.isConnectionSharing(); if (this.httpProxy != null || useHttp2 || userInfo != null) { pathAndQuery = op.getUri().toString(); } NettyFullHttpRequest request = null; HttpMethod method = HttpMethod.valueOf(op.getAction().toString()); if (body == null || body.length == 0) { request = new NettyFullHttpRequest(HttpVersion.HTTP_1_1, method, pathAndQuery, Unpooled.buffer(0), false); } else { ByteBuf content = Unpooled.wrappedBuffer(body, 0, (int) op.getContentLength()); request = new NettyFullHttpRequest(HttpVersion.HTTP_1_1, method, pathAndQuery, content, false); } if (useHttp2) { // when operation is cloned, it may contain original streamId header. remove it. if (hasRequestHeaders) { op.getRequestHeaders().remove(Operation.STREAM_ID_HEADER); } // We set the operation so that once a streamId is assigned, we can record // the correspondence between the streamId and operation: this will let us // handle responses properly later. request.setOperation(op); } String pragmaHeader = op.getRequestHeader(Operation.PRAGMA_HEADER); if (op.isFromReplication() && pragmaHeader == null) { request.headers().set(HttpHeaderNames.PRAGMA, Operation.PRAGMA_DIRECTIVE_REPLICATED); } if (op.getTransactionId() != null) { request.headers().set(Operation.TRANSACTION_ID_HEADER, op.getTransactionId()); } if (op.getContextId() != null) { request.headers().set(Operation.CONTEXT_ID_HEADER, op.getContextId()); } AuthorizationContext ctx = op.getAuthorizationContext(); if (ctx != null && ctx.getToken() != null) { request.headers().set(Operation.REQUEST_AUTH_TOKEN_HEADER, ctx.getToken()); } boolean isXenonToXenon = op.isFromReplication(); boolean isRequestWithCallback = false; if (hasRequestHeaders) { for (Entry<String, String> nameValue : op.getRequestHeaders().entrySet()) { String key = nameValue.getKey(); if (!isXenonToXenon) { if (Operation.REQUEST_CALLBACK_LOCATION_HEADER.equals(key)) { isRequestWithCallback = true; isXenonToXenon = true; } else if (Operation.RESPONSE_CALLBACK_STATUS_HEADER.equals(key)) { isXenonToXenon = true; } } request.headers().set(nameValue.getKey(), nameValue.getValue()); } } request.headers().set(HttpHeaderNames.CONTENT_LENGTH, Long.toString(op.getContentLength())); request.headers().set(HttpHeaderNames.CONTENT_TYPE, op.getContentType()); request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE); if (!isXenonToXenon) { if (op.getCookies() != null) { String header = CookieJar.encodeCookies(op.getCookies()); request.headers().set(HttpHeaderNames.COOKIE, header); } if (op.hasReferer()) { request.headers().set(HttpHeaderNames.REFERER, op.getRefererAsString()); } request.headers().set(HttpHeaderNames.USER_AGENT, this.userAgent); if (op.getRequestHeader(Operation.ACCEPT_HEADER) == null) { request.headers().set(HttpHeaderNames.ACCEPT, Operation.MEDIA_TYPE_EVERYTHING_WILDCARDS); } request.headers().set(HttpHeaderNames.HOST, op.getUri().getHost()); } boolean doCookieJarUpdate = !isXenonToXenon; boolean stopTracking = !isRequestWithCallback; op.nestCompletion((o, e) -> { if (e != null) { fail(e, op, originalBody); return; } if (stopTracking) { stopTracking(op); } if (doCookieJarUpdate) { updateCookieJarFromResponseHeaders(o); } // After request is sent control is transferred to the // NettyHttpServerResponseHandler. The response handler will nest completions // and call complete() when response is received, which will invoke this completion op.complete(); }); op.getSocketContext().writeHttpRequest(request); } catch (Throwable e) { op.setBody(ServiceErrorResponse.create(e, Operation.STATUS_CODE_BAD_REQUEST, EnumSet.of(ErrorDetail.SHOULD_RETRY))); fail(e, op, originalBody); } }
From source file:com.wotifgroup.zopfli.JopfliDeflater.java
License:Apache License
@Override public void setInput(byte[] b, int off, int len) { this.buf.addComponent(Unpooled.wrappedBuffer(b, off, len)); this.buf.writerIndex(this.buf.capacity()); this.adler32.update(b, off, len); }
From source file:com.yahoo.pulsar.client.impl.MessageIdImpl.java
License:Apache License
public static MessageId fromByteArray(byte[] data) throws IOException { checkNotNull(data);/*from w w w.java 2 s . com*/ ByteBufCodedInputStream inputStream = ByteBufCodedInputStream .get(Unpooled.wrappedBuffer(data, 0, data.length)); PulsarApi.MessageIdData.Builder builder = PulsarApi.MessageIdData.newBuilder(); PulsarApi.MessageIdData idData; try { idData = builder.mergeFrom(inputStream, null).build(); } catch (UninitializedMessageException e) { throw new IOException(e); } MessageIdImpl messageId; if (idData.hasBatchIndex()) { messageId = new BatchMessageIdImpl(idData.getLedgerId(), idData.getEntryId(), idData.getPartition(), idData.getBatchIndex()); } else { messageId = new MessageIdImpl(idData.getLedgerId(), idData.getEntryId(), idData.getPartition()); } inputStream.recycle(); builder.recycle(); idData.recycle(); return messageId; }
From source file:io.gatling.netty.util.ahc.Utf8ByteBufCharsetDecoderTest.java
License:Apache License
@Test void byteBufs2StringShouldBeAbleToDealWithCharsWithVariableBytesLength() { String inputString = ""; byte[] inputBytes = inputString.getBytes(UTF_8); for (int i = 1; i < inputBytes.length - 1; i++) { ByteBuf buf1 = Unpooled.wrappedBuffer(inputBytes, 0, i); ByteBuf buf2 = Unpooled.wrappedBuffer(inputBytes, i, inputBytes.length - i); try {/*from w w w.ja va 2s. c o m*/ String output = ByteBufUtils.byteBuf2String(UTF_8, buf1, buf2); assertEquals(inputString, output); } finally { buf1.release(); buf2.release(); } } }