当前位置: 首页>>代码示例>>Java>>正文


Java DefaultHttpContent类代码示例

本文整理汇总了Java中io.netty.handler.codec.http.DefaultHttpContent的典型用法代码示例。如果您正苦于以下问题:Java DefaultHttpContent类的具体用法?Java DefaultHttpContent怎么用?Java DefaultHttpContent使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


DefaultHttpContent类属于io.netty.handler.codec.http包,在下文中一共展示了DefaultHttpContent类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: addContentChunk_adds_chunk_content_length_to_rawContentLengthInBytes

import io.netty.handler.codec.http.DefaultHttpContent; //导入依赖的package包/类
@Test
public void addContentChunk_adds_chunk_content_length_to_rawContentLengthInBytes() throws IOException {
    // given
    RequestInfoImpl<?> requestInfo = RequestInfoImpl.dummyInstanceForUnknownRequests();
    requestInfo.isCompleteRequestWithAllChunks = false;
    String chunk1String = UUID.randomUUID().toString();
    String lastChunkString = UUID.randomUUID().toString();
    byte[] chunk1Bytes = chunk1String.getBytes();
    byte[] lastChunkBytes = lastChunkString.getBytes();
    HttpContent chunk1 = new DefaultHttpContent(Unpooled.copiedBuffer(chunk1Bytes));
    HttpContent lastChunk = new DefaultLastHttpContent(Unpooled.copiedBuffer(lastChunkBytes));

    // when
    requestInfo.addContentChunk(chunk1);
    requestInfo.addContentChunk(lastChunk);

    // then
    assertThat(requestInfo.contentChunks.size(), is(2));
    assertThat(requestInfo.isCompleteRequestWithAllChunks(), is(true));
    assertThat(requestInfo.getRawContentLengthInBytes(), is(chunk1Bytes.length + lastChunkBytes.length));
}
 
开发者ID:Nike-Inc,项目名称:riposte,代码行数:22,代码来源:RequestInfoImplTest.java

示例2: testBuildContent

import io.netty.handler.codec.http.DefaultHttpContent; //导入依赖的package包/类
@Test
public void testBuildContent()
    throws Exception {
  HttpRequest nettyRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_0, HttpMethod.GET, "www.google.com");
  RecordedHttpRequestBuilder recordedHttpRequestBuilder = new RecordedHttpRequestBuilder(nettyRequest);

  String charset = "UTF-8";
  String str1 = "first content";
  HttpContent httpContent1 = new DefaultHttpContent(Unpooled.copiedBuffer(str1.getBytes(charset)));
  recordedHttpRequestBuilder.appendHttpContent(httpContent1);
  String str2 = "second content";
  HttpContent httpContent2 = new DefaultHttpContent(Unpooled.copiedBuffer(str2.getBytes(charset)));
  recordedHttpRequestBuilder.appendHttpContent(httpContent2);

  String lastStr = "Last chunk";
  HttpContent lastContent = new DefaultLastHttpContent(Unpooled.copiedBuffer(lastStr.getBytes(charset)));
  recordedHttpRequestBuilder.appendHttpContent(lastContent);

  RecordedHttpRequest recordedHttpRequest = recordedHttpRequestBuilder.build();
  Assert
      .assertEquals((str1 + str2 + lastStr).getBytes(charset), recordedHttpRequest.getHttpBody().getContent(charset));
}
 
开发者ID:linkedin,项目名称:flashback,代码行数:23,代码来源:RecordedHttpRequestBuilderTest.java

示例3: testBuild

import io.netty.handler.codec.http.DefaultHttpContent; //导入依赖的package包/类
@Test
public void testBuild()
    throws IOException {
  HttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_0, HttpResponseStatus.GATEWAY_TIMEOUT);
  RecordedHttpResponseBuilder recordedHttpResponseBuilder = new RecordedHttpResponseBuilder(httpResponse);

  String charset = "UTF-8";
  String str1 = "Hello world";
  HttpContent httpContent1 = new DefaultHttpContent(Unpooled.copiedBuffer(str1.getBytes(charset)));
  recordedHttpResponseBuilder.appendHttpContent(httpContent1);
  String str2 = "second content";
  HttpContent httpContent2 = new DefaultHttpContent(Unpooled.copiedBuffer(str2.getBytes(charset)));
  recordedHttpResponseBuilder.appendHttpContent(httpContent2);

  String lastStr = "Last chunk";
  HttpContent lastContent = new DefaultLastHttpContent(Unpooled.copiedBuffer(lastStr.getBytes(charset)));
  recordedHttpResponseBuilder.appendHttpContent(lastContent);
  RecordedHttpResponse recordedHttpResponse = recordedHttpResponseBuilder.build();
  Assert.assertEquals(recordedHttpResponse.getStatus(), HttpResponseStatus.GATEWAY_TIMEOUT.code());
  Assert.assertEquals((str1 + str2 + lastStr).getBytes(charset),
      recordedHttpResponse.getHttpBody().getContent(charset));
}
 
