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

The following examples show how to use io.netty.handler.codec.http.FullHttpResponse. 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: NettyHttpResponseMapperTest.java    From flashback with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Test
public void testCookieHeader() throws URISyntaxException, IOException {
  Multimap<String, String> headers = LinkedHashMultimap.create();
  headers.put("key1", "value1");
  headers.put("Set-Cookie", "YSxiLGM=, ZCxlLGY=");
  int status = 200;
  String str = "Hello world";
  RecordedStringHttpBody recordedStringHttpBody = new RecordedStringHttpBody(str);

  RecordedHttpResponse recordedHttpResponse = new RecordedHttpResponse(status, headers, recordedStringHttpBody);
  FullHttpResponse fullHttpResponse = NettyHttpResponseMapper.from(recordedHttpResponse);
  Assert.assertEquals(fullHttpResponse.getStatus().code(), status);
  Assert.assertEquals(fullHttpResponse.headers().get("key1"), "value1");
  List<String> headrValues = fullHttpResponse.headers().getAll("Set-Cookie");
  Assert.assertEquals(headrValues.size(), 1);
  Assert.assertTrue(headrValues.contains("YSxiLGM=, ZCxlLGY="));
}
 
Example #2
Source File: TestVerifyEmailRESTHandler.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Test
public void testRequestEmailVerification_PersonNotExist() throws Exception {
   Person curPerson = createPerson();
   String token = "t123545";
   curPerson.setEmailVerificationToken(token);
   
   mockSetup(curPerson.getId(), token);		
	
	EasyMock.expect(personDao.findById(curPerson.getId())).andReturn(null);
   replay();      
   
   FullHttpResponse response = handler.respond(request, ctx);   
   
   MessageBody mb = toClientRequest(response);
   assertEquals(ErrorEvent.MESSAGE_TYPE, mb.getMessageType());     
   
}
 
Example #3
Source File: Ipcd10WebSocketServerHandler.java    From arcusipcd with Apache License 2.0 6 votes vote down vote up
private void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
    // Generate an error page if response getStatus code is not OK (200).
    if (res.getStatus().code() != 200) {
        ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8);
        res.content().writeBytes(buf);
        buf.release();
        setContentLength(res, res.content().readableBytes());
    }

    // Send the response and close the connection if necessary.
    ChannelFuture f;
    if (useSSL) {
    	f = ctx.channel().writeAndFlush(res);
    } else {
    	// TODO may not want to flush here -- only write
    	f = ctx.channel().writeAndFlush(res);	
    }
    if (!isKeepAlive(req) || res.getStatus().code() != 200) {
        f.addListener(ChannelFutureListener.CLOSE);
    }
}
 
Example #4
Source File: HelloWorldHandler.java    From brave with Apache License 2.0 6 votes vote down vote up
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) {
  if (!(msg instanceof HttpRequest)) return;
  HttpRequest req = (HttpRequest) msg;

  if (HttpUtil.is100ContinueExpected(req)) {
    ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
  }
  boolean keepAlive = HttpUtil.isKeepAlive(req);
  FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK,
    Unpooled.wrappedBuffer(HELLO_WORLD));
  response.headers().set(CONTENT_TYPE, "text/plain");
  response.headers().set(CONTENT_LENGTH, response.content().readableBytes());

  if (!keepAlive) {
    ctx.write(response).addListener(ChannelFutureListener.CLOSE);
  } else {
    response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE);
    ctx.write(response);
  }
}
 
Example #5
Source File: HttpServerHandler.java    From ext-opensource-netty with Mozilla Public License 2.0 6 votes vote down vote up
private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
	// Generate an error page if response getStatus code is not OK (200).
	int statusCode = res.status().code();
	if (statusCode != HttpResponseStatus.OK.code() && res.content().readableBytes() == 0) {
		ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(), CharsetUtil.UTF_8);
		res.content().writeBytes(buf);
		buf.release();
	}
	HttpUtil.setContentLength(res, res.content().readableBytes());

	// Send the response and close the connection if necessary.
	if (!HttpUtil.isKeepAlive(req) || statusCode != HttpResponseStatus.OK.code()) {
		res.headers().set(CONNECTION, CLOSE);
		ctx.writeAndFlush(res).addListener(ChannelFutureListener.CLOSE);
	} else {
		res.headers().set(CONNECTION, CLOSE);

		///
		//if (req.protocolVersion().equals(HTTP_1_0)) {
		//	res.headers().set(CONNECTION, KEEP_ALIVE);
		//}
		ctx.writeAndFlush(res).addListener(ChannelFutureListener.CLOSE);
	}
}
 
