Search in sources :

Example 96 with DefaultFullHttpResponse

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.DefaultFullHttpResponse in project weicoder by wdcode.

the class WebSocketHandler method http.

/*
	 * http请求
	 */
private void http(ChannelHandlerContext ctx, FullHttpRequest req) {
    // 请求不成功
    if (!req.decoderResult().isSuccess()) {
        send(ctx, req, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST));
        return;
    }
    // 只允许get请求
    if (req.method() != HttpMethod.GET) {
        send(ctx, req, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.FORBIDDEN));
        return;
    }
    // 处理websocket
    WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(String.format(WEBSOCKET_PATH, req.headers().get(HttpHeaderNames.HOST)), null, true, 5 * 1024 * 1024);
    WebSocketServerHandshaker handshaker = wsFactory.newHandshaker(req);
    if (handshaker == null) {
        WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
    } else {
        handshaker.handshake(ctx.channel(), req);
    }
}
Also used : DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) WebSocketServerHandshaker(io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker) WebSocketServerHandshakerFactory(io.netty.handler.codec.http.websocketx.WebSocketServerHandshakerFactory)

Example 97 with DefaultFullHttpResponse

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.DefaultFullHttpResponse in project java by wavefrontHQ.

the class ChannelUtils method makeResponse.

/**
 * Create {@link FullHttpResponse} based on provided status and body contents.
 *
 * @param status   response status.
 * @param contents response body.
 * @return http response object
 */
public static HttpResponse makeResponse(final HttpResponseStatus status, final Object contents) {
    final FullHttpResponse response;
    if (contents instanceof JsonNode) {
        response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, Unpooled.copiedBuffer(contents.toString(), CharsetUtil.UTF_8));
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON);
    } else if (contents instanceof CharSequence) {
        response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, Unpooled.copiedBuffer((CharSequence) contents, CharsetUtil.UTF_8));
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.TEXT_PLAIN);
    } else {
        throw new IllegalArgumentException("Unexpected response content type, JsonNode or " + "CharSequence expected: " + contents.getClass().getName());
    }
    response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
    return response;
}
Also used : DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) JsonNode(com.fasterxml.jackson.databind.JsonNode)

Example 98 with DefaultFullHttpResponse

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.DefaultFullHttpResponse in project proxyee-down by monkeyWie.

the class HttpHandlerUtil method buildJson.

public static FullHttpResponse buildJson(Object obj, Include include) {
    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
    response.headers().set(HttpHeaderNames.CONTENT_TYPE, AsciiString.cached("application/json; charset=utf-8"));
    if (obj != null) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            if (include != null) {
                objectMapper.setSerializationInclusion(include);
            }
            String content = objectMapper.writeValueAsString(obj);
            response.content().writeBytes(content.getBytes(Charset.forName("utf-8")));
        } catch (JsonProcessingException e) {
            response.setStatus(HttpResponseStatus.SERVICE_UNAVAILABLE);
        }
    }
    response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
    return response;
}
Also used : DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) AsciiString(io.netty.util.AsciiString) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 99 with DefaultFullHttpResponse

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.DefaultFullHttpResponse in project reactor-netty by reactor.

the class HttpClientTest method prematureCancel.

