Search in sources :

Example 26 with DefaultHttpResponse

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.DefaultHttpResponse in project netty-socketio by mrniko.

the class EncoderHandler method sendMessage.

private void sendMessage(HttpMessage msg, Channel channel, ByteBuf out, String type, ChannelPromise promise, HttpResponseStatus status) {
    HttpResponse res = new DefaultHttpResponse(HTTP_1_1, status);
    res.headers().add(HttpHeaderNames.CONTENT_TYPE, type).add(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
    if (msg.getSessionId() != null) {
        res.headers().add(HttpHeaderNames.SET_COOKIE, "io=" + msg.getSessionId());
    }
    String origin = channel.attr(ORIGIN).get();
    addOriginHeaders(origin, res);
    HttpUtil.setContentLength(res, out.readableBytes());
    // prevent XSS warnings on IE
    // https://github.com/LearnBoost/socket.io/pull/1333
    String userAgent = channel.attr(EncoderHandler.USER_AGENT).get();
    if (userAgent != null && (userAgent.contains(";MSIE") || userAgent.contains("Trident/"))) {
        res.headers().add("X-XSS-Protection", "0");
    }
    sendMessage(msg, channel, out, res, promise);
}
Also used : DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse) DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse) HttpResponse(io.netty.handler.codec.http.HttpResponse)

Example 27 with DefaultHttpResponse

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

the class RtspEncoderTest method testSend200OkResponseWithoutBody.

/**
 * Test of a 200 OK response, without body.
 */
@Test
public void testSend200OkResponseWithoutBody() {
    String expected = "RTSP/1.0 200 OK\r\n" + "server: Testserver\r\n" + "cseq: 1\r\n" + "session: 2547019973447939919\r\n" + "\r\n";
    HttpResponse response = new DefaultHttpResponse(RtspVersions.RTSP_1_0, RtspResponseStatuses.OK);
    response.headers().add(RtspHeaderNames.SERVER, "Testserver");
    response.headers().add(RtspHeaderNames.CSEQ, "1");
    response.headers().add(RtspHeaderNames.SESSION, "2547019973447939919");
    EmbeddedChannel ch = new EmbeddedChannel(new RtspEncoder());
    ch.writeOutbound(response);
    ByteBuf buf = ch.readOutbound();
    String actual = buf.toString(CharsetUtil.UTF_8);
    buf.release();
    assertEquals(expected, actual);
}
Also used : DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpResponse(io.netty.handler.codec.http.HttpResponse) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) ByteBuf(io.netty.buffer.ByteBuf) Test(org.junit.jupiter.api.Test)

Example 28 with DefaultHttpResponse

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

the class Http2StreamFrameToHttpObjectCodecTest method testUpgradeHeaders.

@Test
public void testUpgradeHeaders() throws Exception {
    EmbeddedChannel ch = new EmbeddedChannel(new Http2StreamFrameToHttpObjectCodec(true));
    HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
    assertTrue(ch.writeOutbound(response));
    Http2HeadersFrame headersFrame = ch.readOutbound();
    assertThat(headersFrame.headers().status().toString(), is("200"));
    assertFalse(headersFrame.isEndStream());
    assertThat(ch.readOutbound(), is(nullValue()));
    assertFalse(ch.finish());
}
Also used : DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpResponse(io.netty.handler.codec.http.HttpResponse) Test(org.junit.jupiter.api.Test)

Example 29 with DefaultHttpResponse

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

the class HttpStaticFileServerHandler method channelRead0.

