io.netty.handler.codec.http.DefaultHttpResponse Java Examples

The following examples show how to use io.netty.handler.codec.http.DefaultHttpResponse. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MesosClientTest.java    From mesos-rxjava with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #2
Source File: RtspEncoderTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #3
Source File: HttpConversionUtil.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
/**
 * Create a new object to contain the response data.
 *
 * @param streamId The stream associated with the response
 * @param http2Headers The initial set of HTTP/2 headers to create the response with
 * @param validateHttpHeaders <ul>
 *        <li>{@code true} to validate HTTP headers in the http-codec</li>
 *        <li>{@code false} not to validate HTTP headers in the http-codec</li>
 *        </ul>
 * @return A new response object which represents headers for a chunked response
 * @throws Http2Exception see {@link #addHttp2ToHttpHeaders(int, Http2Headers,
 *         HttpHeaders, HttpVersion, boolean, boolean)}
 */
public static HttpResponse toHttpResponse(final int streamId,
                                          final Http2Headers http2Headers,
                                          final boolean validateHttpHeaders) throws Http2Exception {
    final HttpResponseStatus status = parseStatus(http2Headers.status());
    // HTTP/2 does not define a way to carry the version or reason phrase that is included in an
    // HTTP/1.1 status line.
    final HttpResponse msg = new DefaultHttpResponse(HttpVersion.HTTP_1_1, status, validateHttpHeaders);
    try {
        addHttp2ToHttpHeaders(streamId, http2Headers, msg.headers(), msg.protocolVersion(), false, true);
    } catch (final Http2Exception e) {
        throw e;
    } catch (final Throwable t) {
        throw streamError(streamId, PROTOCOL_ERROR, t, "HTTP/2 to HTTP/1.x headers conversion error");
    }
    return msg;
}
 
Example #4
Source File: RtspDecoder.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Override
protected HttpMessage createMessage(final String[] initialLine)
        throws Exception {
    // If the first element of the initial line is a version string then
    // this is a response
    if (versionPattern.matcher(initialLine[0]).matches()) {
        isDecodingRequest = false;
        return new DefaultHttpResponse(RtspVersions.valueOf(initialLine[0]),
            new HttpResponseStatus(Integer.parseInt(initialLine[1]),
                                   initialLine[2]),
            validateHeaders);
    } else {
        isDecodingRequest = true;
        return new DefaultHttpRequest(RtspVersions.valueOf(initialLine[2]),
                RtspMethods.valueOf(initialLine[0]),
                initialLine[1],
                validateHeaders);
    }
}
 
Example #5
Source File: WebRequestHandler.java    From Summer with Apache License 2.0 6 votes vote down vote up
public static void write(ChannelHandlerContext ctx, SessionContext sctx, WebRequest request, WebView webView) {
	try {
		DefaultHttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, 
				HttpResponseStatus.valueOf(webView.getStatus()));
		if (HttpUtil.isKeepAlive(request.getHttpRequest())) {
			response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
		}
		response.headers().set(HttpHeaderNames.CONTENT_TYPE, webView.getContentType());
		response.headers().set(HttpHeaderNames.CONTENT_LENGTH, webView.getLength());
		response.headers().set(HttpHeaderNames.SERVER, Summer.NAME);
		response.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
		if (sctx.getSessionId() == null) {
			response.headers().set(HttpHeaderNames.SET_COOKIE, createSessionId());
		}
		if (webView.getHeaders() != null) {
			webView.getHeaders().forEach((key, value) -> response.headers().set(key, value));
		}
		ctx.write(response);
		ctx.write(webView.getChunkedInput());
		ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
	} catch (Exception e) {
		log.error(e.getMessage(), e);
	}
}
 
