io.vertx.core.http.HttpHeaders Java Examples

The following examples show how to use io.vertx.core.http.HttpHeaders. 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: HttpContextTenantAndAuthIdProvider.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Get the tenant and auth-id from the <em>authorization</em> header of the given routing context request.
 *
 * @param ctx The execution context.
 * @param spanContext The OpenTracing context to use for tracking the operation (may be {@code null}).
 * @return A future indicating the outcome of the operation.
 *         <p>
 *         The future will fail if tenant and auth-id information could not be retrieved from the header
 *         or if there was an error obtaining the tenant object. In the latter case the future will be failed with a
 *         {@link org.eclipse.hono.client.ServiceInvocationException}.
 *         <p>
 *         Otherwise the future will contain the created <em>TenantObjectWithAuthId</em>.
 */
protected final Future<TenantObjectWithAuthId> getFromAuthHeader(final RoutingContext ctx,
        final SpanContext spanContext) {
    final String authorizationHeader = ctx.request().headers().get(HttpHeaders.AUTHORIZATION);
    if (authorizationHeader == null) {
        return Future.failedFuture("no auth header found");
    }
    String userName = null;
    try {
        final int idx = authorizationHeader.indexOf(' ');
        if (idx > 0 && "Basic".equalsIgnoreCase(authorizationHeader.substring(0, idx))) {
            final String authorization = authorizationHeader.substring(idx + 1);
            final String decoded = new String(Base64.getDecoder().decode(authorization));
            final int colonIdx = decoded.indexOf(":");
            userName = colonIdx != -1 ? decoded.substring(0, colonIdx) : decoded;
        }
    } catch (final RuntimeException e) {
        LOG.debug("error parsing auth header: {}", e.getMessage());
    }
    if (userName == null) {
        return Future.failedFuture("unsupported auth header value");
    }
    return getFromUserName(userName, spanContext);
}
 
Example #2
Source File: HtmlFileTransport.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Override
public void sendFrame(String body, Handler<AsyncResult<Void>> handler) {
  if (log.isTraceEnabled()) log.trace("HtmlFile, sending frame");
  if (!headersWritten) {
    String htmlFile = HTML_FILE_TEMPLATE.replace("{{ callback }}", callback);
    rc.response().putHeader(HttpHeaders.CONTENT_TYPE, "text/html; charset=UTF-8");
    setNoCacheHeaders(rc);
    rc.response().setChunked(true);
    setJSESSIONID(options, rc);
    rc.response().write(htmlFile);
    headersWritten = true;
  }
  body = escapeForJavaScript(body);
  String sb = "<script>\np(\"" +
    body +
    "\");\n</script>\r\n";
  Buffer buff = buffer(sb);
  rc.response().write(buff, handler);
  bytesSent += buff.length();
  if (bytesSent >= maxBytesStreaming) {
    if (log.isTraceEnabled()) log.trace("More than maxBytes sent so closing connection");
    // Reset and close the connection
    close();
  }
}
 
Example #3
Source File: RestClientRequestImpl.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
private void genBodyBuffer() throws Exception {
  if (bodyBuffer != null) {
    return;
  }

  if (formMap == null) {
    return;
  }

  request.putHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED);
  try (BufferOutputStream output = new BufferOutputStream()) {
    for (Entry<String, Object> entry : formMap.entrySet()) {
      output.write(entry.getKey().getBytes(StandardCharsets.UTF_8));
      output.write('=');
      if (entry.getValue() != null) {
        String value = RestObjectMapperFactory.getRestObjectMapper().convertToString(entry.getValue());
        value = URLEncoder.encode(value, StandardCharsets.UTF_8.name());
        output.write(value.getBytes(StandardCharsets.UTF_8));
      }
      output.write('&');
    }
    bodyBuffer = output.getBuffer();
  }
}
 