Example #6
Source File: HttpAggregatedIngestionHandlerTest.java    From blueflood with Apache License 2.0 6 votes vote down vote up
@Test
public void testValidCounter() throws IOException {

    BluefloodCounter counter = new BluefloodCounter("counter.a.b", 5, 0.1);
    FullHttpRequest request = createIngestRequest(createRequestBody(TENANT,
            new DefaultClockImpl().now().getMillis(), 0, null, new BluefloodCounter[]{counter}, null, null));

    ArgumentCaptor<FullHttpResponse> argument = ArgumentCaptor.forClass(FullHttpResponse.class);
    handler.handle(context, request);
    verify(channel).write(argument.capture());

    String responseBody = argument.getValue().content().toString(Charset.defaultCharset());

    assertEquals("Invalid response", "", responseBody);
    assertEquals("Invalid status", HttpResponseStatus.OK, argument.getValue().getStatus());
}
 
Example #7
Source File: HttpAggregatedIngestionHandlerTest.java    From blueflood with Apache License 2.0 6 votes vote down vote up
@Test
public void testAggregatedMetricsNotSet() throws IOException {

    FullHttpRequest request = createIngestRequest(createRequestBody(TENANT,
            new DefaultClockImpl().now().getMillis(), 0 , null, null, null, null));

    ArgumentCaptor<FullHttpResponse> argument = ArgumentCaptor.forClass(FullHttpResponse.class);
    handler.handle(context, request);
    verify(channel).write(argument.capture());

    String errorResponseBody = argument.getValue().content().toString(Charset.defaultCharset());
    ErrorResponse errorResponse = getErrorResponse(errorResponseBody);

    assertEquals("Number of errors invalid", 1, errorResponse.getErrors().size());
    assertEquals("Invalid error message", "At least one of the aggregated metrics(gauges, counters, timers, sets) " +
            "are expected", errorResponse.getErrors().get(0).getMessage());
    assertEquals("Invalid source", "", errorResponse.getErrors().get(0).getSource());
    assertEquals("Invalid tenant", TENANT, errorResponse.getErrors().get(0).getTenantId());
    assertEquals("Invalid metric name", "", errorResponse.getErrors().get(0).getMetricName());
    assertEquals("Invalid status", HttpResponseStatus.BAD_REQUEST, argument.getValue().getStatus());
}
 
Example #8
Source File: HttpAggregatedIngestionHandlerTest.java    From blueflood with Apache License 2.0 6 votes vote down vote up
@Test
public void testEmptyTenantId() throws IOException {

    BluefloodGauge gauge = new BluefloodGauge("gauge.a.b", 5);
    FullHttpRequest request = createIngestRequest(createRequestBody("",
            new DefaultClockImpl().now().getMillis(), 0 , new BluefloodGauge[]{gauge}, null, null, null));

    ArgumentCaptor<FullHttpResponse> argument = ArgumentCaptor.forClass(FullHttpResponse.class);
    handler.handle(context, request);
    verify(channel).write(argument.capture());

    String errorResponseBody = argument.getValue().content().toString(Charset.defaultCharset());
    ErrorResponse errorResponse = getErrorResponse(errorResponseBody);

    assertEquals("Number of errors invalid", 1, errorResponse.getErrors().size());
    assertEquals("Invalid error message", "may not be empty", errorResponse.getErrors().get(0).getMessage());
    assertEquals("Invalid source", "tenantId", errorResponse.getErrors().get(0).getSource());
    assertEquals("Invalid tenant", "", errorResponse.getErrors().get(0).getTenantId());
    assertEquals("Invalid metric name", "", errorResponse.getErrors().get(0).getMetricName());
    assertEquals("Invalid status", HttpResponseStatus.BAD_REQUEST, argument.getValue().getStatus());
}
 
