+ * This will set the HTTP header {@link #HTTP_FAULT_INJECTOR_UPSTREAM_HOST_HEADER} to the request URL used by the + * HTTP request before re-writing and will update the request URL to use the HTTP fault injector. + * + * @param request The {@link HttpRequest} having its URL re-written. + * @param host The HTTP fault injector host. + * @param port The HTTP fault injector port. + * @return The updated {@link HttpRequest} with its URL re-written. + * @throws NullPointerException If {@code request} or {@code host} are null. + * @throws IllegalArgumentException If {@code host} is an empty string or {@code port} is + * an invalid port. + * @throws IllegalStateException If the request URL isn't valid or the HTTP fault injector URL isn't valid. + */ + public static HttpRequest rewriteUrlToUseFaultInjector(HttpRequest request, String host, int port) { + validateHostAndPort(host, port); + + try { + URI requestUri = request.getUrl().toURI(); + URI faultInjectorUri = new URI(requestUri.getScheme(), requestUri.getUserInfo(), host, + port, requestUri.getPath(), requestUri.getQuery(), requestUri.getFragment()); + + String xUpstreamHost = (requestUri.getPort() < 0) + ? requestUri.getHost() + : requestUri.getHost() + ":" + requestUri.getPort(); + + return request.setHeader(HTTP_FAULT_INJECTOR_UPSTREAM_HOST_HEADER, xUpstreamHost) + .setUrl(faultInjectorUri.toURL()); + } catch (Exception exception) { + throw new IllegalStateException(exception); + } + } + + /* + * Helper method for validating the HTTP fault injector host and port. + */ + static void validateHostAndPort(String host, int port) { + Objects.requireNonNull(host, "'host' cannot be null."); + + if (host.isEmpty()) { + throw new IllegalArgumentException("'host' must be a non-empty string."); + } + + if (port < 1 || port > 65535) { + throw new IllegalArgumentException("'port' must be a valid port number."); + } + } + + private Utils() { } +}