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

The following examples show how to use io.netty.handler.codec.http.HttpResponseStatus. 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: Api.java    From xyz-hub with Apache License 2.0 6 votes vote down vote up
private void sendResponse(final Task task, HttpResponseStatus status, String contentType, final byte[] response) {

    HttpServerResponse httpResponse = task.context.response().setStatusCode(status.code());

    CacheProfile cacheProfile = task.getCacheProfile();
    if (cacheProfile.browserTTL > 0) {
      httpResponse.putHeader(HttpHeaders.CACHE_CONTROL, "private, max-age=" + (cacheProfile.browserTTL / 1000));
    }

    if (response == null || response.length == 0) {
      httpResponse.end();
    } else if (response.length > getMaxResponseLength(task.context)) {
      sendErrorResponse(task.context, new HttpException(RESPONSE_PAYLOAD_TOO_LARGE, RESPONSE_PAYLOAD_TOO_LARGE_MESSAGE));
    } else {
      httpResponse.putHeader(CONTENT_TYPE, contentType);
      httpResponse.end(Buffer.buffer(response));
    }
  }
 
Example #2
Source File: Http2StreamFrameToHttpObjectCodecTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Test
public void testDecodeFullResponseHeaders() throws Exception {
    EmbeddedChannel ch = new EmbeddedChannel(new Http2StreamFrameToHttpObjectCodec(false));
    Http2Headers headers = new DefaultHttp2Headers();
    headers.scheme(HttpScheme.HTTP.name());
    headers.status(HttpResponseStatus.OK.codeAsText());

    assertTrue(ch.writeInbound(new DefaultHttp2HeadersFrame(headers, true)));

    FullHttpResponse response = ch.readInbound();
    try {
        assertThat(response.status(), is(HttpResponseStatus.OK));
        assertThat(response.protocolVersion(), is(HttpVersion.HTTP_1_1));
        assertThat(response.content().readableBytes(), is(0));
        assertTrue(response.trailingHeaders().isEmpty());
        assertFalse(HttpUtil.isTransferEncodingChunked(response));
    } finally {
        response.release();
    }

    assertThat(ch.readInbound(), is(nullValue()));
    assertFalse(ch.finish());
}
 
Example #3
Source File: TimelyExceptionHandler.java    From timely with Apache License 2.0 6 votes vote down vote up
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    // ignore SSLHandshakeException when using a self-signed server certificate
    if (ignoreSslHandshakeErrors && cause.getCause() instanceof SSLHandshakeException) {
        return;
    }
    LOG.error("Unhandled exception in pipeline", cause);
    if (cause instanceof TimelyException) {
        this.sendHttpError(ctx, (TimelyException) cause);
    } else if (null != cause.getCause() && cause.getCause() instanceof TimelyException) {
        this.sendHttpError(ctx, (TimelyException) cause.getCause());
    } else {
        TimelyException e = new TimelyException(HttpResponseStatus.INTERNAL_SERVER_ERROR.code(), cause.getMessage(),
                "");
        this.sendHttpError(ctx, e);
    }
}
 
Example #4
Source File: WebSocketClientHandshaker08.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
/**
 * <p>
 * Process server response:
 * </p>
 *
 * <pre>
 * HTTP/1.1 101 Switching Protocols
 * Upgrade: websocket
 * Connection: Upgrade
 * Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
 * Sec-WebSocket-Protocol: chat
 * </pre>
 *
 * @param response
 *            HTTP response returned from the server for the request sent by beginOpeningHandshake00().
 * @throws WebSocketHandshakeException
 */
@Override
protected void verify(FullHttpResponse response) {
    final HttpResponseStatus status = HttpResponseStatus.SWITCHING_PROTOCOLS;
    final HttpHeaders headers = response.headers();

    if (!response.status().equals(status)) {
        throw new WebSocketHandshakeException("Invalid handshake response getStatus: " + response.status());
    }

    CharSequence upgrade = headers.get(HttpHeaderNames.UPGRADE);
    if (!HttpHeaderValues.WEBSOCKET.contentEqualsIgnoreCase(upgrade)) {
        throw new WebSocketHandshakeException("Invalid handshake response upgrade: " + upgrade);
    }

    if (!headers.containsValue(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE, true)) {
        throw new WebSocketHandshakeException("Invalid handshake response connection: "
                + headers.get(HttpHeaderNames.CONNECTION));
    }

    CharSequence accept = headers.get(HttpHeaderNames.SEC_WEBSOCKET_ACCEPT);
    if (accept == null || !accept.equals(expectedChallengeResponseString)) {
        throw new WebSocketHandshakeException(String.format(
                "Invalid challenge. Actual: %s. Expected: %s", accept, expectedChallengeResponseString));
    }
}
 