Example #4
Source File: SessionAwareInterceptor.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
private void prepareRedirectRequest(HttpContext<?> context) {
  // Now the context contains the redirect request in clientRequest() and the original request in request()
  HttpClientRequest redirectRequest = context.clientRequest();
  HttpRequestImpl<?> originalRequest = (HttpRequestImpl<?>) context.request();
  WebClientSessionAware webclient = (WebClientSessionAware) originalRequest.client;

  MultiMap headers = context.get(HEADERS_CONTEXT_KEY);
  if (headers == null) {
    headers = HttpHeaders.headers().addAll(redirectRequest.headers());
    context.set(SessionAwareInterceptor.HEADERS_CONTEXT_KEY, headers);
  }

  String redirectHost = URI.create(redirectRequest.absoluteURI()).getHost();
  String domain;
  if (redirectHost.equals(originalRequest.host()) && originalRequest.virtualHost != null) {
    domain = originalRequest.virtualHost;
  } else {
    domain = redirectHost;
  }

  Iterable<Cookie> cookies = webclient.cookieStore().get(originalRequest.ssl, domain, redirectRequest.path());
  for (Cookie c : cookies) {
    redirectRequest.headers().add("cookie", ClientCookieEncoder.STRICT.encode(c));
  }
}
 
Example #5
Source File: CorsIT.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the HTTP adapter returns matching CORS headers in response to a
 * CORS preflight request for posting a command response.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testCorsPreflightRequestForPostingCommandResponse(final VertxTestContext ctx) {

    httpClient.options(
            String.format("/%s/res/%s", CommandConstants.COMMAND_ENDPOINT, "cmd-request-id"),
            MultiMap.caseInsensitiveMultiMap()
                .add(HttpHeaders.ORIGIN, CrudHttpClient.ORIGIN_URI)
                .add(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.POST.name()),
            status -> status == HttpURLConnection.HTTP_OK)
    .onComplete(ctx.succeeding(headers -> {
        ctx.verify(() -> {
            assertAccessControlHeaders(headers, HttpMethod.POST);
            assertThat(headers.get(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS)).contains(Constants.HEADER_COMMAND_RESPONSE_STATUS);
        });
        ctx.completeNow();
    }));
}
 
Example #6
Source File: HealthApi.java    From xyz-hub with Apache License 2.0 6 votes vote down vote up
private static void onHealthStatus(final RoutingContext context) {
  try {
    Response r = healthCheck.getResponse();
    r.setEndpoint(NODE_HEALTHCHECK_ENDPOINT);
    r.setNode(Node.OWN_INSTANCE.id);

    String secretHeaderValue = context.request().getHeader(Config.getHealthCheckHeaderName());

    //Always respond with 200 for public HC requests for now
    int statusCode = r.isPublicRequest(secretHeaderValue) ?
        OK.code() : r.getStatus().getSuggestedHTTPStatusCode();
    String responseString = r.toResponseString(secretHeaderValue);

    context.response().setStatusCode(statusCode)
        .putHeader(HttpHeaders.CONTENT_TYPE, APPLICATION_JSON)
        .end(responseString);
  }
  catch (Exception e) {
    logger.error(Context.getMarker(context), "Error while doing the health-check: ", e);
    context.response().setStatusCode(OK.code())
        .putHeader(HttpHeaders.CONTENT_TYPE, APPLICATION_JSON)
        .end(new JsonObject().put("status", new JsonObject().put("result", "WARNING")).encode());
  }
}
 
Example #7
Source File: HttpResponseWriter.java    From rest.vertx with Apache License 2.0 6 votes vote down vote up
default Map<String, String> join(Map<String, String> original, MediaType contentMediaType, MediaType[] additional) {
	if (contentMediaType == null) {
		contentMediaType = MediaType.WILDCARD_TYPE;
	}

	MediaType first = null; // to be used in case no content type matches requested content type
	if (additional != null && additional.length > 0) {

		for (MediaType produces : additional) {
			if (first == null) {
				first = produces;
			}

			if (MediaTypeHelper.matches(contentMediaType, produces)) {
				original.put(HttpHeaders.CONTENT_TYPE.toString(), MediaTypeHelper.toString(produces));
				break;
			}
		}
	}

	if (original.get(HttpHeaders.CONTENT_TYPE.toString()) == null && first != null) {
		original.put(HttpHeaders.CONTENT_TYPE.toString(), MediaTypeHelper.toString(first));
	}

	return original;
}
 