Example #6
Source File: StreamServerGroupHandler.java    From IpCamera with Eclipse Public License 2.0 6 votes vote down vote up
private void sendSnapshotImage(ChannelHandlerContext ctx, String contentType) throws IOException {
    HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
    if (ipCameraGroupHandler.cameraIndex >= ipCameraGroupHandler.cameraOrder.size()) {
        logger.debug("WARN: Openhab may still be starting, or all cameras in the group are OFFLINE.");
        return;
    }
    ipCameraGroupHandler.cameraOrder.get(ipCameraGroupHandler.cameraIndex).lockCurrentSnapshot.lock();
    ByteBuf snapshotData = Unpooled
            .copiedBuffer(ipCameraGroupHandler.cameraOrder.get(ipCameraGroupHandler.cameraIndex).currentSnapshot);
    ipCameraGroupHandler.cameraOrder.get(ipCameraGroupHandler.cameraIndex).lockCurrentSnapshot.unlock();
    response.headers().add(HttpHeaderNames.CONTENT_TYPE, contentType);
    response.headers().set(HttpHeaderNames.CACHE_CONTROL, HttpHeaderValues.NO_CACHE);
    response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
    response.headers().add(HttpHeaderNames.CONTENT_LENGTH, snapshotData.readableBytes());
    response.headers().add("Access-Control-Allow-Origin", "*");
    response.headers().add("Access-Control-Expose-Headers", "*");
    ctx.channel().write(response);
    ctx.channel().write(snapshotData);
    ByteBuf footerBbuf = Unpooled.copiedBuffer("\r\n", 0, 2, StandardCharsets.UTF_8);
    ctx.channel().writeAndFlush(footerBbuf);
}
 
Example #7
Source File: StreamServerGroupHandler.java    From IpCamera with Eclipse Public License 2.0 6 votes vote down vote up
private void sendFile(ChannelHandlerContext ctx, String fileUri, String contentType) throws IOException {
    logger.debug("file is :{}", fileUri);
    File file = new File(fileUri);
    ChunkedFile chunkedFile = new ChunkedFile(file);
    ByteBuf footerBbuf = Unpooled.copiedBuffer("\r\n", 0, 2, StandardCharsets.UTF_8);
    HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
    response.headers().add(HttpHeaderNames.CONTENT_TYPE, contentType);
    response.headers().set(HttpHeaderNames.CACHE_CONTROL, HttpHeaderValues.NO_CACHE);
    response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
    response.headers().add(HttpHeaderNames.CONTENT_LENGTH, chunkedFile.length());
    response.headers().add("Access-Control-Allow-Origin", "*");
    response.headers().add("Access-Control-Expose-Headers", "*");
    ctx.channel().write(response);
    ctx.channel().write(chunkedFile);
    ctx.channel().writeAndFlush(footerBbuf);
}
 
Example #8
Source File: StreamServerHandler.java    From IpCamera with Eclipse Public License 2.0 6 votes vote down vote up
private void sendSnapshotImage(ChannelHandlerContext ctx, String contentType) throws IOException {
    HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
    ipCameraHandler.lockCurrentSnapshot.lock();
    ByteBuf snapshotData = Unpooled.copiedBuffer(ipCameraHandler.currentSnapshot);
    ipCameraHandler.lockCurrentSnapshot.unlock();
    response.headers().add(HttpHeaderNames.CONTENT_TYPE, contentType);
    response.headers().set(HttpHeaderNames.CACHE_CONTROL, HttpHeaderValues.NO_CACHE);
    response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
    response.headers().add(HttpHeaderNames.CONTENT_LENGTH, snapshotData.readableBytes());
    response.headers().add("Access-Control-Allow-Origin", "*");
    response.headers().add("Access-Control-Expose-Headers", "*");
    ctx.channel().write(response);
    ctx.channel().write(snapshotData);
    ByteBuf footerBbuf = Unpooled.copiedBuffer("\r\n", 0, 2, StandardCharsets.UTF_8);
    ctx.channel().writeAndFlush(footerBbuf);
}
 