Example #9
Source File: HttpAggregatedIngestionHandlerTest.java    From blueflood with Apache License 2.0 6 votes vote down vote up
@Test
public void testGaugeEmptyMetricValue() throws IOException {

    String metricName = "gauge.a.b";
    BluefloodGauge gauge = new BluefloodGauge(metricName, null);
    FullHttpRequest request = createIngestRequest(createRequestBody(TENANT,
            new DefaultClockImpl().now().getMillis(), 0, new BluefloodGauge[]{gauge}, null, null, null));

    ArgumentCaptor<FullHttpResponse> argument = ArgumentCaptor.forClass(FullHttpResponse.class);
    handler.handle(context, request);
    verify(channel).write(argument.capture());

    String errorResponseBody = argument.getValue().content().toString(Charset.defaultCharset());
    ErrorResponse errorResponse = getErrorResponse(errorResponseBody);

    assertEquals("Number of errors invalid", 1, errorResponse.getErrors().size());
    assertEquals("Invalid error message", "may not be null", errorResponse.getErrors().get(0).getMessage());
    assertEquals("Invalid source", "gauges[0].value", errorResponse.getErrors().get(0).getSource());
    assertEquals("Invalid tenant", TENANT, errorResponse.getErrors().get(0).getTenantId());
    assertEquals("Invalid metric name", metricName, errorResponse.getErrors().get(0).getMetricName());
    assertEquals("Invalid status", HttpResponseStatus.BAD_REQUEST, argument.getValue().getStatus());
}
 
Example #10
Source File: Http2ClientChannelHandler.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse msg) throws Exception {
    HttpHeaders headers = msg.headers();
    Integer streamId = headers.getInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text());
    if (streamId == null) {
        if (LOGGER.isWarnEnabled()) {
            LOGGER.warn("HttpResponseHandler unexpected message received: {}, data is {}", msg.toString(),
                NettyHelper.toString(msg.content()));
        }
        return;
    }

    Entry<ChannelFuture, AbstractHttpClientHandler> entry = removePromise(streamId);
    if (entry == null) {
        if (LOGGER.isWarnEnabled()) {
            LOGGER.warn("Message received for unknown stream id {}, msg is {}, data is {}", streamId,
                msg.toString(), NettyHelper.toString(msg.content()));
        }
    } else {
        final AbstractHttpClientHandler callback = entry.getValue();
        callback.receiveHttpResponse(msg);
    }
}
 
Example #11
Source File: HttpRollupsQueryHandlerTest.java    From blueflood with Apache License 2.0 6 votes vote down vote up
@Test
public void testMissingRequiredQueryParams() throws IOException {
    FullHttpRequest request = createQueryRequest("?from=111111");

    ArgumentCaptor<FullHttpResponse> argument = ArgumentCaptor.forClass(FullHttpResponse.class);
    handler.handle(context, request);
    verify(channel).write(argument.capture());

    String errorResponseBody = argument.getValue().content().toString(Charset.defaultCharset());
    ErrorResponse errorResponse = getErrorResponse(errorResponseBody);

    assertEquals("Number of errors invalid", 1, errorResponse.getErrors().size());
    assertEquals("Invalid error message", "Either 'points' or 'resolution' is required.", errorResponse.getErrors().get(0).getMessage());
    assertEquals("Invalid tenant", TENANT, errorResponse.getErrors().get(0).getTenantId());
    assertEquals("Invalid status", HttpResponseStatus.BAD_REQUEST, argument.getValue().getStatus());
}
 
Example #12
Source File: NettyHttpFileHandler.java    From khs-stockticker with Apache License 2.0 6 votes vote down vote up
public void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
   if (res.getStatus().code() != 200) {
      ByteBuf f = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8);
      res.content().clear();
      res.content().writeBytes(f);
      f.release();
   }

   HttpHeaders.setContentLength(res, res.content().readableBytes());
   ChannelFuture f1;
   f1 = ctx.channel().writeAndFlush(res);

   if (!HttpHeaders.isKeepAlive(req) || res.getStatus().code() != 200) {
      f1.addListener(ChannelFutureListener.CLOSE);
   }
}
 