Example #8
Source File: DeviceRegistryHttpClient.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Updates credentials of a specific type for a device.
 *
 * @param tenantId The tenant that the device belongs to.
 * @param deviceId The identifier of the device.
 * @param credentialsSpec The JSON array to be sent in the request body.
 * @param version The version of credentials to be sent as request header.
 * @param expectedStatusCode The status code indicating a successful outcome.
 * @return A future indicating the outcome of the operation.
 *         The future will succeed if the response contains the expected status code.
 *         Otherwise the future will fail with a {@link org.eclipse.hono.client.ServiceInvocationException}.
 * @throws NullPointerException if the tenant is {@code null}.
 */
public Future<MultiMap> updateCredentialsWithVersion(
        final String tenantId,
        final String deviceId,
        final Collection<CommonCredential> credentialsSpec,
        final String version,
        final int expectedStatusCode) {

    Objects.requireNonNull(tenantId);
    final String uri = credentialsByDeviceUri(tenantId, deviceId);

    final MultiMap headers = MultiMap.caseInsensitiveMultiMap()
            .add(HttpHeaders.IF_MATCH, version)
            .add(HttpHeaders.CONTENT_TYPE, HttpUtils.CONTENT_TYPE_JSON);

    // encode array not list, workaround for vert.x issue
    final var payload = Json.encodeToBuffer(credentialsSpec.toArray(CommonCredential[]::new));

    return httpClient.update(uri, payload, headers, status -> status == expectedStatusCode, true);
}
 
Example #9
Source File: CORSFilter.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private void processRequestedHeaders(HttpServerResponse response, String allowHeadersValue) {
    if (!corsConfig.headers.isPresent()) {
        response.headers().set(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, allowHeadersValue);
    } else {
        List<String> requestedHeaders = new ArrayList<>();
        for (String requestedHeader : COMMA_SEPARATED_SPLIT_REGEX.split(allowHeadersValue)) {
            requestedHeaders.add(requestedHeader.toLowerCase());
        }

        List<String> validRequestedHeaders = new ArrayList<>();
        for (String configHeader : corsConfig.headers.get()) {
            if (requestedHeaders.contains(configHeader.toLowerCase())) {
                validRequestedHeaders.add(configHeader);
            }
        }

        if (!validRequestedHeaders.isEmpty()) {
            response.headers().set(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, String.join(",", validRequestedHeaders));
        }
    }
}
 
Example #10
Source File: HttpRequestImpl.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
HttpRequestImpl(WebClientInternal client, HttpMethod method, SocketAddress serverAddress, String protocol, Boolean ssl, Integer port, String host, String
        uri, BodyCodec<T> codec, WebClientOptions options) {
  this.client = client;
  this.method = method;
  this.protocol = protocol;
  this.codec = codec;
  this.port = port;
  this.host = host;
  this.uri = uri;
  this.ssl = ssl;
  this.serverAddress = serverAddress;
  this.followRedirects = options.isFollowRedirects();
  this.options = options;
  if (options.isUserAgentEnabled()) {
    headers = HttpHeaders.set(HttpHeaders.USER_AGENT, options.getUserAgent());
  }
}
 
Example #11
Source File: FormParameterExtractorTest.java    From vertx-swagger with Apache License 2.0 6 votes vote down vote up
@Test()
public void testOkFormDataSimpleRequiredAllowEmpty(TestContext context) {
    Async async = context.async();
    HttpClientRequest req = httpClient.post(TEST_PORT, TEST_HOST, "/formdata/simple/required/allowempty");
    req.handler(response -> {
        response.bodyHandler(body -> {
            context.assertEquals(response.statusCode(), 200);
            context.assertEquals("", body.toString());
            async.complete();
        });
    });
    // Construct form
    StringBuffer payload = new StringBuffer().append("formDataRequired=");
    req.putHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
    req.end(payload.toString());
}
 