开发者ID:linkedin,项目名称:flashback,代码行数:23,代码来源:RecordedHttpResponseBuilderTest.java

示例4: onMessage

import io.netty.handler.codec.http.DefaultHttpContent; //导入依赖的package包/类
@Override
public void onMessage(HTTPCarbonMessage httpMessage) {
    executor.execute(() -> {
        try {
            InputStream inputStream = new HttpMessageDataStreamer(httpMessage).getInputStream();
            String response = new String(ByteStreams.toByteArray(inputStream), Charset.defaultCharset());
            String alteredContent = "Altered " + response + " content";

            HTTPCarbonMessage newMsg = httpMessage.cloneCarbonMessageWithOutData();
            newMsg.addHttpContent(new DefaultHttpContent(
                    Unpooled.wrappedBuffer(alteredContent.getBytes(Charset.defaultCharset()))));
            newMsg.setEndOfMsgAdded(true);

            httpMessage.respond(newMsg);
        } catch (IOException | ServerConnectorException e) {
            logger.error("Error occurred during message processing ", e);
        }

    });
}
 
开发者ID:wso2,项目名称:carbon-transports,代码行数:21,代码来源:ContentReadingListener.java

示例5: nextChunk

import io.netty.handler.codec.http.DefaultHttpContent; //导入依赖的package包/类
private HttpContent nextChunk( ChannelHandlerContext context )
    throws Exception
{
    if( isLastChunk )
    {
        isLastChunkRead = true;
        LastHttpContent lastChunk = new DefaultLastHttpContent( EMPTY_BUFFER );
        lastChunk.trailingHeaders().add( X_WERVAL_CONTENT_LENGTH, contentLength );
        return lastChunk;
    }
    ByteBuf buffer = chunkedBody.readChunk( context );
    if( chunkedBody.isEndOfInput() )
    {
        isLastChunk = true;
    }
    contentLength += buffer.readableBytes();
    return new DefaultHttpContent( buffer );
}
 
开发者ID:werval,项目名称:werval,代码行数:19,代码来源:HttpChunkedBodyEncoder.java

示例6: shouldDecodeSuccessBucketConfigResponse

import io.netty.handler.codec.http.DefaultHttpContent; //导入依赖的package包/类
@Test
public void shouldDecodeSuccessBucketConfigResponse() throws Exception {
    HttpResponse responseHeader = new DefaultHttpResponse(HttpVersion.HTTP_1_1, new HttpResponseStatus(200, "OK"));
    HttpContent responseChunk1 = new DefaultHttpContent(Unpooled.copiedBuffer("foo", CHARSET));
    HttpContent responseChunk2 = new DefaultLastHttpContent(Unpooled.copiedBuffer("bar", CHARSET));

    BucketConfigRequest requestMock = mock(BucketConfigRequest.class);
    requestQueue.add(requestMock);
    channel.writeInbound(responseHeader, responseChunk1, responseChunk2);
    channel.readInbound();

    assertEquals(1, eventSink.responseEvents().size());
    BucketConfigResponse event = (BucketConfigResponse) eventSink.responseEvents().get(0).getMessage();

    assertEquals(ResponseStatus.SUCCESS, event.status());
    assertEquals("foobar", event.config());
    assertTrue(requestQueue.isEmpty());
}
 
开发者ID:couchbase,项目名称:couchbase-jvm-core,代码行数:19,代码来源:ConfigHandlerTest.java

示例7: shouldDecodeListDesignDocumentsResponse

import io.netty.handler.codec.http.DefaultHttpContent; //导入依赖的package包/类
@Test
public void shouldDecodeListDesignDocumentsResponse() throws Exception {
    HttpResponse responseHeader = new DefaultHttpResponse(HttpVersion.HTTP_1_1, new HttpResponseStatus(200, "OK"));
    HttpContent responseChunk1 = new DefaultHttpContent(Unpooled.copiedBuffer("foo", CharsetUtil.UTF_8));
    HttpContent responseChunk2 = new DefaultLastHttpContent(Unpooled.copiedBuffer("bar", CharsetUtil.UTF_8));

    GetDesignDocumentsRequest requestMock = mock(GetDesignDocumentsRequest.class);
    requestQueue.add(requestMock);
    channel.writeInbound(responseHeader, responseChunk1, responseChunk2);

    assertEquals(1, eventSink.responseEvents().size());
    GetDesignDocumentsResponse event = (GetDesignDocumentsResponse) eventSink.responseEvents().get(0).getMessage();

    assertEquals(ResponseStatus.SUCCESS, event.status());
    assertEquals("foobar", event.content());
    assertTrue(requestQueue.isEmpty());
}
 