Example #9
Source File: HttpUtilsTest.java    From azure-cosmosdb-java with MIT License 6 votes vote down vote up
@Test(groups = { "unit" })
public void verifyConversionOfHttpResponseHeadersToMap() throws UnsupportedEncodingException {
    HttpHeaders headersMap = new DefaultHttpHeaders();
    headersMap.add(HttpConstants.HttpHeaders.OWNER_FULL_NAME, OWNER_FULL_NAME_VALUE);

    HttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_0,
            HttpResponseStatus.ACCEPTED,
            headersMap);
    HttpResponseHeaders httpResponseHeaders = new HttpClientResponse(httpResponse, null).getHeaders();
    Set<Entry<String, String>> resultHeadersSet = HttpUtils.asMap(httpResponseHeaders).entrySet();
    
    assertThat(resultHeadersSet.size()).isEqualTo(1);
    Entry<String, String> entry = resultHeadersSet.iterator().next();
    assertThat(entry.getKey()).isEqualTo(HttpConstants.HttpHeaders.OWNER_FULL_NAME);
    assertThat(entry.getValue()).isEqualTo(HttpUtils.urlDecode(OWNER_FULL_NAME_VALUE));
    
    List<Entry<String, String>> resultHeadersList = HttpUtils.unescape(httpResponseHeaders.entries());
    assertThat(resultHeadersList.size()).isEqualTo(1);
    entry = resultHeadersSet.iterator().next();
    assertThat(entry.getKey()).isEqualTo(HttpConstants.HttpHeaders.OWNER_FULL_NAME);
    assertThat(entry.getValue()).isEqualTo(HttpUtils.urlDecode(OWNER_FULL_NAME_VALUE));
}
 
Example #10
Source File: HttpClientMockWrapper.java    From azure-cosmosdb-java with MIT License 6 votes vote down vote up
public HttpClientResponse<ByteBuf> asHttpClientResponse() {
    if (this.networkFailure != null) {
        return null;
    }

    HttpClientResponse<ByteBuf> resp = Mockito.mock(HttpClientResponse.class);
    Mockito.doReturn(HttpResponseStatus.valueOf(status)).when(resp).getStatus();
    Mockito.doReturn(Observable.just(ByteBufUtil.writeUtf8(ByteBufAllocator.DEFAULT, content))).when(resp).getContent();

    DefaultHttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(status), httpHeaders);

    try {
        Constructor<HttpResponseHeaders> constructor = HttpResponseHeaders.class.getDeclaredConstructor(HttpResponse.class);
        constructor.setAccessible(true);
        HttpResponseHeaders httpResponseHeaders = constructor.newInstance(httpResponse);
        Mockito.doReturn(httpResponseHeaders).when(resp).getHeaders();

    } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
            | InvocationTargetException | NoSuchMethodException | SecurityException e) {
        throw new IllegalStateException("Failed to instantiate class object.", e);
    }

    return resp;
}
 
Example #11
Source File: ResponseFactory.java    From xrpc with Apache License 2.0 6 votes vote down vote up
/**
 * Return http response with status, body, content type, and custom headers.
 *
 * @param status http status
 * @param body body ByteBuf
 * @param contentType content type of response
 * @param customHeaders if non-null these headers will be added to the response
 */
default HttpResponse createResponse(
    HttpResponseStatus status,
    ByteBuf body,
    CharSequence contentType,
    Map<String, String> customHeaders) {

  HttpResponse response =
      body == null || body.readableBytes() <= 0
          ? new DefaultHttpResponse(HttpVersion.HTTP_1_1, status)
          : new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, body);

  if (customHeaders != null) {
    customHeaders.forEach((key, value) -> response.headers().set(key, value));
  }

  response.headers().set(CONTENT_TYPE, contentType);
  response.headers().setInt(CONTENT_LENGTH, body == null ? 0 : body.readableBytes());

  return response;
}
 
Example #12
Source File: NettyConnectionFactoryTest.java    From styx with Apache License 2.0 6 votes vote down vote up
private Flux<HttpObject> channelRequestResponse(Channel channel, FullHttpRequest request) {
    return Flux.create(sink -> {
        channel.pipeline().addLast(new SimpleChannelInboundHandler<HttpObject>() {
            @Override
            protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
                sink.next(msg);

                if (msg instanceof DefaultHttpResponse) {
                    DefaultHttpResponse response = (DefaultHttpResponse) msg;
                    if (response.decoderResult().isFailure()) {
                        sink.error(response.decoderResult().cause());
                    }
                }
                if (msg instanceof LastHttpContent) {
                    sink.complete();
                }
            }
        });

        channel.writeAndFlush(request);
    });
}
 