Example #12
Source File: JsonBodyProcessorImplTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Test
public void testInvalidJsonArray(VertxTestContext testContext) {
  when(mockerServerRequest.getHeader(HttpHeaders.CONTENT_TYPE)).thenReturn("application/json");
  when(mockedContext.request()).thenReturn(mockerServerRequest);
  when(mockedContext.getBody()).thenReturn(TestSchemas.INVALID_ARRAY.toBuffer());

  BodyProcessor processor = Bodies.json(TestSchemas.SAMPLE_ARRAY_SCHEMA_BUILDER).create(parser);

  processor.process(mockedContext).onComplete(testContext.failing(err -> {
    testContext.verify(() -> {
      assertThat(err)
        .isInstanceOf(BodyProcessorException.class)
        .hasFieldOrPropertyWithValue("actualContentType", "application/json")
        .hasCauseInstanceOf(ValidationException.class);
    });
    testContext.completeNow();
  }));
}
 
Example #13
Source File: DefaultRestClientRequest.java    From vertx-rest-client with Apache License 2.0 6 votes vote down vote up
private void populateAcceptHeaderIfNotPresent() {
    final String acceptHeader = httpClientRequest.headers().get(HttpHeaders.ACCEPT);
    if (Strings.isNullOrEmpty(acceptHeader)) {
        httpClientRequest.headers().set(
                HttpHeaders.ACCEPT,
                formatForAcceptHeader(
                        httpMessageConverters
                                .stream()
                                .map(HttpMessageConverter::getSupportedMediaTypes)
                                .reduce(new LinkedList<>(), (a, b) -> {
                                            a.addAll(b);
                                            return a;
                                        }
                                )
                )
        );
    }
}
 
Example #14
Source File: OpenAPI3ValidationTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Test
public void testEmptyParametersNotNull() throws Exception {
  Operation op = testSpec.getPaths().get("/pets").getPost();
  OpenAPI3RequestValidationHandler validationHandler = new OpenAPI3RequestValidationHandlerImpl(op, op.getParameters(), testSpec, refsCache);
  loadHandlers("/pets", HttpMethod.POST, true, validationHandler, (routingContext) -> {
    RequestParameters params = routingContext.get("parsedParameters");
    assertEquals(0, params.cookieParametersNames().size()); //Here it should not throw exception (issue #850)
    assertEquals(0, params.pathParametersNames().size());
    assertEquals(0, params.queryParametersNames().size());
    assertEquals(0, params.headerParametersNames().size());
    assertEquals(0, params.formParametersNames().size());
    routingContext
      .response()
      .setStatusCode(200)
      .setStatusMessage("OK")
      .putHeader(HttpHeaders.CONTENT_TYPE, "application/json")
      .end();
  });

  testRequestWithJSON(HttpMethod.POST, "/pets", new JsonObject().put("id", 1).put("name", "Willy").toBuffer(),200, "OK");
}
 
Example #15
Source File: Api.java    From xyz-hub with Apache License 2.0 6 votes vote down vote up
/**
 * Internally used to send a "Not Modified" response when appropriate. In any case this method will set the e-tag header, if the task
 * response has generated an e-tag.
 *
 * @param task the task for which to generate the "Not Modified" response.
 * @return true if a response has been send; false if not.
 */
private boolean sendNotModifiedResponseIfNoneMatch(final Task task) {
  //If the task has an ETag, set it in the HTTP header.
  //Set the ETag header
  if (task.getEtag() != null) {
    final RoutingContext context = task.context;
    final HttpServerResponse httpResponse = context.response();
    final MultiMap httpHeaders = httpResponse.headers();

    httpHeaders.add(HttpHeaders.ETAG, task.getEtag());

    //If the ETag didn't change, return "Not Modified"
    if (task.etagMatches()) {
      sendResponse(task, NOT_MODIFIED, null, null);
      return true;
    }
  }

  return false;
}
 
Example #16
Source File: BearerAuthenticationMechanism.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private String extractBearerToken(RoutingContext context) {
    final HttpServerRequest request = context.request();
    final String authorization = request.headers().get(HttpHeaders.AUTHORIZATION);

    if (authorization == null) {
        return null;
    }

    int idx = authorization.indexOf(' ');

    if (idx <= 0 || !BEARER.equalsIgnoreCase(authorization.substring(0, idx))) {
        return null;
    }

    return authorization.substring(idx + 1);
}
 