开发者ID:couchbase,项目名称:couchbase-jvm-core,代码行数:18,代码来源:ConfigHandlerTest.java

示例8: write

import io.netty.handler.codec.http.DefaultHttpContent; //导入依赖的package包/类
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    Class<?> recievedMsgClass = msg.getClass();

    if (HttpServerResponse.class.isAssignableFrom(recievedMsgClass)) {
        @SuppressWarnings("rawtypes")
        HttpServerResponse rxResponse = (HttpServerResponse) msg;
        if (keepAlive && !rxResponse.getHeaders().contains(HttpHeaders.Names.CONTENT_LENGTH)) {
            // If there is no content length & it is a keep alive connection. We need to specify the transfer
            // encoding as chunked as we always send data in multiple HttpContent.
            // On the other hand, if someone wants to not have chunked encoding, adding content-length will work
            // as expected.
            rxResponse.getHeaders().add(HttpHeaders.Names.TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED);
        }
        super.write(ctx, rxResponse.getNettyResponse(), promise);
    } else if (ByteBuf.class.isAssignableFrom(recievedMsgClass)) {
        HttpContent content = new DefaultHttpContent((ByteBuf) msg);
        super.write(ctx, content, promise);
    } else {
        super.write(ctx, msg, promise); // pass through, since we do not understand this message.
    }

}
 
开发者ID:allenxwang,项目名称:RxNetty,代码行数:24,代码来源:ServerRequestResponseConverter.java

示例9: closeTest

import io.netty.handler.codec.http.DefaultHttpContent; //导入依赖的package包/类
/**
 * Tests that {@link NettyRequest#close()} leaves any added {@link HttpContent} the way it was before it was added.
 * (i.e no reference count changes).
 * @throws RestServiceException
 */
@Test
public void closeTest() throws RestServiceException {
  Channel channel = new MockChannel();
  NettyRequest nettyRequest = createNettyRequest(HttpMethod.POST, "/", null, channel);
  Queue<HttpContent> httpContents = new LinkedBlockingQueue<HttpContent>();
  for (int i = 0; i < 5; i++) {
    ByteBuffer content = ByteBuffer.wrap(TestUtils.getRandomBytes(1024));
    HttpContent httpContent = new DefaultHttpContent(Unpooled.wrappedBuffer(content));
    nettyRequest.addContent(httpContent);
    httpContents.add(httpContent);
  }
  closeRequestAndValidate(nettyRequest, channel);
  while (httpContents.peek() != null) {
    assertEquals("Reference count of http content has changed", 1, httpContents.poll().refCnt());
  }
}
 
开发者ID:linkedin,项目名称:ambry,代码行数:22,代码来源:NettyRequestTest.java

示例10: splitContent

import io.netty.handler.codec.http.DefaultHttpContent; //导入依赖的package包/类
/**
 * Splits the given {@code contentBytes} into {@code numChunks} chunks and stores them in {@code httpContents}.
 * @param contentBytes the content that needs to be split.
 * @param numChunks the number of chunks to split {@code contentBytes} into.
 * @param httpContents the {@link List<HttpContent>} that will contain all the content in parts.
 * @param useCopyForcingByteBuf if {@code true}, uses {@link CopyForcingByteBuf} instead of the default
 *                              {@link ByteBuf}.
 */
private void splitContent(byte[] contentBytes, int numChunks, List<HttpContent> httpContents,
    boolean useCopyForcingByteBuf) {
  int individualPartSize = contentBytes.length / numChunks;
  ByteBuf content;
  for (int addedContentCount = 0; addedContentCount < numChunks - 1; addedContentCount++) {
    if (useCopyForcingByteBuf) {
      content =
          CopyForcingByteBuf.wrappedBuffer(contentBytes, addedContentCount * individualPartSize, individualPartSize);
    } else {
      content = Unpooled.wrappedBuffer(contentBytes, addedContentCount * individualPartSize, individualPartSize);
    }
    httpContents.add(new DefaultHttpContent(content));
  }
  if (useCopyForcingByteBuf) {
    content =
        CopyForcingByteBuf.wrappedBuffer(contentBytes, (numChunks - 1) * individualPartSize, individualPartSize);
  } else {
    content = Unpooled.wrappedBuffer(contentBytes, (numChunks - 1) * individualPartSize, individualPartSize);
  }
  httpContents.add(new DefaultLastHttpContent(content));
}
 