Example #5
Source File: ModelServerTest.java    From serve with Apache License 2.0 6 votes vote down vote up
@Test(
        alwaysRun = true,
        dependsOnMethods = {"testPredictionsModelNotFound"})
public void testInvalidManagementUri() throws InterruptedException {
    Channel channel = TestUtils.connect(true, configManager);
    Assert.assertNotNull(channel);

    HttpRequest req =
            new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/InvalidUrl");
    channel.writeAndFlush(req).sync();
    channel.closeFuture().sync();

    ErrorResponse resp = JsonUtils.GSON.fromJson(TestUtils.getResult(), ErrorResponse.class);

    Assert.assertEquals(resp.getCode(), HttpResponseStatus.NOT_FOUND.code());
    Assert.assertEquals(resp.getMessage(), ERROR_NOT_FOUND);
}
 
Example #6
Source File: RequestProcessor.java    From mantis with Apache License 2.0 6 votes vote down vote up
public Observable<Void> simulateTimeout(HttpServerRequest<ByteBuf> httpRequest, HttpServerResponse<ByteBuf> response) {
    String uri = httpRequest.getUri();
    QueryStringDecoder decoder = new QueryStringDecoder(uri);
    List<String> timeout = decoder.parameters().get("timeout");
    byte[] contentBytes;
    HttpResponseStatus status = HttpResponseStatus.NO_CONTENT;
    if (null != timeout && !timeout.isEmpty()) {
        try {
            Thread.sleep(Integer.parseInt(timeout.get(0)));
            contentBytes = "".getBytes();
        } catch (Exception e) {
            contentBytes = e.getMessage().getBytes();
            status = HttpResponseStatus.INTERNAL_SERVER_ERROR;
        }
    } else {
        status = HttpResponseStatus.BAD_REQUEST;
        contentBytes = "Please provide a timeout parameter.".getBytes();
    }

    response.setStatus(status);
    return response.writeBytesAndFlush(contentBytes);
}
 
Example #7
Source File: EventbusRequest.java    From vxms with Apache License 2.0 6 votes vote down vote up
/**
 * Quickreply, send message over event-bus and pass the result directly to rest response
 *
 * @param targetId the target id to send to
 * @param message the message to send
 * @param options the event-bus delivery serverOptions
 */
public void sendAndRespondRequest(String targetId, Object message, DeliveryOptions options) {
  final Vertx vertx = vxmsShared.getVertx();
  vertx
      .eventBus()
      .send(
          targetId,
          message,
          options != null ? options : new DeliveryOptions(),
          event -> {
            final HttpServerResponse response = context.response();
            if (event.failed()) {
              response.setStatusCode(HttpResponseStatus.SERVICE_UNAVAILABLE.code()).end();
            }
            Optional.ofNullable(event.result())
                .ifPresent(
                    result ->
                        Optional.ofNullable(result.body())
                            .ifPresent(resp -> respond(response, resp)));
          });
}
 
Example #8
Source File: ConsumerService.java    From strimzi-kafka-bridge with Apache License 2.0 6 votes vote down vote up
public ConsumerService subscribeTopic(VertxTestContext context, String groupId, String name, JsonObject... partition) throws InterruptedException, ExecutionException, TimeoutException {
    CompletableFuture<Boolean> subscribe = new CompletableFuture<>();
    // subscribe to a topic
    JsonArray partitions = new JsonArray();
    for (JsonObject p : partition) {
        partitions.add(p);
    }

    JsonObject partitionsRoot = new JsonObject();
    partitionsRoot.put("partitions", partitions);

    postRequest(Urls.consumerInstanceAssignments(groupId, name))
            .putHeader(CONTENT_LENGTH.toString(), String.valueOf(partitionsRoot.toBuffer().length()))
            .putHeader(CONTENT_TYPE.toString(), BridgeContentType.KAFKA_JSON)
            .as(BodyCodec.jsonObject())
            .sendJsonObject(partitionsRoot, ar -> {
                context.verify(() -> {
                    assertThat(ar.succeeded(), is(true));
                    assertThat(ar.result().statusCode(), is(HttpResponseStatus.NO_CONTENT.code()));
                });
                subscribe.complete(true);
            });
    subscribe.get(HTTP_REQUEST_TIMEOUT, TimeUnit.SECONDS);
    return this;
}
 