Example #13
Source File: SpdyServerHandler.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof HttpRequest) {
        HttpRequest req = (HttpRequest) msg;

        if (is100ContinueExpected(req)) {
            ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
        }
        boolean keepAlive = isKeepAlive(req);

        ByteBuf content = Unpooled.copiedBuffer("Hello World " + new Date(), CharsetUtil.UTF_8);

        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, content);
        response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");
        response.headers().set(CONTENT_LENGTH, response.content().readableBytes());

        if (!keepAlive) {
            ctx.write(response).addListener(ChannelFutureListener.CLOSE);
        } else {
            response.headers().set(CONNECTION, Values.KEEP_ALIVE);
            ctx.write(response);
        }
    }
}
 
Example #14
Source File: HttpServerHandlerTest.java    From shardingsphere with Apache License 2.0 6 votes vote down vote up
@Test
public void assertChannelReadStartSuccess() {
    scalingConfiguration.getRuleConfiguration().setSourceDatasource("ds_0: !!" + YamlDataSourceConfiguration.class.getName() + "\n  "
            + "dataSourceClassName: com.zaxxer.hikari.HikariDataSource\n  props:\n    "
            + "jdbcUrl: jdbc:h2:mem:test_db;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MySQL\n    username: root\n    password: 'password'\n    connectionTimeout: 30000\n    "
            + "idleTimeout: 60000\n    maxLifetime: 1800000\n    maxPoolSize: 50\n    minPoolSize: 1\n    maintenanceIntervalMilliseconds: 30000\n    readOnly: false\n");
    scalingConfiguration.getRuleConfiguration().getDestinationDataSources().setUrl("jdbc:h2:mem:test_db;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MySQL");
    scalingConfiguration.getRuleConfiguration().getDestinationDataSources().setName("root");
    scalingConfiguration.getRuleConfiguration().getDestinationDataSources().setPassword("password");
    ByteBuf byteBuf = Unpooled.copiedBuffer(GSON.toJson(scalingConfiguration), CharsetUtil.UTF_8);
    fullHttpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/scaling/job/start", byteBuf);
    httpServerHandler.channelRead0(channelHandlerContext, fullHttpRequest);
    ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(FullHttpResponse.class);
    verify(channelHandlerContext).writeAndFlush(argumentCaptor.capture());
    FullHttpResponse fullHttpResponse = (FullHttpResponse) argumentCaptor.getValue();
    assertTrue(fullHttpResponse.content().toString(CharsetUtil.UTF_8).contains("{\"success\":true"));
}
 
Example #15
Source File: WebSocketFrameTransport.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg)
{
    final Channel ch = ctx.channel();
    if (!_handshaker.isHandshakeComplete())
    {
        // web socket client connected
        _handshaker.finishHandshake(ch, (FullHttpResponse) msg);
        _handshakeFuture.setSuccess();
        return;
    }

    if (msg instanceof FullHttpResponse)
    {
        final FullHttpResponse response = (FullHttpResponse) msg;
        throw new IllegalStateException(String.format("Unexpected FullHttpResponse (getStatus=%s, content=%s)",
                                          response.content().toString(StandardCharsets.UTF_8), response.status()));
    }

    WebSocketFrame frame = (WebSocketFrame) msg;
    ctx.fireChannelRead(frame.retain());
}
 
Example #16
Source File: HttpUploadServerHandler.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
private void writeResponse(Channel channel, HttpResponseStatus statusCode) {
    // Convert the response content to a ChannelBuffer.
    ByteBuf buf = copiedBuffer(responseContent.toString(), CharsetUtil.UTF_8);
    responseContent.setLength(0);
    // Decide whether to close the connection or not.
    boolean close = HttpHeaders.Values.CLOSE.equalsIgnoreCase(request.headers().get(CONNECTION)) ||
        request.getProtocolVersion().equals(HttpVersion.HTTP_1_0) && !HttpHeaders.Values.KEEP_ALIVE.equalsIgnoreCase(request.headers().get(CONNECTION));
    // Build the response object.
    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, statusCode, buf);
    response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");
    if (!close) {
        // There's no need to add 'Content-Length' header if this is the last response.
        response.headers().set(CONTENT_LENGTH, buf.readableBytes());
    }
    // Write the response.
    ChannelFuture future = channel.writeAndFlush(response);
    // Close the connection after the write operation is done if necessary.
    if (close) {
        future.addListener(ChannelFutureListener.CLOSE);
    }
}
 