Example #17
Source File: AbstractEventBusHttpEndpoint.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Sends a request message to an address via the vert.x event bus for further processing.
 * <p>
 * The address is determined by invoking {@link #getEventBusAddress()}.
 *
 * @param ctx The routing context of the request.
 * @param requestMsg The JSON object to send via the event bus.
 * @param responseHandler The handler to be invoked for the message received in response to the request.
 *                        <p>
 *                        The handler will be invoked with the <em>status code</em> retrieved from the
 *                        {@link org.eclipse.hono.util.MessageHelper#APP_PROPERTY_STATUS} field and the <em>payload</em>
 *                        retrieved from the {@link org.eclipse.hono.util.RequestResponseApiConstants#FIELD_PAYLOAD} field.
 * @throws NullPointerException If the routing context is {@code null}.
 */
protected final void sendAction(final RoutingContext ctx, final JsonObject requestMsg,
        final BiConsumer<Integer, EventBusMessage> responseHandler) {

    final DeliveryOptions options = createEventBusMessageDeliveryOptions(config.getSendTimeOut(),
            TracingHandler.serverSpanContext(ctx));
    vertx.eventBus().request(getEventBusAddress(), requestMsg, options, invocation -> {
        if (invocation.failed()) {
            HttpUtils.serviceUnavailable(ctx, 2);
        } else {
            final EventBusMessage response = EventBusMessage.fromJson((JsonObject) invocation.result().body());

            final Integer status = response.getStatus();

            final String version = response.getResourceVersion();
            if (! Strings.isNullOrEmpty(version)) {
                ctx.response().putHeader(HttpHeaders.ETAG, version);
            }

            responseHandler.accept(status, response);
        }
    });
}
 
Example #18
Source File: GraphiQLHandlerImpl.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(RoutingContext rc) {
  if (!options.isEnabled()) {
    rc.next();
    return;
  }
  String filename = Utils.pathOffset(rc.normalizedPath(), rc);
  if (filename.isEmpty()) {
    rc.response().setStatusCode(301).putHeader(HttpHeaders.LOCATION, rc.currentRoute().getPath()).end();
    return;
  }
  if ("/".equals(filename) || "/index.html".equals(filename)) {
    String resource = rc.vertx().fileSystem()
      .readFileBlocking(WEBROOT + "/index.html")
      .toString(UTF_8)
      .replace("__VERTX_GRAPHIQL_CONFIG__", replacement(rc));
    rc.response()
      .putHeader(HttpHeaders.CACHE_CONTROL, "no-cache")
      .putHeader(HttpHeaders.CONTENT_TYPE, "text/html;charset=utf8")
      .end(resource);
  } else {
    staticHandler.handle(rc);
  }
}
 
Example #19
Source File: XhrTransport.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
private void handleSendMessage(RoutingContext rc, SockJSSession session, Buffer body) {
  String msgs = body.toString();
  if (msgs.equals("")) {
    rc.response().setStatusCode(500);
    rc.response().end("Payload expected.");
    return;
  }
  if (!session.handleMessages(msgs)) {
    sendInvalidJSON(rc.response());
  } else {
    rc.response().putHeader(HttpHeaders.CONTENT_TYPE, "text/plain; charset=UTF-8");
    setNoCacheHeaders(rc);
    setJSESSIONID(options, rc);
    setCORS(rc);
    rc.response().setStatusCode(204);
    rc.response().end();
  }
  if (log.isTraceEnabled()) log.trace("XHR send processed ok");
}
 
Example #20
Source File: HystrixMetricEventStream.java    From vertx-circuit-breaker with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(RoutingContext rc) {
  HttpServerResponse response = rc.response();
  response
    .setChunked(true)
    .putHeader(HttpHeaders.CONTENT_TYPE, "text/event-stream")
    .putHeader(HttpHeaders.CACHE_CONTROL, "no-cache")
    .putHeader(HttpHeaders.CONNECTION, HttpHeaders.KEEP_ALIVE);

  rc.request().connection()
    .closeHandler(v -> {
      connections.remove(response);
      endQuietly(response);
    })
    .exceptionHandler(t -> {
      connections.remove(response);
      rc.fail(t);
    });

  connections.add(response);
}
 
Example #21
Source File: CorsIT.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the HTTP adapter returns matching CORS headers in response to a
 * CORS preflight request for putting a command response.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testCorsPreflightRequestForPuttingCommandResponse(final VertxTestContext ctx) {

    httpClient.options(
            String.format("/%s/res/%s/%s/%s", CommandConstants.COMMAND_ENDPOINT, "my-tenant", "my-device", "cmd-request-id"),
            MultiMap.caseInsensitiveMultiMap()
                .add(HttpHeaders.ORIGIN, CrudHttpClient.ORIGIN_URI)
                .add(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.PUT.name()),
            status -> status == HttpURLConnection.HTTP_OK)
    .onComplete(ctx.succeeding(headers -> {
        ctx.verify(() -> {
            assertAccessControlHeaders(headers, HttpMethod.PUT);
            assertThat(headers.get(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS)).contains(Constants.HEADER_COMMAND_RESPONSE_STATUS);
        });
        ctx.completeNow();
    }));
}
 
Example #22
Source File: CorsIT.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the HTTP adapter returns matching CORS headers in response to a
 * CORS preflight request for putting an event.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testCorsPreflightRequestForPuttingEvents(final VertxTestContext ctx) {

    httpClient.options(
            String.format("/%s/%s/%s", EventConstants.EVENT_ENDPOINT, "my-tenant", "my-device"),
            MultiMap.caseInsensitiveMultiMap()
                .add(HttpHeaders.ORIGIN, CrudHttpClient.ORIGIN_URI)
                .add(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.PUT.name()),
            status -> status == HttpURLConnection.HTTP_OK)
    .onComplete(ctx.succeeding(headers -> {
        ctx.verify(() -> {
            assertAccessControlHeaders(headers, HttpMethod.PUT);
            assertThat(headers.get(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS))
                    .contains(Constants.HEADER_TIME_TILL_DISCONNECT);
        });
        ctx.completeNow();
    }));
}
 
Example #23
Source File: ErrorHandlerTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
private void checkHtmlResponse(Buffer buff, HttpClientResponse resp, int statusCode, String statusMessage,
                               Exception e, boolean displayExceptionDetails) {
  assertEquals("text/html", resp.headers().get(HttpHeaders.CONTENT_TYPE));
  String page = buff.toString();
  assertTrue(page.startsWith("<html>"));
  assertTrue(page.contains(String.valueOf(statusCode)));
  assertTrue(page.contains(statusMessage));
  assertTrue(page.contains("An unexpected error occurred"));
  if (e != null) {
    if (displayExceptionDetails) {
      assertTrue(page.contains(e.getStackTrace()[0].toString()));
    } else {
      assertFalse(page.contains(e.getStackTrace()[0].toString()));
    }
  }
}
 
Example #24
Source File: VertxBasedHttpProtocolAdapterTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that a POST request to the telemetry URI results in a message that is sent downstream.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testPostTelemetrySendsMessageDownstream(final VertxTestContext ctx) {

    mockSuccessfulAuthentication("DEFAULT_TENANT", "device_1");

    httpClient.post("/telemetry")
            .putHeader(HttpHeaders.CONTENT_TYPE.toString(), HttpUtils.CONTENT_TYPE_JSON)
            .basicAuthentication("testuser@DEFAULT_TENANT", "password123")
            .putHeader(HttpHeaders.ORIGIN.toString(), "hono.eclipse.org")
            .expect(ResponsePredicate.status(HttpURLConnection.HTTP_ACCEPTED))
            .expect(this::assertCorsHeaders)
            .sendJsonObject(new JsonObject(), ctx.succeeding(r -> {
                ctx.verify(() -> verify(telemetrySender).send(any(Message.class), any(SpanContext.class)));
                ctx.completeNow();
            }));
}
 
Example #25
Source File: AbstractHttpMessageConverter.java    From vertx-rest-client with Apache License 2.0 6 votes vote down vote up
@Override
public void write(T object, MediaType contentType, HttpOutputMessage httpOutputMessage) throws HttpMessageConverterException {
    try {
        final MultiMap headers = httpOutputMessage.getHeaders();
        if (headers.get(HttpHeaders.CONTENT_TYPE) == null) {
            MediaType contentTypeToUse = contentType;
            if (contentType == null || contentType.isWildcardType() || contentType.isWildcardSubtype()) {
                contentTypeToUse = getDefaultContentType(object);
            }
            if (contentTypeToUse != null) {
                headers.set(HttpHeaders.CONTENT_TYPE, contentTypeToUse.toString());
            }
        }

        writeInternal(object, httpOutputMessage);
    } catch (HttpMessageConverterException e) {
        throw e;
    } catch (Throwable t) {
        throw new HttpMessageConverterException("Error writing object", t);
    }
}
 
Example #26
Source File: BrokenConsul.java    From vertx-consul-client with Apache License 2.0 5 votes vote down vote up
BrokenHttpServer(Vertx vertx) {
  super(vertx, h -> {
    HttpServerResponse resp = h.response();
    resp.putHeader(HttpHeaders.CONTENT_LENGTH, "10000").write("start and ... ");
    resp.close();
  });
}
 
Example #27
Source File: ServiceRequest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
public ServiceRequest(JsonObject json) {
  init();
  ServiceRequestConverter.fromJson(json, this);
  JsonObject hdrs = json.getJsonObject("headers", null);
  if (hdrs != null) {
    headers = HttpHeaders.headers();
    for (Map.Entry<String, Object> entry: hdrs) {
      if (!(entry.getValue() instanceof String)) {
        throw new IllegalStateException("Invalid type for message header value " + entry.getValue().getClass());
      }
      headers.set(entry.getKey(), (String)entry.getValue());
    }
  }
}
 
Example #28
Source File: SockJSHandlerImpl.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
private Handler<RoutingContext> createIFrameHandler(String iframeHTML) {
  String etag = getMD5String(iframeHTML);
  return rc -> {
    try {
      if (log.isTraceEnabled()) log.trace("In Iframe handler");
      if (etag != null && etag.equals(rc.request().getHeader("if-none-match"))) {
        rc.response().setStatusCode(304);
        rc.response().end();
      } else {
        long oneYear = 365 * 24 * 60 * 60 * 1000L;
        String expires = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz").format(new Date(System.currentTimeMillis() + oneYear));
        rc.response()
          .putHeader(HttpHeaders.CONTENT_TYPE, "text/html; charset=UTF-8")
          .putHeader(HttpHeaders.CACHE_CONTROL, "public,max-age=31536000")
          .putHeader(HttpHeaders.EXPIRES, expires)
          .putHeader(HttpHeaders.ETAG, etag)
          .end(iframeHTML);
      }
    } catch (Exception e) {
      log.error("Failed to server iframe", e);
    }
  };
}
 
Example #29
Source File: HttpResponseWriter.java    From rest.vertx with Apache License 2.0 5 votes vote down vote up
default Map<String, String> join(Map<String, String> original, Map<String, String> additional) {
	if (additional != null && additional.size() > 0) {
		original.putAll(additional);
	}

	original.remove(HttpHeaders.CONTENT_TYPE.toString()); // remove content-type headers from output
	return original;
}
 
Example #30
Source File: UnauthenticatedNexusProxyVerticleTests.java    From nexus-proxy with Apache License 2.0 5 votes vote down vote up
@Test
public void root_responds_with_200_to_allowed_user_agents(final TestContext ctx) {
    final Async async = ctx.async();

    vertx.createHttpClient().get(PORT, HOST, "/", res -> {
        assertEquals(200, res.statusCode());
        assertEquals("0", res.headers().get(HttpHeaders.CONTENT_LENGTH));
        async.complete();
    }).putHeader(HttpHeaders.USER_AGENT, "GoogleHC/1.0").end();
}