开发者ID:linkedin,项目名称:ambry,代码行数:30,代码来源:NettyRequestTest.java

示例11: doPostTest

import io.netty.handler.codec.http.DefaultHttpContent; //导入依赖的package包/类
/**
 * Does the post test by sending the request and content to {@link NettyMessageProcessor} through an
 * {@link EmbeddedChannel} and returns the data stored in the {@link InMemoryRouter} as a result of the post.
 * @param postRequest the POST request as a {@link HttpRequest}.
 * @param contentToSend the content to be sent as a part of the POST.
 * @return the data stored in the {@link InMemoryRouter} as a result of the POST.
 * @throws InterruptedException
 */
private ByteBuffer doPostTest(HttpRequest postRequest, List<ByteBuffer> contentToSend) throws InterruptedException {
  EmbeddedChannel channel = createChannel();

  // POST
  notificationSystem.reset();
  postRequest.headers().set(RestUtils.Headers.AMBRY_CONTENT_TYPE, "application/octet-stream");
  HttpUtil.setKeepAlive(postRequest, false);
  channel.writeInbound(postRequest);
  if (contentToSend != null) {
    for (ByteBuffer content : contentToSend) {
      channel.writeInbound(new DefaultHttpContent(Unpooled.wrappedBuffer(content)));
    }
    channel.writeInbound(LastHttpContent.EMPTY_LAST_CONTENT);
  }
  if (!notificationSystem.operationCompleted.await(100, TimeUnit.MILLISECONDS)) {
    fail("Post did not succeed after 100ms. There is an error or timeout needs to increase");
  }
  assertNotNull("Blob id operated on cannot be null", notificationSystem.blobIdOperatedOn);
  return router.getActiveBlobs().get(notificationSystem.blobIdOperatedOn).getBlob();
}
 
开发者ID:linkedin,项目名称:ambry,代码行数:29,代码来源:NettyMessageProcessorTest.java

示例12: subscribe

import io.netty.handler.codec.http.DefaultHttpContent; //导入依赖的package包/类
@Override
public void subscribe(Subscriber<? super HttpContent> subscriber) {
    publisher.subscribe(new Subscriber<ByteBuffer>() {
        @Override
        public void onSubscribe(Subscription subscription) {
            subscriber.onSubscribe(subscription);
        }

        @Override
        public void onNext(ByteBuffer byteBuffer) {
            ByteBuf buffer = channel.alloc().buffer(byteBuffer.remaining());
            buffer.writeBytes(byteBuffer);
            HttpContent content = new DefaultHttpContent(buffer);
            subscriber.onNext(content);
        }

        @Override
        public void onError(Throwable t) {
            subscriber.onError(t);
        }

        @Override
        public void onComplete() {
            subscriber.onComplete();
        }
    });
}
 
开发者ID:aws,项目名称:aws-sdk-java-v2,代码行数:28,代码来源:RunnableRequest.java

示例13: addContentChunk_and_getRawConent_and_getRawContentBytes_work_as_expected_for_last_chunk

import io.netty.handler.codec.http.DefaultHttpContent; //导入依赖的package包/类
@Test
public void addContentChunk_and_getRawConent_and_getRawContentBytes_work_as_expected_for_last_chunk() throws IOException {
    // given
    RequestInfoImpl<?> requestInfo = RequestInfoImpl.dummyInstanceForUnknownRequests();
    requestInfo.isCompleteRequestWithAllChunks = false;
    String chunk1String = UUID.randomUUID().toString();
    String lastChunkString = UUID.randomUUID().toString();
    byte[] chunk1Bytes = chunk1String.getBytes();
    byte[] lastChunkBytes = lastChunkString.getBytes();
    HttpContent chunk1 = new DefaultHttpContent(Unpooled.copiedBuffer(chunk1Bytes));
    HttpContent lastChunk = new DefaultLastHttpContent(Unpooled.copiedBuffer(lastChunkBytes));
    assertThat(chunk1.refCnt(), is(1));
    assertThat(lastChunk.refCnt(), is(1));
    assertThat(requestInfo.getRawContentBytes(), nullValue());
    assertThat(requestInfo.getRawContent(), nullValue());

    // when
    requestInfo.addContentChunk(chunk1);
    requestInfo.addContentChunk(lastChunk);

    // then
    assertThat(chunk1.refCnt(), is(2));
    assertThat(lastChunk.refCnt(), is(2));
    assertThat(requestInfo.contentChunks.size(), is(2));
    assertThat(requestInfo.isCompleteRequestWithAllChunks(), is(true));
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    baos.write(chunk1Bytes);
    baos.write(lastChunkBytes);
    assertThat(requestInfo.getRawContentBytes(), is(baos.toByteArray()));
    String rawContentString = requestInfo.getRawContent();
    assertThat(requestInfo.getRawContent(), is(chunk1String + lastChunkString));
    assertThat(requestInfo.getRawContent() == rawContentString, is(true)); // Verify that the raw content string is cached the first time it's loaded and reused for subsequent calls
    assertThat(chunk1.refCnt(), is(1));
    assertThat(lastChunk.refCnt(), is(1));
}
 