Example #17
Source File: HttpGremlinEndpointHandler.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
private static void sendError(final ChannelHandlerContext ctx, final HttpResponseStatus status,
                                final String message, final Optional<Throwable> t) {
      if (t.isPresent())
          logger.warn(String.format("Invalid request - responding with %s and %s", status, message), t.get());
      else
          logger.warn(String.format("Invalid request - responding with %s and %s", status, message));

      errorMeter.mark();
      final ObjectNode node = mapper.createObjectNode();
      node.put("message", message);
if (t.isPresent()) {
          // "Exception-Class" needs to go away - didn't realize it was named that way during review for some reason.
          // replaced with the same method for exception reporting as is used with websocket/nio protocol
	node.put("Exception-Class", t.get().getClass().getName());
          final ArrayNode exceptionList = node.putArray(Tokens.STATUS_ATTRIBUTE_EXCEPTIONS);
          ExceptionUtils.getThrowableList(t.get()).forEach(throwable -> exceptionList.add(throwable.getClass().getName()));
          node.put(Tokens.STATUS_ATTRIBUTE_STACK_TRACE, ExceptionUtils.getStackTrace(t.get()));
}

      final FullHttpResponse response = new DefaultFullHttpResponse(
              HTTP_1_1, status, Unpooled.copiedBuffer(node.toString(), CharsetUtil.UTF_8));
      response.headers().set(CONTENT_TYPE, "application/json");

      // Close the connection as soon as the error message is sent.
      ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
  }
 
Example #18
Source File: HttpAggregatedIngestionHandlerTest.java    From blueflood with Apache License 2.0 6 votes vote down vote up
@Test
public void testCounterEmptyMetricRate() throws IOException {

    String metricName = "counter.a.b";
    BluefloodCounter counter = new BluefloodCounter(metricName, 5, null);
    FullHttpRequest request = createIngestRequest(createRequestBody(TENANT,
            new DefaultClockImpl().now().getMillis(), 0, null, new BluefloodCounter[]{counter}, null, null));

    ArgumentCaptor<FullHttpResponse> argument = ArgumentCaptor.forClass(FullHttpResponse.class);
    handler.handle(context, request);
    verify(channel).write(argument.capture());

    String errorResponseBody = argument.getValue().content().toString(Charset.defaultCharset());
    ErrorResponse errorResponse = getErrorResponse(errorResponseBody);

    assertEquals("Number of errors invalid", 1, errorResponse.getErrors().size());
    assertEquals("Invalid error message", "may not be null", errorResponse.getErrors().get(0).getMessage());
    assertEquals("Invalid source", "counters[0].rate", errorResponse.getErrors().get(0).getSource());
    assertEquals("Invalid tenant", TENANT, errorResponse.getErrors().get(0).getTenantId());
    assertEquals("Invalid metric name", metricName, errorResponse.getErrors().get(0).getMetricName());
    assertEquals("Invalid status", HttpResponseStatus.BAD_REQUEST, argument.getValue().getStatus());
}
 
Example #19
Source File: TemplatedHttpHandlerTest.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldRespondWithResponseCode() throws Exception {
   
   handler = new TemplatedHttpHandler(new AlwaysAllow(),httpSender,templateService) {
      public String getContentType() {
         return "application/xml";
      }
      public TemplatedResponse doHandle(FullHttpRequest request, ChannelHandlerContext ctx) {
         return new TemplatedResponse().withResponseStatus(HttpResponseStatus.NOT_FOUND);
      }
   }; 
   replay();
   FullHttpResponse response = handler.respond(fullHttpRequest,ctx);
   verify();
   assertEquals(HttpResponseStatus.NOT_FOUND, response.getStatus());
}
 
Example #20
Source File: WebWhoisProtocolsModuleTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
/**
 * Tests that the client converts given {@link FullHttpRequest} to bytes, which is sent to the
 * server and reconstructed to a {@link FullHttpRequest} that is equivalent to the original. Then
 * test that the server converts given {@link FullHttpResponse} to bytes, which is sent to the
 * client and reconstructed to a {@link FullHttpResponse} that is equivalent to the original.
 *
 * <p>The request and response equivalences are tested in the same method because the client codec
 * tries to pair the response it receives with the request it sends. Receiving a response without
 * sending a request first will cause the {@link HttpObjectAggregator} to fail to aggregate
 * properly.
 */