@Test
void prematureCancel() {
    Sinks.Many<Void> signal = Sinks.unsafe().many().unicast().onBackpressureError();
    disposableServer = TcpServer.create().host("localhost").port(0).handle((in, out) -> {
        signal.tryEmitComplete().orThrow();
        return out.withConnection(c -> c.addHandlerFirst(new HttpResponseEncoder())).sendObject(Mono.delay(Duration.ofSeconds(2)).map(t -> new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.PROCESSING))).neverComplete();
    }).wiretap(true).bindNow(Duration.ofSeconds(30));
    StepVerifier.create(createHttpClientForContextWithAddress().get().uri("/").responseContent().timeout(signal.asFlux())).verifyError(TimeoutException.class);
}
Also used : Arrays(java.util.Arrays) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) StepVerifier(reactor.test.StepVerifier) DefaultChannelGroup(io.netty.channel.group.DefaultChannelGroup) Tuples(reactor.util.function.Tuples) Disabled(org.junit.jupiter.api.Disabled) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) HttpResources(reactor.netty.http.HttpResources) TcpClient(reactor.netty.tcp.TcpClient) Future(java.util.concurrent.Future) Loggers(reactor.util.Loggers) DomainSocketAddress(io.netty.channel.unix.DomainSocketAddress) BeforeAll(org.junit.jupiter.api.BeforeAll) Duration(java.time.Duration) CharsetUtil(io.netty.util.CharsetUtil) Path(java.nio.file.Path) LoopResources(reactor.netty.resources.LoopResources) HttpObjectDecoder(io.netty.handler.codec.http.HttpObjectDecoder) Context(reactor.util.context.Context) Set(java.util.Set) ConnectionPoolMetrics(reactor.netty.resources.ConnectionPoolMetrics) StandardCharsets(java.nio.charset.StandardCharsets) Executors(java.util.concurrent.Executors) CountDownLatch(java.util.concurrent.CountDownLatch) SSLException(javax.net.ssl.SSLException) AddressResolverGroup(io.netty.resolver.AddressResolverGroup) HttpServer(reactor.netty.http.server.HttpServer) LogLevel(io.netty.handler.logging.LogLevel) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) SocketUtils(reactor.netty.SocketUtils) HttpProtocol(reactor.netty.http.HttpProtocol) Nullable(reactor.util.annotation.Nullable) ArrayList(java.util.ArrayList) InsecureTrustManagerFactory(io.netty.handler.ssl.util.InsecureTrustManagerFactory) SslProvider(reactor.netty.tcp.SslProvider) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) SslContext(io.netty.handler.ssl.SslContext) Files(java.nio.file.Files) Publisher(org.reactivestreams.Publisher) IOException(java.io.IOException) Mono(reactor.core.publisher.Mono) Field(java.lang.reflect.Field) Channel(io.netty.channel.Channel) AtomicLong(java.util.concurrent.atomic.AtomicLong) DefaultEventExecutor(io.netty.util.concurrent.DefaultEventExecutor) Flux(reactor.core.publisher.Flux) FutureMono(reactor.netty.FutureMono) Paths(java.nio.file.Paths) SslContextBuilder(io.netty.handler.ssl.SslContextBuilder) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) ConnectionProvider(reactor.netty.resources.ConnectionProvider) DnsAddressResolverGroup(io.netty.resolver.dns.DnsAddressResolverGroup) Sinks(reactor.core.publisher.Sinks) SocketAddress(java.net.SocketAddress) Http11SslContextSpec(reactor.netty.http.Http11SslContextSpec) ByteBufAllocator(io.netty.buffer.ByteBufAllocator) URISyntaxException(java.net.URISyntaxException) BiFunction(java.util.function.BiFunction) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) ChannelId(io.netty.channel.ChannelId) Http2SslContextSpec(reactor.netty.http.Http2SslContextSpec) TimeoutException(java.util.concurrent.TimeoutException) BaseHttpTest(reactor.netty.BaseHttpTest) ByteBuffer(java.nio.ByteBuffer) Unpooled(io.netty.buffer.Unpooled) TransportConfig(reactor.netty.transport.TransportConfig) SocketChannel(java.nio.channels.SocketChannel) HttpResponseEncoder(io.netty.handler.codec.http.HttpResponseEncoder) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ByteBufFlux(reactor.netty.ByteBufFlux) NettyPipeline(reactor.netty.NettyPipeline) Logger(reactor.util.Logger) ByteBufMono(reactor.netty.ByteBufMono) URI(java.net.URI) ChannelDuplexHandler(io.netty.channel.ChannelDuplexHandler) ChannelGroup(io.netty.channel.group.ChannelGroup) ReadTimeoutHandler(io.netty.handler.timeout.ReadTimeoutHandler) StandardOpenOption(java.nio.file.StandardOpenOption) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) InetSocketAddress(java.net.InetSocketAddress) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Objects(java.util.Objects) Test(org.junit.jupiter.api.Test) List(java.util.List) HttpVersion(io.netty.handler.codec.http.HttpVersion) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Tuple2(reactor.util.function.Tuple2) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) Queues(reactor.util.concurrent.Queues) Charset(java.nio.charset.Charset) ByteBuf(io.netty.buffer.ByteBuf) Connection(reactor.netty.Connection) ExecutorService(java.util.concurrent.ExecutorService) HttpHeaderValues(io.netty.handler.codec.http.HttpHeaderValues) SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) HttpMethod(io.netty.handler.codec.http.HttpMethod) CertificateException(java.security.cert.CertificateException) ServerSocketChannel(java.nio.channels.ServerSocketChannel) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) ConcurrentSkipListSet(java.util.concurrent.ConcurrentSkipListSet) TcpServer(reactor.netty.tcp.TcpServer) ChannelHandler(io.netty.channel.ChannelHandler) HttpContentDecompressor(io.netty.handler.codec.http.HttpContentDecompressor) HttpResponseEncoder(io.netty.handler.codec.http.HttpResponseEncoder) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) Sinks(reactor.core.publisher.Sinks) BaseHttpTest(reactor.netty.BaseHttpTest) Test(org.junit.jupiter.api.Test)

