本文整理汇总了Java中io.netty.handler.codec.http.DefaultHttpResponse类的典型用法代码示例。如果您正苦于以下问题:Java DefaultHttpResponse类的具体用法?Java DefaultHttpResponse怎么用?Java DefaultHttpResponse使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
DefaultHttpResponse类属于io.netty.handler.codec.http包,在下文中一共展示了DefaultHttpResponse类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: exceptionCaught
import io.netty.handler.codec.http.DefaultHttpResponse; //导入依赖的package包/类
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable e)
throws Exception
{
// handle the case of to big requests.
if (e.getCause() instanceof TooLongFrameException)
{
DefaultHttpResponse response = new DefaultHttpResponse(HTTP_1_1, REQUEST_ENTITY_TOO_LARGE);
ctx.write(response).addListener(ChannelFutureListener.CLOSE);
}
else
{
if(ctx.channel().isActive()){ // 连接已断开就不打印了
logger.warn("Exception caught by request handler", e);
}
ctx.close();
}
}
示例2: onCreate
import io.netty.handler.codec.http.DefaultHttpResponse; //导入依赖的package包/类
private void onCreate(ChannelHandlerContext ctx)
throws IOException, URISyntaxException {
writeContinueHeader(ctx);
final String nnId = params.namenodeId();
final int bufferSize = params.bufferSize();
final short replication = params.replication();
final long blockSize = params.blockSize();
final FsPermission permission = params.permission();
EnumSet<CreateFlag> flags = params.overwrite() ?
EnumSet.of(CreateFlag.CREATE, CreateFlag.OVERWRITE)
: EnumSet.of(CreateFlag.CREATE);
final DFSClient dfsClient = newDfsClient(nnId, confForCreate);
OutputStream out = dfsClient.createWrappedOutputStream(dfsClient.create(
path, permission, flags, replication,
blockSize, null, bufferSize, null), null);
DefaultHttpResponse resp = new DefaultHttpResponse(HTTP_1_1, CREATED);
final URI uri = new URI(HDFS_URI_SCHEME, nnId, path, null, null);
resp.headers().set(LOCATION, uri.toString());
resp.headers().set(CONTENT_LENGTH, 0);
ctx.pipeline().replace(this, HdfsWriter.class.getSimpleName(),
new HdfsWriter(dfsClient, out, resp));
}
示例3: writeResponseHead
import io.netty.handler.codec.http.DefaultHttpResponse; //导入依赖的package包/类
@Override
public void writeResponseHead(Response restletResponse) throws IOException {
setNettyResponse(new DefaultHttpResponse(HTTP_1_1, new HttpResponseStatus(getStatusCode(), getReasonPhrase())));
HttpHeaders headers = getNettyResponse().headers();
// this.response.clear();
for (Header header : getResponseHeaders()) {
headers.add(header.getName(), header.getValue());
}
// Decide whether to close the connection or not.
if (isKeepAlive()) {
headers.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
getNettyChannel().write(getNettyResponse());
} else {
getNettyChannel().writeAndFlush(getNettyResponse()).addListener(ChannelFutureListener.CLOSE);
}
}
示例4: startProxyServerWithFilterAnsweringStatusCode
import io.netty.handler.codec.http.DefaultHttpResponse; //导入依赖的package包/类
private void startProxyServerWithFilterAnsweringStatusCode(int statusCode) {
final HttpResponseStatus status = HttpResponseStatus.valueOf(statusCode);
HttpFiltersSource filtersSource = new HttpFiltersSourceAdapter() {
@Override
public HttpFilters filterRequest(HttpRequest originalRequest) {
return new HttpFiltersAdapter(originalRequest) {
@Override
public HttpResponse clientToProxyRequest(HttpObject httpObject) {
return new DefaultHttpResponse(HttpVersion.HTTP_1_1, status);
}
};
}
};
proxyServer = DefaultHttpProxyServer.bootstrap()
.withPort(0)
.withFiltersSource(filtersSource)
.start();
}
示例5: exceptionCaught
import io.netty.handler.codec.http.DefaultHttpResponse; //导入依赖的package包/类
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
Attribute<HttpServerChannelHandler> attr = ctx.attr(SERVER_HANDLER_KEY);
HttpServerChannelHandler handler = attr.get();
if (handler != null) {
handler.exceptionCaught(ctx, cause);
} else {
if (cause instanceof ClosedChannelException) {
// The channel is closed so we do nothing here
LOG.debug("Channel already closed. Ignoring this exception.");
return;
} else {
// we cannot throw the exception here
LOG.warn("HttpServerChannelHandler is not found as attachment to handle exception, send 404 back to the client.", cause);
// Now we just send 404 back to the client
HttpResponse response = new DefaultHttpResponse(HTTP_1_1, NOT_FOUND);
response.headers().set(Exchange.CONTENT_TYPE, "text/plain");
response.headers().set(Exchange.CONTENT_LENGTH, 0);
ctx.writeAndFlush(response);
ctx.close();
}
}
}
示例6: testMesosStreamIdIsSavedForSuccessfulSubscribeCall
import io.netty.handler.codec.http.DefaultHttpResponse; //导入依赖的package包/类
@Test
public void testMesosStreamIdIsSavedForSuccessfulSubscribeCall() throws Exception {
final AtomicReference<String> mesosStreamId = new AtomicReference<>(null);
final Func1<HttpClientResponse<ByteBuf>, Observable<ByteBuf>> f = MesosClient.verifyResponseOk(
"Subscribe",
mesosStreamId,
StringMessageCodec.UTF8_STRING.mediaType()
);
final DefaultHttpResponse nettyResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
nettyResponse.headers().add("Mesos-Stream-Id", "streamId");
nettyResponse.headers().add("Content-Type", StringMessageCodec.UTF8_STRING.mediaType());
final HttpClientResponse<ByteBuf> response = new HttpClientResponse<>(
nettyResponse,
UnicastContentSubject.create(1000, TimeUnit.MILLISECONDS)
);
f.call(response);
assertThat(mesosStreamId.get()).isEqualTo("streamId");
}
示例7: testMesosStreamIdIsNotSavedForUnsuccessfulSubscribeCall
import io.netty.handler.codec.http.DefaultHttpResponse; //导入依赖的package包/类
@Test
public void testMesosStreamIdIsNotSavedForUnsuccessfulSubscribeCall() throws Exception {
final AtomicReference<String> mesosStreamId = new AtomicReference<>(null);
final Func1<HttpClientResponse<ByteBuf>, Observable<ByteBuf>> f = MesosClient.verifyResponseOk(
"Subscribe",
mesosStreamId,
StringMessageCodec.UTF8_STRING.mediaType()
);
final DefaultHttpResponse nettyResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST);
nettyResponse.headers().add("Mesos-Stream-Id", "streamId");
nettyResponse.headers().add("Content-Type", StringMessageCodec.UTF8_STRING.mediaType());
final HttpClientResponse<ByteBuf> response = new HttpClientResponse<>(
nettyResponse,
UnicastContentSubject.create(1000, TimeUnit.MILLISECONDS)
);
try {
f.call(response);
} catch (Mesos4xxException e) {
// expected
}
assertThat(mesosStreamId.get()).isEqualTo(null);
}
示例8: testVerifyResponseOk_ensuresContentTypeOfResponseMatchesReceiveCodec
import io.netty.handler.codec.http.DefaultHttpResponse; //导入依赖的package包/类
@Test
public void testVerifyResponseOk_ensuresContentTypeOfResponseMatchesReceiveCodec() throws Exception {
final Func1<HttpClientResponse<ByteBuf>, Observable<ByteBuf>> f = MesosClient.verifyResponseOk(
"Subscribe",
new AtomicReference<>(),
StringMessageCodec.UTF8_STRING.mediaType()
);
final DefaultHttpResponse nettyResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
nettyResponse.headers().add("Content-Type", "text/html");
final HttpClientResponse<ByteBuf> response = new HttpClientResponse<>(
nettyResponse,
UnicastContentSubject.create(1000, TimeUnit.MILLISECONDS)
);
try {
f.call(response);
} catch (MesosException e) {
final String expected = String.format(
"Response had Content-Type \"%s\" expected \"%s\"",
"text/html",
StringMessageCodec.UTF8_STRING.mediaType()
);
assertThat(e.getContext().getMessage()).isEqualTo(expected);
}
}
示例9: createTextResponse
import io.netty.handler.codec.http.DefaultHttpResponse; //导入依赖的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;
}
示例10: onMessage
import io.netty.handler.codec.http.DefaultHttpResponse; //导入依赖的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;
}
}
});
}
示例11: beginHTTPResponse
import io.netty.handler.codec.http.DefaultHttpResponse; //导入依赖的package包/类
public static void beginHTTPResponse(ChannelHandlerContext ctx, FullHttpRequest request, long lastModified,
String path, long fileLength) {
HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
HttpUtil.setContentLength(response, fileLength);
setContentTypeHeader(response, path);
response.headers().set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
setDateAndCacheHeaders(response, lastModified);
if (HttpUtil.isKeepAlive(request)) {
response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
}
// Write the initial line and the header.
ctx.write(response);
}
示例12: httpErrorsAreSupported
import io.netty.handler.codec.http.DefaultHttpResponse; //导入依赖的package包/类
/** Test that the handler correctly supports http error codes i.e. 404 (NOT FOUND). */
@Test
public void httpErrorsAreSupported() throws IOException {
EmbeddedChannel ch = new EmbeddedChannel(new HttpDownloadHandler(null));
ByteArrayOutputStream out = Mockito.spy(new ByteArrayOutputStream());
DownloadCommand cmd = new DownloadCommand(CACHE_URI, true, "abcdef", out);
ChannelPromise writePromise = ch.newPromise();
ch.writeOneOutbound(cmd, writePromise);
HttpResponse response =
new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND);
response.headers().set(HttpHeaders.CONNECTION, HttpHeaderValues.CLOSE);
ch.writeInbound(response);
assertThat(writePromise.isDone()).isTrue();
assertThat(writePromise.cause()).isInstanceOf(HttpException.class);
assertThat(((HttpException) writePromise.cause()).status())
.isEqualTo(HttpResponseStatus.NOT_FOUND);
// No data should have been written to the OutputStream and it should have been closed.
assertThat(out.size()).isEqualTo(0);
verify(out).close();
assertThat(ch.isOpen()).isFalse();
}
示例13: shouldDecodeSuccessfulGetDesignDocumentResponse
import io.netty.handler.codec.http.DefaultHttpResponse; //导入依赖的package包/类
@Test
public void shouldDecodeSuccessfulGetDesignDocumentResponse() throws Exception {
String response = Resources.read("designdoc_success.json", this.getClass());
HttpResponse responseHeader = new DefaultHttpResponse(HttpVersion.HTTP_1_1, new HttpResponseStatus(200, "OK"));
HttpContent responseChunk = new DefaultLastHttpContent(Unpooled.copiedBuffer(response, CharsetUtil.UTF_8));
GetDesignDocumentRequest requestMock = mock(GetDesignDocumentRequest.class);
when(requestMock.name()).thenReturn("name");
when(requestMock.development()).thenReturn(true);
queue.add(requestMock);
channel.writeInbound(responseHeader, responseChunk);
latch.await(1, TimeUnit.SECONDS);
assertEquals(1, firedEvents.size());
GetDesignDocumentResponse inbound = (GetDesignDocumentResponse) firedEvents.get(0);
assertTrue(inbound.status().isSuccess());
assertEquals("name", inbound.name());
assertEquals(true, inbound.development());
assertEquals(response, inbound.content().toString(CharsetUtil.UTF_8));
ReferenceCountUtil.releaseLater(inbound);
}
示例14: shouldParseErrorWithEmptyRows
import io.netty.handler.codec.http.DefaultHttpResponse; //导入依赖的package包/类
@Test
@SuppressWarnings("unchecked")
public void shouldParseErrorWithEmptyRows() throws Exception {
String response = Resources.read("error_empty_rows.json", this.getClass());
HttpResponse responseHeader = new DefaultHttpResponse(HttpVersion.HTTP_1_1, new HttpResponseStatus(200, "OK"));
HttpContent responseChunk1 = new DefaultLastHttpContent(Unpooled.copiedBuffer(response, CharsetUtil.UTF_8));
ViewQueryRequest requestMock = mock(ViewQueryRequest.class);
queue.add(requestMock);
channel.writeInbound(responseHeader, responseChunk1);
latch.await(1, TimeUnit.SECONDS);
assertEquals(1, firedEvents.size());
ViewQueryResponse inbound = (ViewQueryResponse) firedEvents.get(0);
assertTrue(inbound.status().isSuccess());
assertEquals(0, countAndRelease(inbound.rows()));
String error = inbound.error().toBlocking().single();
Map<String, Object> parsed = mapper.readValue(error, Map.class);
assertEquals(1, parsed.size());
assertNotNull(parsed.get("errors"));
}
示例15: shouldParseErrorAfterRows
import io.netty.handler.codec.http.DefaultHttpResponse; //导入依赖的package包/类
@Test
@SuppressWarnings("unchecked")
public void shouldParseErrorAfterRows() throws Exception {
String response = Resources.read("error_rows.json", this.getClass());
HttpResponse responseHeader = new DefaultHttpResponse(HttpVersion.HTTP_1_1, new HttpResponseStatus(200, "OK"));
HttpContent responseChunk1 = new DefaultLastHttpContent(Unpooled.copiedBuffer(response, CharsetUtil.UTF_8));
ViewQueryRequest requestMock = mock(ViewQueryRequest.class);
queue.add(requestMock);
channel.writeInbound(responseHeader, responseChunk1);
latch.await(1, TimeUnit.SECONDS);
assertEquals(1, firedEvents.size());
ViewQueryResponse inbound = (ViewQueryResponse) firedEvents.get(0);
assertTrue(inbound.status().isSuccess());
assertEquals(10, countAndRelease(inbound.rows()));
String error = inbound.error().toBlocking().single();
Map<String, Object> parsed = mapper.readValue(error, Map.class);
assertEquals(1, parsed.size());
assertNotNull(parsed.get("errors"));
}