private void requestAndRespondWithStatus(HttpResponseStatus status) {
  ByteBuf buffer;
  FullHttpRequest requestSent = makeHttpGetRequest(HOST, PATH);
  // Need to send a copy as the content read index will advance after the request is written to
  // the outbound of client channel, making comparison with requestReceived fail.
  assertThat(clientChannel.writeOutbound(requestSent.copy())).isTrue();
  buffer = clientChannel.readOutbound();
  assertThat(channel.writeInbound(buffer)).isTrue();
  // We only have a DefaultHttpRequest, not a FullHttpRequest because there is no HTTP aggregator
  // in the server's pipeline. But it is fine as we are not interested in the content (payload) of
  // the request, just its headers, which are contained in the DefaultHttpRequest.
  DefaultHttpRequest requestReceived = channel.readInbound();
  // Verify that the request received is the same as the request sent.
  assertHttpRequestEquivalent(requestSent, requestReceived);

  FullHttpResponse responseSent = makeHttpResponse(status);
  assertThat(channel.writeOutbound(responseSent.copy())).isTrue();
  buffer = channel.readOutbound();
  assertThat(clientChannel.writeInbound(buffer)).isTrue();
  FullHttpResponse responseReceived = clientChannel.readInbound();
  // Verify that the request received is the same as the request sent.
  assertHttpResponseEquivalent(responseSent, responseReceived);
}
 
Example #21
Source File: SimpleWampWebsocketListener.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
private static void sendHttpResponse(
    ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
    // Generate an error page if response getStatus code is not OK (200).
    if (res.getStatus().code() != 200) {
        ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8);
        res.content().writeBytes(buf);
        buf.release();
        HttpHeaders.setContentLength(res, res.content().readableBytes());
    }
    // Send the response and close the connection if necessary.
    ChannelFuture f = ctx.channel().writeAndFlush(res);
    if (!HttpHeaders.isKeepAlive(req) || res.getStatus().code() != 200) {
        f.addListener(ChannelFutureListener.CLOSE);
    }
}
 
Example #22
Source File: HandlerResponse.java    From cantor with Apache License 2.0 5 votes vote down vote up
HandlerResponse(HandlerRequest request,
                AffinityScheduler scheduler,
                TriConsumer<FullHttpResponse, Runnable, Consumer<Throwable>> writer) {
    this.httpVer = request.version();
    this.scheduler = scheduler;
    this.writer = writer;
}
 
Example #23
Source File: HttpAggregatedIngestionHandlerTest.java    From blueflood with Apache License 2.0 5 votes vote down vote up
@Test
public void perTenantMetricsOn_shouldRecordDelayedMetrics() throws Exception {
    BluefloodSet set1 = new BluefloodSet("delayed.me.1.set.a.b", new String[]{"", ""});
    BluefloodSet set2 = new BluefloodSet("delayed.me.2.set.a.b", new String[]{"", ""});
    long delayedTime = new DefaultClockImpl().now().getMillis() - 100 -
            Configuration.getInstance().getLongProperty(CoreConfig.ROLLUP_DELAY_MILLIS);
    FullHttpRequest request = createIngestRequest(
                                createRequestBody(TENANT, delayedTime, 0, null, null,
                                        null, new BluefloodSet[]{set1, set2}));

    long ingestedMetricsBefore = ingestedMetrics.getCount();
    long ingestedDelayedMetricsBefore = ingestedDelayedMetrics.getCount();

    ListenableFuture<List<Boolean>> futures = mock(ListenableFuture.class);
    List<Boolean> answers = new ArrayList<>();
    answers.add(Boolean.TRUE);
    when(processor.apply(any())).thenReturn(futures);
    when(futures.get(anyLong(), any())).thenReturn(answers);

    HttpAggregatedIngestionHandler handler = spy(new HttpAggregatedIngestionHandler(processor, new TimeValue(5, TimeUnit.SECONDS), true));
    ArgumentCaptor<FullHttpResponse> argument = ArgumentCaptor.forClass(FullHttpResponse.class);
    handler.handle(context, request);
    verify(channel).write(argument.capture());
    verify(handler, times(1)).recordPerTenantMetrics(eq(TENANT), eq(0), eq(2));

    assertEquals("ingested metrics count", 0, ingestedMetrics.getCount() - ingestedMetricsBefore);
    assertEquals("ingested delayed metrics count", 2, ingestedDelayedMetrics.getCount() - ingestedDelayedMetricsBefore);
}
 