Example #13
Source File: WebHdfsHandler.java    From hadoop with Apache License 2.0 6 votes vote down vote up
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));
}
 
Example #14
Source File: PublisherAdapterTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    executeFuture = new CompletableFuture<>();
    fullHttpResponse = mock(DefaultHttpContent.class);

    when(fullHttpResponse.content()).thenReturn(new EmptyByteBuf(ByteBufAllocator.DEFAULT));
    requestContext = new RequestContext(channelPool,
                                        eventLoopGroup,
                                        AsyncExecuteRequest.builder().responseHandler(responseHandler).build(),
                                        null);

    channel = new MockChannel();
    channel.attr(PROTOCOL_FUTURE).set(CompletableFuture.completedFuture(Protocol.HTTP1_1));
    channel.attr(REQUEST_CONTEXT_KEY).set(requestContext);
    channel.attr(EXECUTE_FUTURE_KEY).set(executeFuture);
    when(ctx.channel()).thenReturn(channel);

    nettyResponseHandler = ResponseHandler.getInstance();
    DefaultHttpResponse defaultFullHttpResponse = mock(DefaultHttpResponse.class);
    when(defaultFullHttpResponse.headers()).thenReturn(EmptyHttpHeaders.INSTANCE);
    when(defaultFullHttpResponse.status()).thenReturn(HttpResponseStatus.CREATED);
    when(defaultFullHttpResponse.protocolVersion()).thenReturn(HttpVersion.HTTP_1_1);
    nettyResponseHandler.channelRead0(ctx, defaultFullHttpResponse);
}
 
Example #15
Source File: MessageWsServerHandler.java    From sctalk with Apache License 2.0 6 votes vote down vote up
/**
 * 处理Http请求,完成WebSocket握手<br/>
 * 注意:WebSocket连接第一次请求使用的是Http
 * 
 * @param ctx
 * @param request
 * @throws Exception
 */
private void handleHttpRequest(ChannelHandlerContext ctx, HttpRequest request)
        throws Exception {
    // 如果HTTP解码失败,返回HHTP异常
    if (!request.getDecoderResult().isSuccess()
            || (!"websocket".equals(request.headers().get("Upgrade")))) {
        sendHttpResponse(ctx, request,
                new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST));
        return;
    }

    // 正常WebSocket的Http连接请求,构造握手响应返回
    WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
            "ws://" + request.headers().get(HttpHeaders.Names.HOST), null, false);
    handshaker = wsFactory.newHandshaker(request);
    if (handshaker == null) {
        // 无法处理的websocket版本
        WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
    } else {
        // 向客户端发送websocket握手,完成握手
        logger.debug("向客户端发送websocket握手,完成握手");
        handshaker.handshake(ctx.channel(), request);
    }
}
 
Example #16
Source File: CookieIntercept.java    From proxyee-down with Apache License 2.0 6 votes vote down vote up
@Override
public void beforeRequest(Channel clientChannel, HttpRequest httpRequest, HttpProxyInterceptPipeline pipeline) throws Exception {
  String acceptValue = httpRequest.headers().get(HttpHeaderNames.ACCEPT);
  if (acceptValue != null && acceptValue.contains("application/x-sniff-cookie")) {
    HttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, new DefaultHttpHeaders());
    httpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, 0);
    //https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/Access-Control-Expose-Headers
    AsciiString customHeadKey = AsciiString.cached("X-Sniff-Cookie");
    String cookie = pipeline.getHttpRequest().headers().get(HttpHeaderNames.COOKIE);
    httpResponse.headers().set(customHeadKey, cookie == null ? "" : cookie);
    httpResponse.headers().set(HttpHeaderNames.ACCESS_CONTROL_EXPOSE_HEADERS, customHeadKey);
    String origin = httpRequest.headers().get(HttpHeaderNames.ORIGIN);
    if (StringUtil.isNullOrEmpty(origin)) {
      String referer = httpRequest.headers().get(HttpHeaderNames.REFERER);
      URL url = new URL(referer);
      origin = url.getHost();
    }
    httpResponse.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN, origin);
    httpResponse.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_CREDENTIALS, true);
    clientChannel.writeAndFlush(httpResponse);
    clientChannel.writeAndFlush(new DefaultLastHttpContent());
    clientChannel.close();
  } else {
    super.beforeRequest(clientChannel, httpRequest, pipeline);
  }
}
 
