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: 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 #2
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 #3
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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
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 #15
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 #16
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 #17
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 #18
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 #19
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 #20
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 #21
Source File: HttpMetricNamesHandlerTest.java    From blueflood with Apache License 2.0 5 votes vote down vote up
@Test
public void emptyPrefix() throws Exception {
    ArgumentCaptor<FullHttpResponse> argument = ArgumentCaptor.forClass(FullHttpResponse.class);
    handler.handle(context, createGetRequest("/v2.0/" + TENANT + "/metric_name/search"));
    verify(channel).write(argument.capture());
    verify(mockDiscoveryHandle, never()).getMetricNames(anyString(), anyString());

    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", "Invalid Query String", errorResponse.getErrors().get(0).getMessage());
    assertEquals("Invalid tenant", TENANT, errorResponse.getErrors().get(0).getTenantId());
    assertEquals("Invalid status", HttpResponseStatus.BAD_REQUEST, argument.getValue().getStatus());
}
 
Example #22
Source File: WhoisProtocolModuleTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Test
public void testSuccess_parseSingleOutboundHttpResponse() {
  String outputString = "line1\r\nline2\r\n";
  FullHttpResponse response = makeWhoisHttpResponse(outputString, HttpResponseStatus.OK);
  // Http response parsed and passed along.
  assertThat(channel.writeOutbound(response)).isTrue();
  ByteBuf outputBuffer = channel.readOutbound();
  assertThat(outputBuffer.toString(US_ASCII)).isEqualTo(outputString);
  assertThat(channel.isActive()).isFalse();
  // Nothing more to write.
  assertThat((Object) channel.readOutbound()).isNull();
}
 
Example #23
Source File: TestVerifyPinRESTHandler.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Test
public void testMalformedPinCharsErrors() throws Exception {
   Person saved = person.copy();
   EasyMock.expect(personDao.findById(person.getId())).andReturn(person);
   EasyMock.expect(grantDao.findForEntity(person.getId())).andReturn(Arrays.asList(grant));
   EasyMock.expect(client.getPrincipalId()).andReturn(saved.getId()).anyTimes();
   replay();
   FullHttpRequest req = createRequest("1111a", person.getCurrPlace().toString());
   FullHttpResponse res = handler.respond(req, ctx);
   assertError(res, Errors.CODE_INVALID_REQUEST);
}
 
Example #24
Source File: TestVerifyPinRESTHandler.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
private void assertError(FullHttpResponse res, String code) {
   assertEquals(HttpResponseStatus.INTERNAL_SERVER_ERROR, res.getStatus());
   String json = res.content().toString(CharsetUtil.UTF_8);
   ClientMessage clientMessage = JSON.fromJson(json, ClientMessage.class);
   assertEquals("Error", clientMessage.getType());
   assertEquals(code, clientMessage.getPayload().getAttributes().get("code"));
}
 
Example #25
Source File: AsyncRESTHandler.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
public FullHttpResponse respond(FullHttpRequest req, ChannelHandlerContext ctx) throws Exception {
	ClientMessage request;
	MessageBody response;

	try {
		request = decode(req);
	} catch (Throwable t) {
		LOGGER.debug("Unable to decode request", t);
		return response(HttpResponseStatus.BAD_REQUEST, "plain/text", "Unable to decode request");
	}

	HttpResponseStatus status = HttpResponseStatus.OK;
	try {
	   /* preHandleValidation is typically a NOOP. However
	    * there may be times where a RESTHandler might need
	    * AUTH style checks that require access to the
	    * ChannelHandlerContext.
	    */
	   assertValidRequest(req, ctx);
		response = doHandle(request, ctx);
	} catch (Throwable th) {
		LOGGER.error("Error handling client message", th);
		response = Errors.fromException(th);
		status = HttpResponseStatus.INTERNAL_SERVER_ERROR;
	}

	ClientMessage message = ClientMessage.builder().withCorrelationId(request.getCorrelationId())
			.withDestination(request.getSource()).withSource(Addresses.toServiceAddress(PlaceService.NAMESPACE))
			.withPayload(response).create();

	return response(status, BridgeHeaders.CONTENT_TYPE_JSON_UTF8, JSON.toJson(message));
}
 
Example #26
Source File: CaEnrollBenchmark.java    From xipki with Apache License 2.0 5 votes vote down vote up
@Override
public void onComplete(FullHttpResponse response) {
  boolean success;
  try {
    success = onComplete0(response);
  } catch (Throwable th) {
    LOG.warn("unexpected exception", th);
    success = false;
  }

  account(1, success ? 0 : 1);
}
 