Example #9
Source File: NettyResponseUtil.java    From HAP-Java with MIT License 6 votes vote down vote up
public static FullHttpResponse createResponse(HttpResponse homekitResponse) {

    FullHttpResponse response =
        new DefaultFullHttpResponse(
            homekitResponse.getVersion() == HttpResponse.HttpVersion.EVENT_1_0
                ? EVENT_VERSION
                : HttpVersion.HTTP_1_1,
            HttpResponseStatus.valueOf(homekitResponse.getStatusCode()),
            Unpooled.copiedBuffer(homekitResponse.getBody()));
    for (Entry<String, String> header : homekitResponse.getHeaders().entrySet()) {
      response.headers().add(header.getKey(), header.getValue());
    }
    response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, response.content().readableBytes());
    response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    return response;
  }
 
Example #10
Source File: ManagementRequestHandler.java    From serve with Apache License 2.0 6 votes vote down vote up
private void setDefaultModelVersion(
        ChannelHandlerContext ctx, String modelName, String newModelVersion)
        throws ModelNotFoundException, InternalServerException, RequestTimeoutException,
                ModelVersionNotFoundException {
    ModelManager modelManager = ModelManager.getInstance();
    HttpResponseStatus httpResponseStatus =
            modelManager.setDefaultVersion(modelName, newModelVersion);
    if (httpResponseStatus == HttpResponseStatus.NOT_FOUND) {
        throw new ModelNotFoundException("Model not found: " + modelName);
    } else if (httpResponseStatus == HttpResponseStatus.FORBIDDEN) {
        throw new ModelVersionNotFoundException(
                "Model version " + newModelVersion + " does not exist for model " + modelName);
    }
    String msg =
            "Default vesion succsesfully updated for model \""
                    + modelName
                    + "\" to \""
                    + newModelVersion
                    + "\"";
    SnapshotManager.getInstance().saveSnapshot();
    NettyUtils.sendJsonResponse(ctx, new StatusResponse(msg));
}
 
Example #11
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 #12
Source File: GrpcRequestHandlerTest.java    From xio with Apache License 2.0 6 votes vote down vote up
@Test
public void testCompressedFlag() {
  HelloRequest grpcRequest = HelloRequest.newBuilder().setName("myName").build();
  ByteBuf grpcRequestBuffer = bufferFor(grpcRequest, true);
  int streamId = 345;

  SegmentedRequestData segmentedRequest = fullGrpcRequest(grpcRequestBuffer, streamId, true);
  channel.writeInbound(segmentedRequest);

  Response response = channel.readOutbound();
  SegmentedData segmentedData = channel.readOutbound();

  assertEquals(HttpResponseStatus.OK, response.status());
  assertEquals(streamId, response.streamId());
  assertEquals("application/grpc+proto", response.headers().get(HttpHeaderNames.CONTENT_TYPE));

  assertEquals("12", Objects.requireNonNull(segmentedData.trailingHeaders()).get("grpc-status"));
  String actualMessage =
      grpcDecodedString(
          Objects.requireNonNull(
              Objects.requireNonNull(segmentedData.trailingHeaders()).get("grpc-message")));
  assertEquals("compression not supported", actualMessage);
  assertEquals(streamId, segmentedData.streamId());
  assertTrue(segmentedData.endOfMessage());
}
 
Example #13
Source File: GraphQLHttpServiceTest.java    From besu with Apache License 2.0 6 votes vote down vote up
@Test
public void handleEmptyRequestAndRedirect_get() throws Exception {
  try (final Response resp =
      client.newCall(new Request.Builder().get().url(service.url()).build()).execute()) {
    Assertions.assertThat(resp.code()).isEqualTo(HttpResponseStatus.PERMANENT_REDIRECT.code());
    final String location = resp.header("Location");
    Assertions.assertThat(location).isNotEmpty().isNotNull();
    final HttpUrl redirectUrl = resp.request().url().resolve(location);
    Assertions.assertThat(redirectUrl).isNotNull();
    final Request.Builder redirectBuilder = resp.request().newBuilder();
    redirectBuilder.get();
    // resp.body().close();
    try (final Response redirectResp =
        client.newCall(redirectBuilder.url(redirectUrl).build()).execute()) {
      Assertions.assertThat(redirectResp.code()).isEqualTo(HttpResponseStatus.BAD_REQUEST.code());
    }
  }
}
 
