本文整理汇总了Java中io.netty.handler.codec.http.DefaultLastHttpContent类的典型用法代码示例。如果您正苦于以下问题:Java DefaultLastHttpContent类的具体用法?Java DefaultLastHttpContent怎么用?Java DefaultLastHttpContent使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
DefaultLastHttpContent类属于io.netty.handler.codec.http包,在下文中一共展示了DefaultLastHttpContent类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: publish
import io.netty.handler.codec.http.DefaultLastHttpContent; //导入依赖的package包/类
/**
* This method will be called when events need to be published via this sink
*
* @param payload payload of the event based on the supported event class exported by the extensions
* @param dynamicOptions holds the dynamic options of this sink and Use this object to obtain dynamic options.
* @throws ConnectionUnavailableException if end point is unavailable the ConnectionUnavailableException thrown
* such that the system will take care retrying for connection
*/
@Override
public void publish(Object payload, DynamicOptions dynamicOptions) throws ConnectionUnavailableException {
String headers = httpHeaderOption.getValue(dynamicOptions);
String httpMethod = HttpConstants.EMPTY_STRING.equals(httpMethodOption.getValue(dynamicOptions)) ?
HttpConstants.METHOD_DEFAULT : httpMethodOption.getValue(dynamicOptions);
List<Header> headersList = HttpSinkUtil.getHeaders(headers);
String contentType = HttpSinkUtil.getContentType(mapType, headersList);
String messageBody = (String) payload;
HTTPCarbonMessage cMessage = createHttpCarbonMessage(httpMethod);
cMessage = generateCarbonMessage(headersList, contentType, httpMethod, cMessage);
cMessage.addHttpContent(new DefaultLastHttpContent(Unpooled.wrappedBuffer(messageBody
.getBytes(Charset.defaultCharset()))));
clientConnector.send(cMessage);
}
示例2: startDownTask
import io.netty.handler.codec.http.DefaultLastHttpContent; //导入依赖的package包/类
public static void startDownTask(TaskInfo taskInfo, HttpRequest httpRequest,
HttpResponse httpResponse, Channel clientChannel) {
HttpHeaders httpHeaders = httpResponse.headers();
HttpDownInfo httpDownInfo = new HttpDownInfo(taskInfo, httpRequest);
HttpDownServer.DOWN_CONTENT.put(taskInfo.getId(), httpDownInfo);
httpHeaders.clear();
httpResponse.setStatus(HttpResponseStatus.OK);
httpHeaders.set(HttpHeaderNames.CONTENT_TYPE, "text/html");
String host = HttpDownServer.isDev() ? "localhost"
: ((InetSocketAddress) clientChannel.localAddress()).getHostString();
String js =
"<script>window.top.location.href='http://" + host + ":" + HttpDownServer.VIEW_SERVER_PORT
+ "/#/tasks/new/" + httpDownInfo
.getTaskInfo().getId()
+ "';</script>";
HttpContent content = new DefaultLastHttpContent();
content.content().writeBytes(js.getBytes());
httpHeaders.set(HttpHeaderNames.CONTENT_LENGTH, js.getBytes().length);
clientChannel.writeAndFlush(httpResponse);
clientChannel.writeAndFlush(content);
clientChannel.close();
}
示例3: addContentChunk_adds_last_chunk_trailing_headers
import io.netty.handler.codec.http.DefaultLastHttpContent; //导入依赖的package包/类
@Test
public void addContentChunk_adds_last_chunk_trailing_headers() {
// given
RequestInfoImpl<?> requestInfo = RequestInfoImpl.dummyInstanceForUnknownRequests();
requestInfo.isCompleteRequestWithAllChunks = false;
LastHttpContent lastChunk = new DefaultLastHttpContent(Unpooled.copiedBuffer(UUID.randomUUID().toString(), CharsetUtil.UTF_8));
String headerKey = UUID.randomUUID().toString();
List<String> headerVal = Arrays.asList(UUID.randomUUID().toString(), UUID.randomUUID().toString());
lastChunk.trailingHeaders().add(headerKey, headerVal);
// when
requestInfo.addContentChunk(lastChunk);
// then
assertThat(requestInfo.trailingHeaders.names().size(), is(1));
assertThat(requestInfo.trailingHeaders.getAll(headerKey), is(headerVal));
}
示例4: addContentChunk_adds_chunk_content_length_to_rawContentLengthInBytes
import io.netty.handler.codec.http.DefaultLastHttpContent; //导入依赖的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));
}
示例5: addDecoderReplaysLastHttp
import io.netty.handler.codec.http.DefaultLastHttpContent; //导入依赖的package包/类
@Test
public void addDecoderReplaysLastHttp() throws Exception {
ByteBuf buf = Unpooled.copiedBuffer("{\"foo\":1}", CharsetUtil.UTF_8);
EmbeddedChannel channel = new EmbeddedChannel();
HttpClientOperations ops = new HttpClientOperations(channel,
(response, request) -> null, handler);
ops.addHandler(new JsonObjectDecoder());
channel.writeInbound(new DefaultLastHttpContent(buf));
assertThat(channel.pipeline().names().iterator().next(), is("JsonObjectDecoder$extractor"));
Object content = channel.readInbound();
assertThat(content, instanceOf(ByteBuf.class));
((ByteBuf) content).release();
content = channel.readInbound();
assertThat(content, instanceOf(LastHttpContent.class));
((LastHttpContent) content).release();
assertThat(channel.readInbound(), nullValue());
}
示例6: addNamedDecoderReplaysLastHttp
import io.netty.handler.codec.http.DefaultLastHttpContent; //导入依赖的package包/类
@Test
public void addNamedDecoderReplaysLastHttp() throws Exception {
ByteBuf buf = Unpooled.copiedBuffer("{\"foo\":1}", CharsetUtil.UTF_8);
EmbeddedChannel channel = new EmbeddedChannel();
HttpClientOperations ops = new HttpClientOperations(channel,
(response, request) -> null, handler);
ops.addHandler("json", new JsonObjectDecoder());
channel.writeInbound(new DefaultLastHttpContent(buf));
assertThat(channel.pipeline().names().iterator().next(), is("json$extractor"));
Object content = channel.readInbound();
assertThat(content, instanceOf(ByteBuf.class));
((ByteBuf) content).release();
content = channel.readInbound();
assertThat(content, instanceOf(LastHttpContent.class));
((LastHttpContent) content).release();
assertThat(channel.readInbound(), nullValue());
}
示例7: addEncoderReplaysLastHttp
import io.netty.handler.codec.http.DefaultLastHttpContent; //导入依赖的package包/类
@Test
public void addEncoderReplaysLastHttp() throws Exception {
ByteBuf buf = Unpooled.copiedBuffer("{\"foo\":1}", CharsetUtil.UTF_8);
EmbeddedChannel channel = new EmbeddedChannel();
HttpClientOperations ops = new HttpClientOperations(channel,
(response, request) -> null, handler);
ops.addHandler(new JsonObjectDecoder());
channel.writeInbound(new DefaultLastHttpContent(buf));
assertThat(channel.pipeline().names().iterator().next(), is("JsonObjectDecoder$extractor"));
Object content = channel.readInbound();
assertThat(content, instanceOf(ByteBuf.class));
((ByteBuf) content).release();
content = channel.readInbound();
assertThat(content, instanceOf(LastHttpContent.class));
((LastHttpContent) content).release();
assertThat(channel.readInbound(), nullValue());
}
示例8: addNamedEncoderReplaysLastHttp
import io.netty.handler.codec.http.DefaultLastHttpContent; //导入依赖的package包/类
@Test
public void addNamedEncoderReplaysLastHttp() throws Exception {
ByteBuf buf = Unpooled.copiedBuffer("{\"foo\":1}", CharsetUtil.UTF_8);
EmbeddedChannel channel = new EmbeddedChannel();
HttpClientOperations ops = new HttpClientOperations(channel,
(response, request) -> null, handler);
ops.addHandler("json", new JsonObjectDecoder());
channel.writeInbound(new DefaultLastHttpContent(buf));
assertThat(channel.pipeline().names().iterator().next(), is("json$extractor"));
Object content = channel.readInbound();
assertThat(content, instanceOf(ByteBuf.class));
((ByteBuf) content).release();
content = channel.readInbound();
assertThat(content, instanceOf(LastHttpContent.class));
((LastHttpContent) content).release();
assertThat(channel.readInbound(), nullValue());
}
示例9: testBuildContent
import io.netty.handler.codec.http.DefaultLastHttpContent; //导入依赖的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));
}
示例10: testBuild
import io.netty.handler.codec.http.DefaultLastHttpContent; //导入依赖的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));
}
示例11: handleThrowable
import io.netty.handler.codec.http.DefaultLastHttpContent; //导入依赖的package包/类
private void handleThrowable(MicroservicesRegistryImpl currentMicroservicesRegistry, Throwable throwable,
Request request) {
Optional<ExceptionMapper> exceptionMapper = currentMicroservicesRegistry.getExceptionMapper(throwable);
if (exceptionMapper.isPresent()) {
org.wso2.msf4j.Response msf4jResponse = new org.wso2.msf4j.Response(request);
msf4jResponse.setEntity(exceptionMapper.get().toResponse(throwable));
msf4jResponse.send();
} else {
log.warn("Unmapped exception", throwable);
try {
HTTPCarbonMessage response = HttpUtil.createTextResponse(
javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
"Exception occurred :" + throwable.getMessage());
response.addHttpContent(new DefaultLastHttpContent());
request.respond(response);
} catch (ServerConnectorException e) {
log.error("Error while sending the response.", e);
}
}
}
示例12: writeData
import io.netty.handler.codec.http.DefaultLastHttpContent; //导入依赖的package包/类
/**
* Write the entity to the carbon message.
*/
@Override
public void writeData(HTTPCarbonMessage carbonMessage, Object entity, String mediaType, int chunkSize,
HTTPCarbonMessage responder) {
mediaType = (mediaType != null) ? mediaType : MediaType.WILDCARD;
ByteBuffer byteBuffer = BeanConverter.getConverter(mediaType).convertToMedia(entity);
carbonMessage.addHttpContent(new DefaultLastHttpContent(Unpooled.wrappedBuffer(byteBuffer)));
if (chunkSize == Response.NO_CHUNK) {
carbonMessage.setHeader(Constants.HTTP_CONTENT_LENGTH, String.valueOf(byteBuffer.remaining()));
} else {
carbonMessage.setHeader(Constants.HTTP_TRANSFER_ENCODING, CHUNKED);
}
carbonMessage.setHeader(Constants.HTTP_CONTENT_TYPE, mediaType);
try {
responder.respond(carbonMessage);
} catch (ServerConnectorException e) {
throw new RuntimeException("Error while sending the response.", e);
}
}
示例13: createTextResponse
import io.netty.handler.codec.http.DefaultLastHttpContent; //导入依赖的package包/类
/**
* Create a CarbonMessage for a specific status code.
*
* @param status HTTP status code
* @param msg message text
* @return CarbonMessage representing the status
*/
public static HTTPCarbonMessage createTextResponse(int status, String msg) {
HTTPCarbonMessage response = new HTTPCarbonMessage(
new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(status)));
response.setProperty(Constants.HTTP_STATUS_CODE, status);
if (msg != null) {
response.setHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(msg.length()));
byte[] msgArray = null;
try {
msgArray = msg.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Failed to get the byte array from responseValue", e);
}
ByteBuffer byteBuffer = ByteBuffer.allocate(msgArray.length);
byteBuffer.put(msgArray);
byteBuffer.flip();
response.addHttpContent(new DefaultLastHttpContent(Unpooled.wrappedBuffer(byteBuffer)));
} else {
response.setHeader(HttpHeaders.CONTENT_LENGTH, "0");
}
return response;
}
示例14: onDataRead
import io.netty.handler.codec.http.DefaultLastHttpContent; //导入依赖的package包/类
@Override
public int onDataRead(ChannelHandlerContext ctx, int streamId, ByteBuf data, int padding, boolean endOfStream)
throws Http2Exception {
HTTPCarbonMessage cMsg = streamIdRequestMap.get(streamId);
if (cMsg != null) {
cMsg.addHttpContent(new DefaultLastHttpContent(data.retain()));
if (endOfStream) {
cMsg.setEndOfMsgAdded(true);
// if (HTTPTransportContextHolder.getInstance().getHandlerExecutor() != null) {
// HTTPTransportContextHolder.getInstance().getHandlerExecutor().executeAtSourceRequestSending(cMsg);
// }
}
}
return data.readableBytes() + padding;
}
示例15: onMessage
import io.netty.handler.codec.http.DefaultLastHttpContent; //导入依赖的package包/类
@Override
public void onMessage(HTTPCarbonMessage httpRequestMessage) {
executor.execute(() -> {
HTTPCarbonMessage cMsg = new HTTPCarbonMessage(new DefaultHttpResponse(HttpVersion.HTTP_1_1,
HttpResponseStatus.OK));
cMsg.setHeader(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
cMsg.setHeader(HttpHeaders.Names.TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED);
cMsg.setHeader(HttpHeaders.Names.CONTENT_TYPE, Constants.TEXT_PLAIN);
cMsg.setProperty(Constants.HTTP_STATUS_CODE, 200);
try {
httpRequestMessage.respond(cMsg);
} catch (ServerConnectorException e) {
logger.error("Error occurred during message notification: " + e.getMessage());
}
while (true) {
HttpContent httpContent = httpRequestMessage.getHttpContent();
cMsg.addHttpContent(httpContent);
if (httpContent instanceof LastHttpContent) {
cMsg.addHttpContent(new DefaultLastHttpContent());
httpRequestMessage.release();
break;
}
}
});
}