Example #27
Source File: TemplatedHttpHandler.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
public FullHttpResponse respond(FullHttpRequest req, ChannelHandlerContext ctx) throws Exception {
   HttpResponseStatus responseStatus = HttpResponseStatus.OK;
   Optional<String> response = Optional.empty();

   try {
      TemplatedResponse handlerResponse = doHandle(req, ctx);
      if (handlerResponse.sectionId.isPresent()) {
         Map<String, String> multiResponse = templateService.renderMultipart(handlerResponse.templateId.get(), handlerResponse.context);
         response = Optional.of(multiResponse.get(handlerResponse.sectionId.get()));
      } else if (handlerResponse.templateId.isPresent()){
         response = Optional.of(templateService.render(handlerResponse.templateId.get(), handlerResponse.context));
      }

      if(!response.isPresent()){
         responseStatus=HttpResponseStatus.NO_CONTENT;
      }

      if(handlerResponse.responseStatus.isPresent()){
         responseStatus=handlerResponse.responseStatus.get();
      }
      

   } catch (Throwable th) {
      LOGGER.error("Error responding to TemplatedRequestHandler", th);
      responseStatus = HttpResponseStatus.INTERNAL_SERVER_ERROR;
   }
   
   FullHttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, responseStatus, Unpooled.copiedBuffer(response.orElse("").getBytes()));
   httpResponse.headers().set(HttpHeaders.Names.CONTENT_TYPE, getContentType());
   return httpResponse;
}
 
Example #28
Source File: ShiroAuthenticator.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
public FullHttpResponse authenticateRequest(Channel channel, String username, String password, String isPublic, ByteBuf responseContentIfSuccess) {
   UsernamePasswordToken token = new UsernamePasswordToken(username, password);
   token.setHost(((InetSocketAddress) channel.remoteAddress()).getHostString());
   token.setRememberMe(!"true".equalsIgnoreCase(isPublic));
   return authenticateRequest(channel, token, responseContentIfSuccess);
}
 
Example #29
Source File: BitsoWebSocket.java    From bitso-java with MIT License 5 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg)
        throws Exception {
    Channel channel = ctx.channel();

    if(!mHandshaker.isHandshakeComplete()) {
        mHandshaker.finishHandshake(channel, (FullHttpResponse) msg);
        mHandshakeFuture.setSuccess();
        return;
    }

    if (msg instanceof FullHttpResponse) {
        FullHttpResponse response = (FullHttpResponse) msg;
        throw new Exception("Unexpected FullHttpResponse (getStatus=" + response.status() + ", content="
                + response.content().toString(CharsetUtil.UTF_8) + ')');
    }

    WebSocketFrame frame = (WebSocketFrame) msg;
    if (frame instanceof TextWebSocketFrame) {
        TextWebSocketFrame textFrame = (TextWebSocketFrame) frame;
        setMessageReceived(textFrame.text());
    }
    
    if(frame instanceof CloseWebSocketFrame){
        setConnected(Boolean.FALSE);
    }
}
 
Example #30
Source File: ProxyToServerConnection.java    From g4proxy with Apache License 2.0 5 votes vote down vote up
@Override
protected ConnectionState readHTTPInitial(HttpResponse httpResponse) {
    LOG.debug("Received raw response: {}", httpResponse);

    if (httpResponse.getDecoderResult().isFailure()) {
        LOG.debug("Could not parse response from server. Decoder result: {}", httpResponse.getDecoderResult().toString());

        // create a "substitute" Bad Gateway response from the server, since we couldn't understand what the actual
        // response from the server was. set the keep-alive on the substitute response to false so the proxy closes
        // the connection to the server, since we don't know what state the server thinks the connection is in.
        FullHttpResponse substituteResponse = ProxyUtils.createFullHttpResponse(HttpVersion.HTTP_1_1,
                HttpResponseStatus.BAD_GATEWAY,
                "Unable to parse response from server");
        HttpHeaders.setKeepAlive(substituteResponse, false);
        httpResponse = substituteResponse;
    }

    currentFilters.serverToProxyResponseReceiving();

    rememberCurrentResponse(httpResponse);
    respondWith(httpResponse);

    if (ProxyUtils.isChunked(httpResponse)) {
        return AWAITING_CHUNK;
    } else {
        currentFilters.serverToProxyResponseReceived();

        return AWAITING_INITIAL;
    }
}