Example #14
Source File: TrackerService.java    From twill with Apache License 2.0 6 votes vote down vote up
private void writeResourceReport(Channel channel) {
  ByteBuf content = Unpooled.buffer();
  Writer writer = new OutputStreamWriter(new ByteBufOutputStream(content), CharsetUtil.UTF_8);
  try {
    reportAdapter.toJson(resourceReport.get(), writer);
    writer.close();
  } catch (IOException e) {
    LOG.error("error writing resource report", e);
    writeAndClose(channel, new DefaultFullHttpResponse(
      HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR,
      Unpooled.copiedBuffer(e.getMessage(), StandardCharsets.UTF_8)));
    return;
  }

  FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);
  HttpUtil.setContentLength(response, content.readableBytes());
  response.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json; charset=UTF-8");
  channel.writeAndFlush(response);
}
 
Example #15
Source File: ModelServerTest.java    From multi-model-server with Apache License 2.0 6 votes vote down vote up
private void testModelRegisterWithDefaultWorkers(Channel mgmtChannel)
        throws NoSuchFieldException, IllegalAccessException, InterruptedException {
    setConfiguration("default_workers_per_model", "1");
    loadTests(mgmtChannel, "noop-v1.0", "noop_default_model_workers");

    result = null;
    latch = new CountDownLatch(1);
    HttpRequest req =
            new DefaultFullHttpRequest(
                    HttpVersion.HTTP_1_1, HttpMethod.GET, "/models/noop_default_model_workers");
    mgmtChannel.writeAndFlush(req);

    latch.await();
    DescribeModelResponse resp = JsonUtils.GSON.fromJson(result, DescribeModelResponse.class);
    Assert.assertEquals(httpStatus, HttpResponseStatus.OK);
    Assert.assertEquals(resp.getMinWorkers(), 1);
    unloadTests(mgmtChannel, "noop_default_model_workers");
    setConfiguration("default_workers_per_model", "0");
}
 
Example #16
Source File: VerifyRequestSizeValidationComponentTest.java    From riposte with Apache License 2.0 6 votes vote down vote up
@Test
public void should_return_expected_response_when_endpoint_disabled_ContentLength_header_above_global_size_validation() {
    ExtractableResponse response =
            given()
                    .baseUri(BASE_URI)
                    .port(serverConfig.endpointsPort())
                    .basePath(BasicEndpointWithRequestSizeValidationDisabled.MATCHING_PATH)
                    .log().all()
                    .body(generatePayloadOfSizeInBytes(GLOBAL_MAX_REQUEST_SIZE + 100))
                    .when()
                    .post()
                    .then()
                    .log().headers()
                    .extract();

    assertThat(response.statusCode()).isEqualTo(HttpResponseStatus.OK.code());
    assertThat(response.asString()).isEqualTo(BasicEndpointWithRequestSizeValidationDisabled.RESPONSE_PAYLOAD);
}
 
Example #17
Source File: TestShiroAuthenticator.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Test
public void testLoginBadPassword() throws Exception {
   Login login = new Login();
   login.setUserId(UUID.randomUUID());
   login.setUsername("joe");
   login.setPassword("password");
   
   EasyMock
      .expect(authenticationDao.findLogin("joe"))
      .andReturn(login);
   
   replay();
   
   DefaultFullHttpRequest request = new DefaultFullHttpRequest(
         HttpVersion.HTTP_1_1, 
         HttpMethod.POST, 
         "http://localhost/client",
         Unpooled.wrappedBuffer("{username:\"joe\",password:\"wrong\"}".getBytes("UTF-8"))
   );
   
   FullHttpResponse response = authenticator.authenticateRequest(channel, request);
   assertEquals(HttpResponseStatus.UNAUTHORIZED, response.getStatus());
   assertCookieCleared(response);
   
   verify();
}
 