@Override
public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
    this.request = request;
    if (!request.decoderResult().isSuccess()) {
        sendError(ctx, BAD_REQUEST);
        return;
    }
    if (!GET.equals(request.method())) {
        sendError(ctx, METHOD_NOT_ALLOWED);
        return;
    }
    final boolean keepAlive = HttpUtil.isKeepAlive(request);
    final String uri = request.uri();
    final String path = sanitizeUri(uri);
    if (path == null) {
        sendError(ctx, FORBIDDEN);
        return;
    }
    File file = new File(path);
    if (file.isHidden() || !file.exists()) {
        sendError(ctx, NOT_FOUND);
        return;
    }
    if (file.isDirectory()) {
        if (uri.endsWith("/")) {
            sendListing(ctx, file, uri);
        } else {
            sendRedirect(ctx, uri + '/');
        }
        return;
    }
    if (!file.isFile()) {
        sendError(ctx, FORBIDDEN);
        return;
    }
    // Cache Validation
    String ifModifiedSince = request.headers().get(HttpHeaderNames.IF_MODIFIED_SINCE);
    if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) {
        SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
        Date ifModifiedSinceDate = dateFormatter.parse(ifModifiedSince);
        // Only compare up to the second because the datetime format we send to the client
        // does not have milliseconds
        long ifModifiedSinceDateSeconds = ifModifiedSinceDate.getTime() / 1000;
        long fileLastModifiedSeconds = file.lastModified() / 1000;
        if (ifModifiedSinceDateSeconds == fileLastModifiedSeconds) {
            sendNotModified(ctx);
            return;
        }
    }
    RandomAccessFile raf;
    try {
        raf = new RandomAccessFile(file, "r");
    } catch (FileNotFoundException ignore) {
        sendError(ctx, NOT_FOUND);
        return;
    }
    long fileLength = raf.length();
    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
    HttpUtil.setContentLength(response, fileLength);
    setContentTypeHeader(response, file);
    setDateAndCacheHeaders(response, file);
    if (!keepAlive) {
        response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
    } else if (request.protocolVersion().equals(HTTP_1_0)) {
        response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
    }
    // Write the initial line and the header.
    ctx.write(response);
    // Write the content.
    ChannelFuture sendFileFuture;
    ChannelFuture lastContentFuture;
    if (ctx.pipeline().get(SslHandler.class) == null) {
        sendFileFuture = ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength), ctx.newProgressivePromise());
        // Write the end marker.
        lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
    } else {
        sendFileFuture = ctx.writeAndFlush(new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)), ctx.newProgressivePromise());
        // HttpChunkedInput will write the end marker (LastHttpContent) for us.
        lastContentFuture = sendFileFuture;
    }
    sendFileFuture.addListener(new ChannelProgressiveFutureListener() {

        @Override
        public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) {
            if (total < 0) {
                // total unknown
                System.err.println(future.channel() + " Transfer progress: " + progress);
            } else {
                System.err.println(future.channel() + " Transfer progress: " + progress + " / " + total);
            }
        }

        @Override
        public void operationComplete(ChannelProgressiveFuture future) {
            System.err.println(future.channel() + " Transfer complete.");
        }
    });
    // Decide whether to close the connection or not.
    if (!keepAlive) {
        // Close the connection when the whole content is written out.
        lastContentFuture.addListener(ChannelFutureListener.CLOSE);
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) ChunkedFile(io.netty.handler.stream.ChunkedFile) FileNotFoundException(java.io.FileNotFoundException) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpResponse(io.netty.handler.codec.http.HttpResponse) ChannelProgressiveFuture(io.netty.channel.ChannelProgressiveFuture) DefaultFileRegion(io.netty.channel.DefaultFileRegion) Date(java.util.Date) SslHandler(io.netty.handler.ssl.SslHandler) HttpChunkedInput(io.netty.handler.codec.http.HttpChunkedInput) RandomAccessFile(java.io.RandomAccessFile) DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse) RandomAccessFile(java.io.RandomAccessFile) ChunkedFile(io.netty.handler.stream.ChunkedFile) File(java.io.File) SimpleDateFormat(java.text.SimpleDateFormat) ChannelProgressiveFutureListener(io.netty.channel.ChannelProgressiveFutureListener)

Example 30 with DefaultHttpResponse

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

the class WebSocketHandshakeExceptionTest method testClientExceptionWithResponse.

@Test
public void testClientExceptionWithResponse() {
    HttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST);
    httpResponse.headers().set("x-header", "x-value");
    WebSocketClientHandshakeException clientException = new WebSocketClientHandshakeException("client message", httpResponse);
    assertNotNull(clientException.response());
    assertEquals("client message", clientException.getMessage());
    assertEquals(HttpResponseStatus.BAD_REQUEST, clientException.response().status());
    assertEquals(httpResponse.headers(), clientException.response().headers());
}
Also used : DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse) DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse) HttpResponse(io.netty.handler.codec.http.HttpResponse) Test(org.junit.jupiter.api.Test)

Aggregations

DefaultHttpResponse (io.netty.handler.codec.http.DefaultHttpResponse)64 HttpResponse (io.netty.handler.codec.http.HttpResponse)34 DefaultFullHttpResponse (io.netty.handler.codec.http.DefaultFullHttpResponse)23 FullHttpResponse (io.netty.handler.codec.http.FullHttpResponse)18 HttpContent (io.netty.handler.codec.http.HttpContent)14 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)11 LastHttpContent (io.netty.handler.codec.http.LastHttpContent)11 ChannelFuture (io.netty.channel.ChannelFuture)10 HttpRequest (io.netty.handler.codec.http.HttpRequest)10 ByteBuf (io.netty.buffer.ByteBuf)9 DefaultLastHttpContent (io.netty.handler.codec.http.DefaultLastHttpContent)9 HttpObject (io.netty.handler.codec.http.HttpObject)9 RandomAccessFile (java.io.RandomAccessFile)9 Test (org.junit.Test)9 FileNotFoundException (java.io.FileNotFoundException)7 IOException (java.io.IOException)7 Channel (io.netty.channel.Channel)6 File (java.io.File)6 HttpChunkedInput (io.netty.handler.codec.http.HttpChunkedInput)5 URL (java.net.URL)5