Example #17
Source File: VerifyProxyEndpointsDoNotAlterRequestOrResponseByDefaultComponentTest.java    From riposte with Apache License 2.0 6 votes vote down vote up
private List<HttpObject> handleChunkedResponse(int desiredResponseStatusCode, boolean responseShouldBeEmpty) {
    HttpResponse firstChunk = new DefaultHttpResponse(
        HttpVersion.HTTP_1_1,
        HttpResponseStatus.valueOf(desiredResponseStatusCode)
    );

    firstChunk.headers()
            .set(TRANSFER_ENCODING, CHUNKED)
            .set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE)
            .set(SOME_EXPECTED_RESPONSE_HEADER.getKey(), SOME_EXPECTED_RESPONSE_HEADER.getValue());

    List<HttpObject> responseChunks = new ArrayList<>();
    
    responseChunks.add(firstChunk);

    if (!responseShouldBeEmpty) {
        RESPONSE_PAYLOAD_CHUNKS.forEach(chunkData -> responseChunks.add(
            new DefaultHttpContent(Unpooled.wrappedBuffer(chunkData.getBytes(CharsetUtil.UTF_8)))
        ));
    }

    responseChunks.add(LastHttpContent.EMPTY_LAST_CONTENT);

    return responseChunks;
}
 
Example #18
Source File: HttpServerOperations.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
HttpServerOperations(Connection c,
		ConnectionObserver listener,
		@Nullable BiPredicate<HttpServerRequest, HttpServerResponse> compressionPredicate,
		HttpRequest nettyRequest,
		@Nullable ConnectionInfo connectionInfo,
		ServerCookieEncoder encoder,
		ServerCookieDecoder decoder) {
	super(c, listener);
	this.nettyRequest = nettyRequest;
	this.path = resolvePath(nettyRequest.uri());
	this.nettyResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
	this.responseHeaders = nettyResponse.headers();
	this.responseHeaders.set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
	this.compressionPredicate = compressionPredicate;
	this.cookieHolder = Cookies.newServerRequestHolder(requestHeaders(), decoder);
	this.connectionInfo = connectionInfo;
	this.cookieEncoder = encoder;
	this.cookieDecoder = decoder;
}
 
Example #19
Source File: HttpSender.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
public void sendChunkedHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
	
       HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
       HttpUtil.setTransferEncodingChunked(response, true);
       response.headers().set(HttpHeaderNames.CONTENT_TYPE, res.headers().get(HttpHeaderNames.CONTENT_TYPE));

       if(HttpUtil.isKeepAlive(req)) {
          response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
       }

       ctx.write(response);
       ctx.write(new ChunkedStream(new ByteBufInputStream(res.content())));
       ChannelFuture future = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
       if(!HttpUtil.isKeepAlive(req)) {
          future.addListener(ChannelFutureListener.CLOSE);
       }		
       metrics.incHTTPResponseCounter(className, res.status().code());
}
 
Example #20
Source File: HdfsWriter.java    From hadoop with Apache License 2.0 5 votes vote down vote up
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
  releaseDfsResources();
  DefaultHttpResponse resp = ExceptionHandler.exceptionCaught(cause);
  resp.headers().set(CONNECTION, CLOSE);
  ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}
 
Example #21
Source File: TraceableHttpServerResponseTest.java    From msf4j with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public void setUp() throws IOException {
    HttpCarbonMessage httpCarbonMessage =
            new HttpCarbonMessage(new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK));
    response = new Response(httpCarbonMessage);
    response.setStatus(200);
    httpResponse = new TraceableHttpServerResponse(response);
}
 