Example #18
Source File: VerifyRequestSizeValidationComponentTest.java    From riposte with Apache License 2.0 6 votes vote down vote up
@Test
public void should_return_expected_response_when_chunked_request_not_exceeding_global_request_size() throws Exception {
    NettyHttpClientRequestBuilder request = request()
        .withMethod(HttpMethod.POST)
        .withUri(BasicEndpoint.MATCHING_PATH)
        .withPaylod(generatePayloadOfSizeInBytes(GLOBAL_MAX_REQUEST_SIZE))
        .withHeader(HttpHeaders.Names.TRANSFER_ENCODING, CHUNKED);

    // when
    NettyHttpClientResponse serverResponse = request.execute(serverConfig.endpointsPort(),
                                                            incompleteCallTimeoutMillis);

    // then
    assertThat(serverResponse.statusCode).isEqualTo(HttpResponseStatus.OK.code());
    assertThat(serverResponse.payload).isEqualTo(BasicEndpoint.RESPONSE_PAYLOAD);
}
 
Example #19
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 #20
Source File: HttpUploadHandlerTest.java    From bazel with Apache License 2.0 6 votes vote down vote up
/**
 * Test that the handler correctly supports http error codes i.e. 404 (NOT FOUND) with a
 * Content-Length header.
 */
@Test
public void httpErrorsWithContentAreSupported() {
  EmbeddedChannel ch = new EmbeddedChannel(new HttpUploadHandler(null, ImmutableList.of()));
  ByteArrayInputStream data = new ByteArrayInputStream(new byte[] {1, 2, 3, 4, 5});
  ChannelPromise writePromise = ch.newPromise();
  ch.writeOneOutbound(new UploadCommand(CACHE_URI, true, "abcdef", data, 5), writePromise);

  HttpRequest request = ch.readOutbound();
  assertThat(request).isInstanceOf(HttpRequest.class);
  HttpChunkedInput content = ch.readOutbound();
  assertThat(content).isInstanceOf(HttpChunkedInput.class);

  ByteBuf errorMsg = ByteBufUtil.writeAscii(ch.alloc(), "error message");
  FullHttpResponse response =
      new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND, errorMsg);
  response.headers().set(HttpHeaders.CONNECTION, HttpHeaderValues.KEEP_ALIVE);

  ch.writeInbound(response);

  assertThat(writePromise.isDone()).isTrue();
  assertThat(writePromise.cause()).isInstanceOf(HttpException.class);
  assertThat(((HttpException) writePromise.cause()).response().status())
      .isEqualTo(HttpResponseStatus.NOT_FOUND);
  assertThat(ch.isOpen()).isTrue();
}
 
Example #21
Source File: NettyHttpUtil.java    From netty-cookbook with Apache License 2.0 5 votes vote down vote up
public static FullHttpResponse theHttpContent(String str, HttpResponseStatus status) {
	ByteBuf byteBuf = Unpooled.copiedBuffer(str.getBytes());
	FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, status ,byteBuf);
	response.headers().set(CONTENT_TYPE, ContentTypePool.TEXT_UTF8);
	response.headers().set(CONTENT_LENGTH, byteBuf.readableBytes());
	response.headers().set(CONNECTION, HEADER_CONNECTION_CLOSE);
	return response;
}
 
Example #22
Source File: Http2Handler.java    From xrpc with Apache License 2.0 5 votes vote down vote up
/** Marks the meter for the given response status in the given connection context. */
private void markResponseStatus(ChannelHandlerContext ctx, HttpResponseStatus status) {
  ServerContext xctx = ctx.channel().attr(ServerContext.ATTRIBUTE_KEY).get();
  // TODO(jkinkead): Per issue #152, this should track ALL response codes.
  Meter meter = xctx.metersByStatusCode().get(status);
  if (meter != null) {
    meter.mark();
  }
}
 
Example #23
Source File: HttpUtil.java    From prebid-server-java with Apache License 2.0 5 votes vote down vote up
/**
 * Sends HTTP response according to the given status and body
 */
public static void respondWith(RoutingContext context, HttpResponseStatus status, String body) {
    final HttpServerResponse response = context.response().setStatusCode(status.code());
    if (body != null) {
        response.end(body);
    } else {
        response.end();
    }
}
 
Example #24
Source File: RestRouteInitializer.java    From vxms with Apache License 2.0 5 votes vote down vote up
private static void failRequest(RoutingContext routingContext, Throwable throwable) {
    routingContext
            .response()
            .setStatusCode(HttpResponseStatus.INTERNAL_SERVER_ERROR.code())
            .setStatusMessage(throwable.getMessage())
            .end();
    throwable.printStackTrace();
}
 