Example #24
Source File: FunctionsChannelHandler.java    From netty-cookbook with Apache License 2.0 5 votes vote down vote up
private static void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
	ByteBuf content = Unpooled.copiedBuffer(
			"Failure: " + status.toString() + "\r\n",
			CharsetUtil.UTF_8);
	FullHttpResponse fullHttpResponse = new DefaultFullHttpResponse(
			HTTP_1_1,
			status,
			content
	);
	fullHttpResponse.headers().add(CONTENT_TYPE, "text/plain; charset=UTF-8");

	// Close the connection as soon as the error message is sent.
	ctx.write(fullHttpResponse).addListener(ChannelFutureListener.CLOSE);
}
 
Example #25
Source File: HttpProcessHandler.java    From dubbo-2.6.5 with Apache License 2.0 5 votes vote down vote up
private static final FullHttpResponse http_404() {
    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND);
    HttpHeaders httpHeaders = response.headers();
    httpHeaders.set(HttpHeaders.Names.CONTENT_TYPE, "text/plain");
    httpHeaders.set(HttpHeaders.Names.CONTENT_LENGTH, response.content().readableBytes());
    return response;
}
 
Example #26
Source File: NettyHttpUtil.java    From netty-cookbook with Apache License 2.0 5 votes vote down vote up
public static FullHttpResponse theBase64Image1pxGif() {
	ByteBuf byteBuf = Base64.decode(Unpooled.copiedBuffer(BASE64GIF_BYTES));
	FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK , byteBuf);
	response.headers().set(CONTENT_TYPE, ContentTypePool.GIF);
	response.headers().set(CONTENT_LENGTH, byteBuf.readableBytes());
	response.headers().set(CONNECTION, HEADER_CONNECTION_CLOSE);
	return response;
}
 
Example #27
Source File: TestChangePinRESTHandler.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Test
public void testMalformedPinCharsErrors() throws Exception {
   EasyMock.expect(personDao.findById(person.getId())).andReturn(person);
   replay();
   FullHttpRequest req = createRequest(null, "111a");
   FullHttpResponse res = handler.respond(req, ctx);
   assertError(res, Errors.CODE_INVALID_REQUEST);
}
 
Example #28
Source File: NettyHttpServerHandler.java    From piranha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Read the channel.
 *
 * @param context the context.
 * @param object the object read.
 */
@Override
protected void channelRead0(ChannelHandlerContext context, FullHttpRequest object) {
    NettyHttpServerRequest nettyRequest = new NettyHttpServerRequest(context, object);
    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, true);
    NettyHttpServerResponse nettyResponse = new NettyHttpServerResponse(response);
    httpServerProcessor.process(nettyRequest, nettyResponse);
    ChannelFuture future = context.channel().writeAndFlush(response);
    future.addListener(ChannelFutureListener.CLOSE);
}
 
Example #29
Source File: HttpsRelayServiceHandler.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Override
protected void encode(ChannelHandlerContext ctx, FullHttpResponse response, ByteBuf byteBuf)
    throws Exception {
  if (!response.status().equals(HttpResponseStatus.OK)) {
    throw new NonOkHttpResponseException(response, ctx.channel());
  }
  saveCookies(response);
  byteBuf.writeBytes(encodeFullHttpResponse(response));
}
 
Example #30
Source File: HttpResponse.java    From ns4_frame with Apache License 2.0 5 votes vote down vote up
private void writeResponseLocation(Channel channel, String URL) {
    // Decide whether to close the connection or not.
    boolean close = false;
    // Build the response object.
    FullHttpResponse response = new DefaultFullHttpResponse(
            HttpVersion.HTTP_1_1, HttpResponseStatus.FOUND);
    response.headers().set(CONTENT_TYPE, ContentType.HTML);
    response.headers().set(LOCATION, URL);
    response.headers().set(CONTENT_LENGTH, 0);
    // Write the response.
    ChannelFuture future = channel.writeAndFlush(response);
    future.addListener(ChannelFutureListener.CLOSE);
}