开发者ID:Nike-Inc,项目名称:riposte,代码行数:36,代码来源:RequestInfoImplTest.java

示例14: DefaultHttpContent

import io.netty.handler.codec.http.DefaultHttpContent; //导入依赖的package包/类
@Test
public void addContentChunk_does_not_add_chunk_to_contentChunks_list_if_contentChunksWillBeReleasedExternally_is_true() {
    // given
    RequestInfoImpl<?> requestInfo = RequestInfoImpl.dummyInstanceForUnknownRequests();
    requestInfo.isCompleteRequestWithAllChunks = false;
    requestInfo.contentChunksWillBeReleasedExternally();
    HttpContent chunk = new DefaultHttpContent(Unpooled.copiedBuffer(UUID.randomUUID().toString(), CharsetUtil.UTF_8));

    // when
    requestInfo.addContentChunk(chunk);

    // then
    Assertions.assertThat(requestInfo.contentChunks).isEmpty();
}
 
开发者ID:Nike-Inc,项目名称:riposte,代码行数:15,代码来源:RequestInfoImplTest.java

示例15: convertContentChunksToRawString_and_convertContentChunksToRawBytes_works

import io.netty.handler.codec.http.DefaultHttpContent; //导入依赖的package包/类
@Test
@DataProvider(value = {
        "[email protected]#$%^&*/?.,<>;:'\"{}[]()     | [email protected]#$%^&*/?.,<>;:'\"{}[]()    |   UTF-8",
        "[email protected]#$%^&*/?.,<>;:'\"{}[]()     | [email protected]#$%^&*/?.,<>;:'\"{}[]()    |   UTF-16",
        "[email protected]#$%^&*/?.,<>;:'\"{}[]()     | [email protected]#$%^&*/?.,<>;:'\"{}[]()    |   ISO-8859-1"
}, splitBy = "\\|")
public void convertContentChunksToRawString_and_convertContentChunksToRawBytes_works(String chunk1Base, String chunk2Base, String charsetString) throws IOException {
    // given
    Charset contentCharset = Charset.forName(charsetString);
    String chunk1Content = chunk1Base + "-" + UUID.randomUUID().toString();
    String chunk2Content = chunk2Base + "-" + UUID.randomUUID().toString();
    byte[] chunk1Bytes = chunk1Content.getBytes(contentCharset);
    byte[] chunk2Bytes = chunk2Content.getBytes(contentCharset);
    ByteBuf chunk1ByteBuf = Unpooled.copiedBuffer(chunk1Bytes);
    ByteBuf chunk2ByteBuf = Unpooled.copiedBuffer(chunk2Bytes);
    Collection<HttpContent> chunkCollection = Arrays.asList(new DefaultHttpContent(chunk1ByteBuf), new DefaultHttpContent(chunk2ByteBuf));

    // when
    String resultString = HttpUtils.convertContentChunksToRawString(contentCharset, chunkCollection);
    byte[] resultBytes = HttpUtils.convertContentChunksToRawBytes(chunkCollection);

    // then
    String expectedResultString = chunk1Content + chunk2Content;
    assertThat(resultString, is(expectedResultString));
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    baos.write(chunk1Bytes);
    baos.write(chunk2Bytes);
    assertThat(resultBytes, is(baos.toByteArray()));
}
 
开发者ID:Nike-Inc,项目名称:riposte,代码行数:30,代码来源:HttpUtilsTest.java


注:本文中的io.netty.handler.codec.http.DefaultHttpContent类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。