Example #25
Source File: TestChangePinRESTHandler.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 #26
Source File: ResourceHandler.java    From socketio with Apache License 2.0 5 votes vote down vote up
private void sendNotModified(ChannelHandlerContext ctx) {
  HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_MODIFIED);
  setDateHeader(response);

  // Close the connection as soon as the error message is sent.
  ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}
 
Example #27
Source File: ErrorHandlingTest.java    From vertx-swagger with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 2000)
public void testStatusCodeAndNullStatusMessage(TestContext context) {
    Async async = context.async();
    httpClient.getNow(TEST_PORT, TEST_HOST, "/v2/store/order/1", response -> {
        context.assertEquals(response.statusCode(), EXISTING_HTTP_STATUS_CODE);
        context.assertEquals(response.statusMessage(), HttpResponseStatus.valueOf(EXISTING_HTTP_STATUS_CODE).reasonPhrase());
        async.complete();
    });
}
 
Example #28
Source File: WebWhoisActionHandlerTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Test
public void testAdvanced_redirect() {
  // Sets up EventLoopGroup with 1 thread to be blocking.
  EventLoopGroup group = new NioEventLoopGroup(1);

  // Sets up embedded channel.
  setup("", makeBootstrap(group), false);
  setupChannel(initialProtocol);

  // Initializes LocalAddress with unique String.
  LocalAddress address = new LocalAddress(TARGET_HOST);

  // stores future
  ChannelFuture future = actionHandler.getFinishedFuture();
  channel.writeOutbound(msg);

  // Path that we test WebWhoisActionHandler uses.
  String path = "/test";

  // Sets up the local server that the handler will be redirected to.
  TestServer.webWhoisServer(group, address, "", TARGET_HOST, path);

  FullHttpResponse response =
      new HttpResponseMessage(
          makeRedirectResponse(
              HttpResponseStatus.MOVED_PERMANENTLY, HTTP_REDIRECT + TARGET_HOST + path, true));

  // checks that future has not been set to successful or a failure
  assertThat(future.isDone()).isFalse();

  channel.writeInbound(response);

  // makes sure old channel is shut down when attempting redirection
  assertThat(channel.isActive()).isFalse();

  // assesses that we successfully received good response and protocol is unchanged
  assertThat(future.syncUninterruptibly().isSuccess()).isTrue();
}
 
Example #29
Source File: HttpTestServer.java    From crate with Apache License 2.0 5 votes vote down vote up
private void handleHttpRequest(ChannelHandlerContext ctx, HttpRequest msg) throws UnsupportedEncodingException {
    String uri = msg.uri();
    QueryStringDecoder decoder = new QueryStringDecoder(uri);
    logger.debug("Got Request for " + uri);
    HttpResponseStatus status = fail ? HttpResponseStatus.BAD_REQUEST : HttpResponseStatus.OK;

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        JsonGenerator generator = jsonFactory.createGenerator(out, JsonEncoding.UTF8);
        generator.writeStartObject();
        for (Map.Entry<String, List<String>> entry : decoder.parameters().entrySet()) {
            if (entry.getValue().size() == 1) {
                generator.writeStringField(entry.getKey(), URLDecoder.decode(entry.getValue().get(0), "UTF-8"));
            } else {
                generator.writeArrayFieldStart(entry.getKey());
                for (String value : entry.getValue()) {
                    generator.writeString(URLDecoder.decode(value, "UTF-8"));
                }
                generator.writeEndArray();
            }
        }
        generator.writeEndObject();
        generator.close();

    } catch (Exception ex) {
        status = HttpResponseStatus.INTERNAL_SERVER_ERROR;
    }
    ByteBuf byteBuf = Unpooled.wrappedBuffer(out.toByteArray());
    responses.add(out.toString(StandardCharsets.UTF_8.name()));

    DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, byteBuf);
    ChannelFuture future = ctx.channel().writeAndFlush(response);
    future.addListener(ChannelFutureListener.CLOSE);
}
 
Example #30
Source File: NettyHttpUtil.java    From netty-cookbook with Apache License 2.0 5 votes vote down vote up
public static FullHttpResponse theHttpContent(HttpOutputResource re, String contentType) {
	FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.OK , re.getByteBuf());
	response.headers().set(CONTENT_TYPE, contentType);
	response.headers().set(CONTENT_LENGTH, re.getLength());
	response.headers().set(CONNECTION, HEADER_CONNECTION_CLOSE);		
	//System.out.println("CONTENT_LENGTH:"+re.getLength());
	//System.out.println();
	return response;
}