/** * Creates a CompletionStage for the passed {@link HttpRequest} containing the {@link HttpResponse}. * * @return the HttpResponse CompletionStage. */ public CompletionStage<HttpResponse> createSingleHttpRequest(final HttpRequest request) { return Http.get(actorSystem).singleRequest( request, Http.get(actorSystem).defaultClientHttpsContext(), connectionPoolSettings, actorSystem.log(), actorMaterializer ); }
private void logServerBinding(final ServerBinding serverBinding) { log.info("Bound to address {}:{}", serverBinding.localAddress().getHostString(), serverBinding.localAddress().getPort()); }
private HttpClientFacade(final ActorSystem actorSystem, final boolean proxyEnabled, final String proxyHost, final Integer proxyPort, final String proxyUsername, final String proxyPassword) { this.actorSystem = actorSystem; if (proxyEnabled) { final ClientTransport proxyClientTransport; if (proxyHost != null && proxyPort != null && proxyUsername != null && proxyPassword != null) { proxyClientTransport = ClientTransport.httpsProxy( InetSocketAddress.createUnresolved(proxyHost, proxyPort), HttpCredentials.create(proxyUsername, proxyPassword) ); } else if (proxyHost != null && proxyPort != null) { proxyClientTransport = ClientTransport.httpsProxy( InetSocketAddress.createUnresolved(proxyHost, proxyPort) ); } else { throw new IllegalArgumentException("When HTTP proxy is enabled via config '" + ConfigKeys.AUTHENTICATION_HTTP_PROXY_ENABLED + "' at least proxy host and port must be configured as well"); } connectionPoolSettings = ConnectionPoolSettings.create(actorSystem).withTransport(proxyClientTransport); } else { connectionPoolSettings = ConnectionPoolSettings.create(actorSystem); } actorMaterializer = ActorMaterializer.create(actorSystem); }
public void startHttpServer() throws Exception { final Http http = Http.get(system); final ActorMaterializer materializer = ActorMaterializer.create(system); ActorRef userRegistryActor = system.actorOf(ServiceRegistryActor.props(), "serviceRegistryActor"); ServiceRoutes serviceRoutes = new ServiceRoutes(system, userRegistryActor); final Flow<HttpRequest, HttpResponse, NotUsed> routeFlow = serviceRoutes.routes().flow(system, materializer); final CompletionStage<ServerBinding> binding = http.bindAndHandle(routeFlow, ConnectHttp.toHost("localhost", 8096), materializer); System.out.println("Server online at http://localhost:8096/"); System.in.read(); // let it run until user presses return }
.get(theSystem) .bindAndHandle(routes().flow(theSystem, materializer), ConnectHttp.toHost(host, port), settings, theSystem.log(), postHttpBindingFailure(exception); } else { postHttpBinding(binding); .thenCompose(ignore -> waitForShutdownSignal(theSystem)) // chaining both futures to fail fast .toCompletableFuture() postServerShutdown(Optional.ofNullable(exception), theSystem); if (!system.isPresent()) {
logRequest("request", Logging.InfoLevel(), () -> path(segment("products").slash(longSegment()), (productId) -> get(() -> onComplete(lookupProduct(productId), (Try<DbActor.ProductResult> result) -> { if (result.isFailure()) { return complete(StatusCodes.SERVICE_UNAVAILABLE); } else { final DbActor.ProductResult productResult = result.get(); if (productResult.product.isPresent()) { return completeOK(productResult.product.get(), productMarshaller); } else { return complete(StatusCodes.NOT_FOUND); bindingCompletionStage = Http.get(context().system()) .bindAndHandle( route.flow(context().system(), materializer), ConnectHttp.toHost(host, port), materializer);
public static void main(String[] args) throws Exception { ActorSystem system = ActorSystem.create(); try { final Materializer materializer = ActorMaterializer.create(system); final Function<HttpRequest, HttpResponse> handler = request -> handleRequest(request); CompletionStage<ServerBinding> serverBindingFuture = Http.get(system).bindAndHandleSync( handler, ConnectHttp.toHost("localhost", 8080), materializer); // will throw if binding fails serverBindingFuture.toCompletableFuture().get(1, TimeUnit.SECONDS); System.out.println("Press ENTER to stop."); new BufferedReader(new InputStreamReader(System.in)).readLine(); } finally { system.terminate(); } }
/** * Starts Prometheus HTTP endpoint on which Prometheus may scrape the data. */ private void startKamonPrometheusHttpEndpoint(final ActorSystem actorSystem) { if (configReader.metrics().isPrometheusEnabled() && prometheusReporter != null) { final ActorMaterializer materializer = createActorMaterializer(actorSystem); final Route prometheusReporterRoute = PrometheusReporterRoute .buildPrometheusReporterRoute(prometheusReporter); final CompletionStage<ServerBinding> binding = Http.get(actorSystem) .bindAndHandle(prometheusReporterRoute.flow(actorSystem, materializer), ConnectHttp.toHost(configReader.metrics().getPrometheusHostname(), configReader.metrics().getPrometheusPort()), materializer); binding.thenAccept(theBinding -> CoordinatedShutdown.get(actorSystem).addTask( CoordinatedShutdown.PhaseServiceUnbind(), "shutdown_prometheus_http_endpoint", () -> { logger.info("Gracefully shutting down Prometheus HTTP endpoint.."); // prometheus requests don't get the luxury of being processed a long time after shutdown: return theBinding.terminate(Duration.ofSeconds(1)) .handle((httpTerminated, e) -> Done.getInstance()); }) ).exceptionally(failure -> { logger.error("Kamon Prometheus HTTP endpoint could not be started: {}", failure.getMessage(), failure); logger.error("Terminating actorSystem!"); actorSystem.terminate(); return null; }); } }
.get(theSystem) .bindAndHandle(routes().flow(theSystem, materializer), ConnectHttp.toHost(host, port), settings, theSystem.log(), postHttpBindingFailure(exception); } else { postHttpBinding(binding); .thenCompose(ignore -> waitForShutdownSignal(theSystem)) // chaining both futures to fail fast .toCompletableFuture() postServerShutdown(Optional.ofNullable(exception), theSystem); if (!system.isPresent()) {
/** * Creates a CompletionStage for the passed {@link HttpRequest} containing the {@link HttpResponse}. * * @return the HttpResponse CompletionStage. */ public CompletionStage<HttpResponse> createSingleHttpRequest(final HttpRequest request) { return Http.get(actorSystem).singleRequest( request, Http.get(actorSystem).defaultClientHttpsContext(), connectionPoolSettings, actorSystem.log(), actorMaterializer ); }
private void logServerBinding(final ServerBinding serverBinding) { log.info("Bound to address {}:{}", serverBinding.localAddress().getHostString(), serverBinding.localAddress().getPort()); }
private HttpClientFacade(final ActorSystem actorSystem, final boolean proxyEnabled, final String proxyHost, final Integer proxyPort, final String proxyUsername, final String proxyPassword) { this.actorSystem = actorSystem; if (proxyEnabled) { final ClientTransport proxyClientTransport; if (proxyHost != null && proxyPort != null && proxyUsername != null && proxyPassword != null) { proxyClientTransport = ClientTransport.httpsProxy( InetSocketAddress.createUnresolved(proxyHost, proxyPort), HttpCredentials.create(proxyUsername, proxyPassword) ); } else if (proxyHost != null && proxyPort != null) { proxyClientTransport = ClientTransport.httpsProxy( InetSocketAddress.createUnresolved(proxyHost, proxyPort) ); } else { throw new IllegalArgumentException("When HTTP proxy is enabled via config '" + ConfigKeys.AUTHENTICATION_HTTP_PROXY_ENABLED + "' at least proxy host and port must be configured as well"); } connectionPoolSettings = ConnectionPoolSettings.create(actorSystem).withTransport(proxyClientTransport); } else { connectionPoolSettings = ConnectionPoolSettings.create(actorSystem); } actorMaterializer = ActorMaterializer.create(actorSystem); }
/** * Starts Prometheus HTTP endpoint on which Prometheus may scrape the data. */ private void startKamonPrometheusHttpEndpoint(final ActorSystem actorSystem) { if (configReader.metrics().isPrometheusEnabled() && prometheusReporter != null) { final ActorMaterializer materializer = createActorMaterializer(actorSystem); final Route prometheusReporterRoute = PrometheusReporterRoute .buildPrometheusReporterRoute(prometheusReporter); final CompletionStage<ServerBinding> binding = Http.get(actorSystem) .bindAndHandle(prometheusReporterRoute.flow(actorSystem, materializer), ConnectHttp.toHost(configReader.metrics().getPrometheusHostname(), configReader.metrics().getPrometheusPort()), materializer); binding.thenAccept(theBinding -> CoordinatedShutdown.get(actorSystem).addTask( CoordinatedShutdown.PhaseServiceUnbind(), "shutdown_prometheus_http_endpoint", () -> { logger.info("Gracefully shutting down Prometheus HTTP endpoint.."); // prometheus requests don't get the luxury of being processed a long time after shutdown: return theBinding.terminate(Duration.ofSeconds(1)) .handle((httpTerminated, e) -> Done.getInstance()); }) ).exceptionally(failure -> { logger.error("Kamon Prometheus HTTP endpoint could not be started: {}", failure.getMessage(), failure); logger.error("Terminating actorSystem!"); actorSystem.terminate(); return null; }); } }
.get(theSystem) .bindAndHandle(routes().flow(theSystem, materializer), ConnectHttp.toHost(host, port), settings, theSystem.log(), postHttpBindingFailure(exception); } else { postHttpBinding(binding); .thenCompose(ignore -> waitForShutdownSignal(theSystem)) // chaining both futures to fail fast .toCompletableFuture() postServerShutdown(Optional.ofNullable(exception), theSystem); if (!system.isPresent()) {
/** * Hook that will be called just after the Http server binding is done. Override this method if you want to perform some actions after the server is up. */ protected void postHttpBinding (ServerBinding binding) { systemReference.get().log().info("Server online at http://" + binding.localAddress().getHostName() + ":" + binding.localAddress().getPort() + "/"); }
private void bindHttpStatusRoute(final ActorRef healthCheckingActor, final HttpConfigReader httpConfig, final ActorMaterializer materializer) { String hostname = httpConfig.getHostname(); if (hostname.isEmpty()) { hostname = ConfigUtil.getLocalHostAddress(); log.info("No explicit hostname configured, using HTTP hostname: {}", hostname); } final CompletionStage<ServerBinding> binding = Http.get(getContext().system()) .bindAndHandle(createRoute(getContext().system(), healthCheckingActor).flow(getContext().system(), materializer), ConnectHttp.toHost(hostname, httpConfig.getPort()), materializer); binding.thenAccept(theBinding -> CoordinatedShutdown.get(getContext().getSystem()).addTask( CoordinatedShutdown.PhaseServiceUnbind(), "shutdown_health_http_endpoint", () -> { log.info("Gracefully shutting down status/health HTTP endpoint.."); return theBinding.terminate(Duration.ofSeconds(1)) .handle((httpTerminated, e) -> Done.getInstance()); }) ).exceptionally(failure -> { log.error(failure, "Something very bad happened: {}", failure.getMessage()); getContext().system().terminate(); return null; }); }
/** * Hook that will be called just after the Http server binding is done. Override this method if you want to perform some actions after the server is up. */ protected void postHttpBinding (ServerBinding binding) { systemReference.get().log().info("Server online at http://" + binding.localAddress().getHostName() + ":" + binding.localAddress().getPort() + "/"); }
private void createHealthCheckingActorHttpBinding(final HttpConfigReader httpConfig, final ActorRef healthCheckingActor, final ActorMaterializer materializer) { String hostname = httpConfig.getHostname(); if (hostname.isEmpty()) { hostname = ConfigUtil.getLocalHostAddress(); log.info("No explicit hostname configured, using HTTP hostname: {}", hostname); } final CompletionStage<ServerBinding> binding = Http.get(getContext().system()) // .bindAndHandle( createRoute(getContext().system(), healthCheckingActor).flow(getContext().system(), materializer), ConnectHttp.toHost(hostname, httpConfig.getPort()), materializer); binding.thenAccept(theBinding -> CoordinatedShutdown.get(getContext().getSystem()).addTask( CoordinatedShutdown.PhaseServiceUnbind(), "shutdown_health_http_endpoint", () -> { log.info("Gracefully shutting down status/health HTTP endpoint.."); return theBinding.terminate(Duration.ofSeconds(1)) .handle((httpTerminated, e) -> Done.getInstance()); }) ).exceptionally(failure -> { log.error(failure, "Something very bad happened: {}", failure.getMessage()); getContext().system().terminate(); return null; }); }
/** * Hook that will be called just after the Http server binding is done. Override this method if you want to perform some actions after the server is up. */ protected void postHttpBinding (ServerBinding binding) { systemReference.get().log().info("Server online at http://" + binding.localAddress().getHostName() + ":" + binding.localAddress().getPort() + "/"); }
private void onStarted(ServerBinding binding) { final InetSocketAddress address = binding.localAddress(); log().info("Server started at {}:{}", address.getHostString(), address.getPort()); }