Example #22
Source File: EmbeddedChannelSupportTest.java    From styx with Apache License 2.0 5 votes vote down vote up
@Test
public void doesNotMatchesIncorrect() {
    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
    response.headers().set("foo1", "incorrect");
    response.headers().set("foo2", "bar2");

    assertThat(response, not(httpResponseWithOkStatusAndHeaders(header("foo1", "bar1"), header("foo2", "bar2"))));
}
 
Example #23
Source File: HttpPipelineHandlerTest.java    From styx with Apache License 2.0 5 votes vote down vote up
@Test
public void mapsUnrecoverableInternalErrorsToInternalServerError500ResponseCode() {
    HttpHandler handler = (request, context) -> {
        throw new RuntimeException("Forced exception for testing");
    };
    EmbeddedChannel channel = buildEmbeddedChannel(handlerWithMocks(handler));

    channel.writeInbound(httpRequestAsBuf(GET, "http://foo.com/"));
    DefaultHttpResponse response = (DefaultHttpResponse) channel.readOutbound();

    assertThat(response.status(), is(io.netty.handler.codec.http.HttpResponseStatus.INTERNAL_SERVER_ERROR));
    verify(responseEnhancer).enhance(any(LiveHttpResponse.Transformer.class), any(LiveHttpRequest.class));
    verify(errorListener, only()).proxyErrorOccurred(any(LiveHttpRequest.class), any(InetSocketAddress.class), eq(INTERNAL_SERVER_ERROR), any(RuntimeException.class));
}
 
Example #24
Source File: HttpPipelineHandlerTest.java    From styx with Apache License 2.0 5 votes vote down vote up
@Test
public void mapsWrappedBadRequestExceptionToBadRequest400ResponseCode() {
    EmbeddedChannel channel = buildEmbeddedChannel(handlerWithMocks());

    String badUri = "/no5_such3_file7.pl?\"><script>alert(73541);</script>56519<script>alert(1)</script>0e134";

    channel.writeInbound(httpMessageToBytes(httpRequest(GET, badUri)));
    DefaultHttpResponse response = (DefaultHttpResponse) channel.readOutbound();

    assertThat(response.getStatus(), is(io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST));
    verify(responseEnhancer).enhance(nullable(LiveHttpResponse.Transformer.class), eq(null));
    verify(errorListener, only()).proxyErrorOccurred(eq(BAD_REQUEST), nullable(DecoderException.class));
}
 
Example #25
Source File: ServletNettyHandler.java    From nettyholdspringmvc with Apache License 2.0 5 votes vote down vote up
@Override
  public void messageReceived(ChannelHandlerContext ctx, HttpRequest request) throws Exception {

      if (!request.getDecoderResult().isSuccess()) {
          sendError(ctx, BAD_REQUEST);
          return;
      }

MockHttpServletRequest servletRequest = createServletRequest(request);
      MockHttpServletResponse servletResponse = new MockHttpServletResponse();

this.servlet.service(servletRequest, servletResponse);

      HttpResponseStatus status = HttpResponseStatus.valueOf(servletResponse.getStatus());
HttpResponse response = new DefaultHttpResponse(HTTP_1_1, status);

for (String name : servletResponse.getHeaderNames()) {
	for (Object value : servletResponse.getHeaderValues(name)) {
		response.addHeader(name, value);
	}
}

      // Write the initial line and the header.
      ctx.write(response);

      InputStream contentStream = new ByteArrayInputStream(servletResponse.getContentAsByteArray());

// Write the content.
      ChannelFuture writeFuture = ctx.write(new ChunkedStream(contentStream));
      writeFuture.addListener(ChannelFutureListener.CLOSE);
  }
 