Example 100 with DefaultFullHttpResponse

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.DefaultFullHttpResponse in project reactor-netty by reactor.

the class HttpServerOperations method sendDecodingFailures.

static void sendDecodingFailures(ChannelHandlerContext ctx, ConnectionObserver listener, boolean secure, Throwable t, Object msg) {
    Connection conn = Connection.from(ctx.channel());
    Throwable cause = t.getCause() != null ? t.getCause() : t;
    if (log.isWarnEnabled()) {
        log.warn(format(ctx.channel(), "Decoding failed: " + msg + " : "), cause);
    }
    ReferenceCountUtil.release(msg);
    HttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_0, cause instanceof TooLongFrameException ? HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE : HttpResponseStatus.BAD_REQUEST);
    response.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, 0).set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
    ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    HttpRequest request = null;
    if (msg instanceof HttpRequest) {
        request = (HttpRequest) msg;
    }
    listener.onStateChange(new FailedHttpServerRequest(conn, listener, request, response, secure), REQUEST_DECODING_FAILED);
}
Also used : HttpRequest(io.netty.handler.codec.http.HttpRequest) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) TooLongFrameException(io.netty.handler.codec.TooLongFrameException) Connection(reactor.netty.Connection) DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpResponse(io.netty.handler.codec.http.HttpResponse) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse)

Aggregations

DefaultFullHttpResponse (io.netty.handler.codec.http.DefaultFullHttpResponse)223 FullHttpResponse (io.netty.handler.codec.http.FullHttpResponse)145 ByteBuf (io.netty.buffer.ByteBuf)68 HttpResponse (io.netty.handler.codec.http.HttpResponse)39 Test (org.junit.Test)25 HttpRequest (io.netty.handler.codec.http.HttpRequest)24 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)23 HttpResponseStatus (io.netty.handler.codec.http.HttpResponseStatus)22 ChannelFuture (io.netty.channel.ChannelFuture)19 IOException (java.io.IOException)19 FullHttpRequest (io.netty.handler.codec.http.FullHttpRequest)16 HttpHeaders (io.netty.handler.codec.http.HttpHeaders)16 DefaultHttpResponse (io.netty.handler.codec.http.DefaultHttpResponse)15 HttpObject (io.netty.handler.codec.http.HttpObject)15 DefaultFullHttpRequest (io.netty.handler.codec.http.DefaultFullHttpRequest)12 HttpVersion (io.netty.handler.codec.http.HttpVersion)12 InetSocketAddress (java.net.InetSocketAddress)12 SSLException (javax.net.ssl.SSLException)12 Test (org.junit.jupiter.api.Test)12 Map (java.util.Map)11