Example #26
Source File: HttpResponseWriterTest.java    From styx with Apache License 2.0 5 votes vote down vote up
@Test
public void sendsEmptyLastHttpContentWhenContentObservableCompletes() throws Exception {
    CaptureHttpResponseWriteEventsHandler writeEventsCollector = new CaptureHttpResponseWriteEventsHandler();

    EmbeddedChannel ch = new EmbeddedChannel(
            new CaptureChannelArgumentsHandler(channelArgs),
            writeEventsCollector,
            new SimpleChannelInboundHandler<LiveHttpResponse>() {
                @Override
                protected void channelRead0(ChannelHandlerContext ctx, LiveHttpResponse response) throws Exception {
                    HttpResponseWriter writer = new HttpResponseWriter(ctx);

                    CompletableFuture<Void> future = writer.write(response);
                    writeAck(channelArgs);
                    assertThat(future.isDone(), is(false));

                    contentObservable.onComplete();
                    assertThat(future.isDone(), is(false));

                    writeAck(channelArgs);
                    assertThat(future.isDone(), is(true));

                    channelRead.set(true);
                }
            }
    );

    ch.writeInbound(response(OK).body(new ByteStream(contentObservable)).build());
    assertThat(channelRead.get(), is(true));

    List<Object> writeEvents = writeEventsCollector.writeEvents();

    assertThat(writeEvents.get(0), instanceOf(DefaultHttpResponse.class));
    assertThat(writeEvents.get(1), is(EMPTY_LAST_CONTENT));
}
 
Example #27
Source File: Http2StreamFrameToHttpObjectCodecTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Test (expected = EncoderException.class)
public void encodeNonFullHttpResponse100ContinueIsRejected() throws Exception {
    EmbeddedChannel ch = new EmbeddedChannel(new Http2StreamFrameToHttpObjectCodec(true));
    try {
        ch.writeOutbound(new DefaultHttpResponse(
                HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE));
    } finally {
        ch.finishAndReleaseAll();
    }
}
 
Example #28
Source File: WebHdfsHandler.java    From hadoop with Apache License 2.0 5 votes vote down vote up
private void onAppend(ChannelHandlerContext ctx) throws IOException {
  writeContinueHeader(ctx);
  final String nnId = params.namenodeId();
  final int bufferSize = params.bufferSize();

  DFSClient dfsClient = newDfsClient(nnId, conf);
  OutputStream out = dfsClient.append(path, bufferSize,
      EnumSet.of(CreateFlag.APPEND), null, null);
  DefaultHttpResponse resp = new DefaultHttpResponse(HTTP_1_1, OK);
  resp.headers().set(CONTENT_LENGTH, 0);
  ctx.pipeline().replace(this, HdfsWriter.class.getSimpleName(),
    new HdfsWriter(dfsClient, out, resp));
}
 
Example #29
Source File: WebHdfsHandler.java    From hadoop with Apache License 2.0 5 votes vote down vote up
private void onOpen(ChannelHandlerContext ctx) throws IOException {
  final String nnId = params.namenodeId();
  final int bufferSize = params.bufferSize();
  final long offset = params.offset();
  final long length = params.length();

  DefaultHttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
  HttpHeaders headers = response.headers();
  // Allow the UI to access the file
  headers.set(ACCESS_CONTROL_ALLOW_METHODS, GET);
  headers.set(ACCESS_CONTROL_ALLOW_ORIGIN, "*");
  headers.set(CONTENT_TYPE, APPLICATION_OCTET_STREAM);
  headers.set(CONNECTION, CLOSE);

  final DFSClient dfsclient = newDfsClient(nnId, conf);
  HdfsDataInputStream in = dfsclient.createWrappedInputStream(
    dfsclient.open(path, bufferSize, true));
  in.seek(offset);

  long contentLength = in.getVisibleLength() - offset;
  if (length >= 0) {
    contentLength = Math.min(contentLength, length);
  }
  final InputStream data;
  if (contentLength >= 0) {
    headers.set(CONTENT_LENGTH, contentLength);
    data = new LimitInputStream(in, contentLength);
  } else {
    data = in;
  }

  ctx.write(response);
  ctx.writeAndFlush(new ChunkedStream(data) {
    @Override
    public void close() throws Exception {
      super.close();
      dfsclient.close();
    }
  }).addListener(ChannelFutureListener.CLOSE);
}
 
Example #30
Source File: WebHdfsHandler.java    From hadoop with Apache License 2.0 5 votes vote down vote up
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
  LOG.debug("Error ", cause);
  DefaultHttpResponse resp = ExceptionHandler.exceptionCaught(cause);
  resp.headers().set(CONNECTION, CLOSE);
  ctx.writeAndFlush(resp).addListener(ChannelFutureListener.CLOSE);
}