akka.http.javadsl.Http Java Examples

The following examples show how to use akka.http.javadsl.Http. 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: HttpPushClientActorTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Before
public void createActorSystem() {
    // create actor system with deactivated hostname blacklist to connect to localhost
    actorSystem = ActorSystem.create(getClass().getSimpleName(),
            TestConstants.CONFIG.withValue("ditto.connectivity.connection.http-push.blacklisted-hostnames",
                    ConfigValueFactory.fromAnyRef("")));
    mat = ActorMaterializer.create(actorSystem);
    requestQueue = new LinkedBlockingQueue<>();
    responseQueue = new LinkedBlockingQueue<>();
    handler = Flow.fromFunction(request -> {
        requestQueue.offer(request);
        return responseQueue.take();
    });
    binding = Http.get(actorSystem)
            .bindAndHandle(handler, ConnectHttp.toHost("127.0.0.1", 0), mat)
            .toCompletableFuture()
            .join();
    connection = getHttpConnectionBuilderToLocalBinding(false, binding.localAddress().getPort()).build();
}
 
Example #2
Source File: HttpPushFactoryTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
private void newBinding() {
    requestQueue = new LinkedBlockingQueue<>();
    responseQueue = new LinkedBlockingQueue<>();

    final Flow<HttpRequest, HttpResponse, NotUsed> handler =
            Flow.fromGraph(KillSwitches.<HttpRequest>single())
                    .mapAsync(1, request -> {
                        requestQueue.offer(request);
                        return responseQueue.take();
                    })
                    .mapMaterializedValue(killSwitch -> {
                        Objects.requireNonNull(killSwitchTrigger.peek())
                                .thenAccept(_void -> killSwitch.shutdown());
                        return NotUsed.getInstance();
                    });
    binding = Http.get(actorSystem).bindAndHandle(handler, ConnectHttp.toHost("127.0.0.1", 0), mat)
            .toCompletableFuture()
            .join();
}
 
Example #3
Source File: AkkaHttpClientTest.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
@Test
public void test(final MockTracer tracer) throws IllegalAccessException, InvocationTargetException {
  final Materializer materializer = ActorMaterializer.create(system);

  final Http http = getHttp(system);

  final CompletionStage<HttpResponse> stage = http.singleRequest(HttpRequest.GET("http://localhost:12345"));
  try {
    stage.whenComplete(new BiConsumer<HttpResponse,Throwable>() {
      @Override
      public void accept(final HttpResponse httpResponse, final Throwable throwable) {
        System.out.println(httpResponse.status());
      }
    }).toCompletableFuture().get().entity().getDataBytes().runForeach(param -> {}, materializer);
  }
  catch (final Exception ignore) {
  }

  await().atMost(15, TimeUnit.SECONDS).until(TestUtil.reportedSpansSize(tracer), equalTo(1));

  final List<MockSpan> spans = tracer.finishedSpans();
  assertEquals(1, spans.size());
  assertEquals(AkkaAgentIntercept.COMPONENT_NAME_CLIENT, spans.get(0).tags().get(Tags.COMPONENT.getKey()));
}
 
Example #4
Source File: AkkaHttpClientITest.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
public static void main(final String[] args) throws Exception {
  final ActorSystem system = ActorSystem.create();
  final Materializer materializer = ActorMaterializer.create(system);

  final Http http = getHttp(system);
  final CompletionStage<HttpResponse> stage = http.singleRequest(HttpRequest.GET("http://www.google.com"));
  stage.whenComplete(new BiConsumer<HttpResponse,Throwable>() {
    @Override
    public void accept(final HttpResponse httpResponse, final Throwable throwable) {
      TestUtil.checkActiveSpan();
      System.out.println(httpResponse.status());
    }
  }).toCompletableFuture().get().entity().getDataBytes().runForeach(param -> {}, materializer);

  stage.thenRun(system::terminate).toCompletableFuture().get();
  TestUtil.checkSpan(new ComponentSpanCount("akka-http-client", 1));
}
 
Example #5
Source File: WebSocketDataCenterServer.java    From ts-reaktive with MIT License 6 votes vote down vote up
/**
 * Creates the web socket server and binds to the port, according to [config].
 */
public WebSocketDataCenterServer(ActorSystem system, Map<String,ActorRef> tagsAndShardRegions) {
    Config config = system.settings().config().getConfig("ts-reaktive.replication.server");
    ActorMaterializer materializer = SharedActorMaterializer.get(system);
    this.timeout = config.getDuration("timeout");
    this.maxInFlight = config.getInt("max-in-flight");
    Route route = pathPrefix("events", () -> route(
        tagsAndShardRegions.map(t ->
            path(t._1, () ->
                handleWebSocketMessages(flow(t._2))
            )
        ).toJavaArray(Route.class)
    ));
    ConnectHttp httpOpts = SSLFactory.createSSLContext(config).map(sslContext ->
        (ConnectHttp) new ConnectHttpsImpl(config.getString("host"), config.getInt("port"), Optional.of(
            ConnectionContext.https(sslContext, Optional.empty(), Optional.empty(),
                                    Optional.of(TLSClientAuth.need()), Optional.empty())),
                                           UseHttp2.never())
    ).getOrElse(() ->
        ConnectHttp.toHost(config.getString("host"), config.getInt("port"))
    );
    this.binding = Http.get(system).bindAndHandle(route.flow(system, materializer), httpOpts, materializer);
}
 
Example #6
Source File: ConciergeRootActor.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
private void bindHttpStatusRoute(final ActorRef healthCheckingActor, final HttpConfig httpConfig,
        final ActorMaterializer materializer) {

    String hostname = httpConfig.getHostname();
    if (hostname.isEmpty()) {
        hostname = LocalHostAddressSupplier.getInstance().get();
        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;
    });
}
 
Example #7
Source File: WebSocketDataCenterClient.java    From ts-reaktive with MIT License 6 votes vote down vote up
@Override
public Flow<EventEnvelope,Long,?> uploadFlow() {
    ClientConnectionSettings settings = ClientConnectionSettings.create(system.settings().config());
    
    return Flow.<EventEnvelope>create()
        .map(e -> (Message) BinaryMessage.create(serialize(e)))
        .via(Http.get(system).webSocketClientFlow(WebSocketRequest.create(uri), connectionContext, Optional.empty(), settings, system.log()))
        .map(msg -> {
            if (msg.isText()) {
                log.warn("Ignoring unexpected text-type WS message {}", msg);
                return 0l;
            } else {
                EventsPersisted applied = EventsPersisted.parseFrom(
                    msg.asBinaryMessage().getStrictData().iterator().asInputStream());
                return applied.hasOffset() ? applied.getOffset() : 0l;
            }})
        .filter(l -> l > 0);
}
 
Example #8
Source File: HealthService.java    From ari-proxy with GNU Affero General Public License v3.0 6 votes vote down vote up
private CompletionStage<ServerBinding> startHttpServer() {
	final ActorSystem system = getContext().getSystem();
	final Http http = Http.get(system);
	final ActorMaterializer materializer = ActorMaterializer.create(system);

	final Flow<HttpRequest, HttpResponse, NotUsed> routeFlow = createRoute().flow(system, materializer);

	final String address = "0.0.0.0";
	final CompletionStage<ServerBinding> binding = http.bindAndHandle(
			routeFlow,
			ConnectHttp.toHost(address, httpPort),
			materializer
	);

	log().info("HTTP server online at http://{}:{}/...", address, httpPort);

	return binding;
}
 
Example #9
Source File: AriCommandResponseKafkaProcessorTest.java    From ari-proxy with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test()
void properlyHandleInvalidCommandMessage() {
	final TestKit kafkaProducer = new TestKit(system);
	final TestKit metricsService = new TestKit(system);
	final TestKit callContextProvider = new TestKit(system);

	final ConsumerRecord<String, String> consumerRecord = new ConsumerRecord<>("topic", 0, 0,
			"key", "NOT JSON");
	final Source<ConsumerRecord<String, String>, NotUsed> source = Source.single(consumerRecord);
	final Sink<ProducerRecord<String, String>, NotUsed> sink = Sink.<ProducerRecord<String, String>>ignore()
			.mapMaterializedValue(q -> NotUsed.getInstance());

	AriCommandResponseKafkaProcessor.commandResponseProcessing()
			.on(system)
			.withHandler(requestAndContext -> Http.get(system).singleRequest(requestAndContext._1))
			.withCallContextProvider(callContextProvider.getRef())
			.withMetricsService(metricsService.getRef())
			.from(source)
			.to(sink)
			.run();

	kafkaProducer.expectNoMsg(Duration.apply(250, TimeUnit.MILLISECONDS));
}
 
Example #10
Source File: HttpPushClientActorTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testTLSConnection() {
    // GIVEN: server has a self-signed certificate
    final ClientCertificateCredentials credentials = ClientCertificateCredentials.newBuilder()
            .clientKey(TestConstants.Certificates.CLIENT_SELF_SIGNED_KEY)
            .clientCertificate(TestConstants.Certificates.CLIENT_SELF_SIGNED_CRT)
            .build();
    connection = getHttpConnectionBuilderToLocalBinding(true, binding.localAddress().getPort())
            .credentials(credentials)
            .trustedCertificates(TestConstants.Certificates.CLIENT_SELF_SIGNED_CRT)
            .build();
    final SSLContext sslContext = SSLContextCreator.fromConnection(connection, DittoHeaders.empty())
            .clientCertificate(credentials);
    final HttpsConnectionContext httpsContext = ConnectionContext.https(sslContext);

    final int port = binding.localAddress().getPort();
    binding.terminate(Duration.ofMillis(1L)).toCompletableFuture().join();
    binding = Http.get(actorSystem)
            .bindAndHandle(handler,
                    ConnectHttp.toHostHttps("127.0.0.1", port).withCustomHttpsContext(httpsContext),
                    mat)
            .toCompletableFuture()
            .join();

    new TestKit(actorSystem) {{
        // WHEN: the connection is tested
        final ActorRef underTest = watch(actorSystem.actorOf(createClientActor(getRef(), getConnection(false))));
        underTest.tell(TestConnection.of(connection, DittoHeaders.empty()), getRef());

        // THEN: the connection is connected successfully
        expectMsg(new Status.Success("successfully connected + initialized mapper"));
        expectTerminated(underTest);
    }};
}
 
Example #11
Source File: HttpPushClientActorTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testTLSConnectionFails() {
    // GIVEN: server has a self-signed certificate
    connection = getHttpConnectionBuilderToLocalBinding(true, binding.localAddress().getPort()).build();
    final ClientCertificateCredentials credentials = ClientCertificateCredentials.newBuilder()
            .clientKey(TestConstants.Certificates.CLIENT_SELF_SIGNED_KEY)
            .clientCertificate(TestConstants.Certificates.CLIENT_SELF_SIGNED_CRT)
            .build();
    final SSLContext sslContext = SSLContextCreator.fromConnection(connection, DittoHeaders.empty())
            .clientCertificate(credentials);
    final HttpsConnectionContext invalidHttpsContext = ConnectionContext.https(sslContext);

    final int port = binding.localAddress().getPort();
    binding.terminate(Duration.ofMillis(1L)).toCompletableFuture().join();
    binding = Http.get(actorSystem)
            .bindAndHandle(handler,
                    ConnectHttp.toHostHttps("127.0.0.1", port).withCustomHttpsContext(invalidHttpsContext),
                    mat)
            .toCompletableFuture()
            .join();

    new TestKit(actorSystem) {{
        // WHEN: the connection is tested
        final ActorRef underTest = watch(actorSystem.actorOf(createClientActor(getRef(), getConnection(false))));
        underTest.tell(TestConnection.of(connection, DittoHeaders.empty()), getRef());

        // THEN: the test fails
        final Status.Failure failure = expectMsgClass(Status.Failure.class);
        assertThat(failure.cause()).isInstanceOf(DittoRuntimeException.class);
        assertThat(((DittoRuntimeException) failure.cause()).getDescription().orElse(""))
                .contains("unable to find valid certification path");
        expectTerminated(underTest);
    }};
}
 
Example #12
Source File: DefaultHttpPushFactory.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public <T> Flow<Pair<HttpRequest, T>, Pair<Try<HttpResponse>, T>, ?> createFlow(final ActorSystem system,
        final LoggingAdapter log) {

    final Http http = Http.get(system);
    final ConnectionPoolSettings poolSettings = getConnectionPoolSettings(system);
    final Flow<Pair<HttpRequest, T>, Pair<Try<HttpResponse>, T>, ?> flow;
    if (null != httpsConnectionContext) {
        final ConnectHttp connectHttpsWithCustomSSLContext =
                ConnectHttp.toHostHttps(baseUri).withCustomHttpsContext(httpsConnectionContext);
        // explicitly added <T> as in (some?) IntelliJ idea the line would show an error:
        flow = http.<T>cachedHostConnectionPoolHttps(connectHttpsWithCustomSSLContext, poolSettings, log);
    } else {
        // explicitly added <T> as in (some?) IntelliJ idea the line would show an error:
        // no SSL, hence no need for SSLContextCreator
        flow = http.<T>cachedHostConnectionPool(ConnectHttp.toHost(baseUri), poolSettings, log);
    }
    return flow.buffer(parallelism, OverflowStrategy.backpressure());
}
 
Example #13
Source File: ConnectivityRootActor.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private CompletionStage<ServerBinding> getHttpBinding(final HttpConfig httpConfig,
        final ActorSystem actorSystem,
        final ActorMaterializer materializer,
        final ActorRef healthCheckingActor) {

    String hostname = httpConfig.getHostname();
    if (hostname.isEmpty()) {
        hostname = LocalHostAddressSupplier.getInstance().get();
        log.info("No explicit hostname configured, using HTTP hostname <{}>.", hostname);
    }

    return Http.get(actorSystem)
            .bindAndHandle(createRoute(actorSystem, healthCheckingActor).flow(actorSystem, materializer),
                    ConnectHttp.toHost(hostname, httpConfig.getPort()), materializer);
}
 
Example #14
Source File: SearchRootActor.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private void createHealthCheckingActorHttpBinding(final HttpConfig httpConfig,
        final ActorRef healthCheckingActor, final ActorMaterializer materializer) {

    String hostname = httpConfig.getHostname();
    if (hostname.isEmpty()) {
        hostname = LocalHostAddressSupplier.getInstance().get();
        log.info("No explicit hostname configured, using HTTP hostname <{}>.", hostname);
    }

    final ActorSystem actorSystem = getContext().system();
    final CompletionStage<ServerBinding> binding = Http.get(actorSystem) //
            .bindAndHandle(
                    createRoute(actorSystem, healthCheckingActor).flow(actorSystem,
                            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());
        actorSystem.terminate();
        return null;
    });
}
 
Example #15
Source File: DefaultHttpClientFacade.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public CompletionStage<HttpResponse> createSingleHttpRequest(final HttpRequest request) {
    return Http.get(actorSystem).singleRequest(request,
            Http.get(actorSystem).defaultClientHttpsContext(),
            connectionPoolSettings,
            actorSystem.log(),
            actorMaterializer
    );
}
 
Example #16
Source File: DittoService.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Starts Prometheus HTTP endpoint on which Prometheus may scrape the data.
 */
private void startKamonPrometheusHttpEndpoint(final ActorSystem actorSystem) {
    final MetricsConfig metricsConfig = serviceSpecificConfig.getMetricsConfig();
    if (metricsConfig.isPrometheusEnabled() && null != prometheusReporter) {
        final String prometheusHostname = metricsConfig.getPrometheusHostname();
        final int prometheusPort = metricsConfig.getPrometheusPort();
        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(prometheusHostname, prometheusPort), 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;
        });
    }
}
 
Example #17
Source File: Main.java    From ari-proxy with GNU Affero General Public License v3.0 5 votes vote down vote up
private static ActorMaterializer runAriCommandResponseProcessor(
		Config kafkaConfig,
		ActorSystem system,
		ActorRef callContextProvider,
		ActorRef metricsService) {
	final ConsumerSettings<String, String> consumerSettings = ConsumerSettings
			.create(system, new StringDeserializer(), new StringDeserializer())
			.withBootstrapServers(kafkaConfig.getString(BOOTSTRAP_SERVERS))
			.withGroupId(kafkaConfig.getString(CONSUMER_GROUP))
			.withProperty(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "true")
			.withProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");

	final ProducerSettings<String, String> producerSettings = ProducerSettings
			.create(system, new StringSerializer(), new StringSerializer())
			.withBootstrapServers(kafkaConfig.getString(BOOTSTRAP_SERVERS));

	final Source<ConsumerRecord<String, String>, NotUsed> source = RestartSource.withBackoff(
			Duration.of(5, ChronoUnit.SECONDS),
			Duration.of(10, ChronoUnit.SECONDS),
			0.2,
			() -> Consumer
					.plainSource(consumerSettings, Subscriptions.topics(kafkaConfig.getString(COMMANDS_TOPIC)))
					.mapMaterializedValue(control -> NotUsed.getInstance())
	);

	final Sink<ProducerRecord<String, String>, NotUsed> sink = Producer
			.plainSink(producerSettings)
			.mapMaterializedValue(done -> NotUsed.getInstance());

	return AriCommandResponseKafkaProcessor.commandResponseProcessing()
			.on(system)
			.withHandler(requestAndContext -> Http.get(system).singleRequest(requestAndContext._1))
			.withCallContextProvider(callContextProvider)
			.withMetricsService(metricsService)
			.from(source)
			.to(sink)
			.run();
}
 
Example #18
Source File: TestHttpClient.java    From ts-reaktive with MIT License 5 votes vote down vote up
private HttpResponse send(HttpRequest request) {
    try {
        return Http.get(system)
            .singleRequest(request)
            .toCompletableFuture()
            .get(timeout, TimeUnit.MILLISECONDS);
    } catch (ExecutionException x) {
        throw (RuntimeException) x.getCause();
    } catch (InterruptedException | TimeoutException e) {
        throw new RuntimeException(e);
    }
}
 
Example #19
Source File: AkkaHttpServerITest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
public static void main(final String[] args) throws Exception {
  final ActorSystem system = ActorSystem.create();
  final Materializer materializer = ActorMaterializer.create(system);
  final Http http = getHttp(system);

  testSync(http, materializer);
  testAsync(http, materializer);

  Await.result(system.terminate(), Duration.create(15, TimeUnit.SECONDS));
}
 
Example #20
Source File: AkkaHttpClientITest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
static Http getHttp(final ActorSystem system) throws IllegalAccessException, InvocationTargetException {
  // Use Reflection to call Http.get(system) because Scala Http class decompiles to java
  // class with 2 similar methods 'Http.get(system)' with difference in return type only
  for (final Method method : Http.class.getMethods())
    if (Modifier.isStatic(method.getModifiers()) && "get".equals(method.getName()) && Http.class.equals(method.getReturnType()))
      return (Http)method.invoke(null, system);

  throw new AssertionError("ERROR: failed to get Http object");
}
 
Example #21
Source File: AkkaHttpClientTest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
static Http getHttp(final ActorSystem system) throws IllegalAccessException, InvocationTargetException {
  // Use Reflection to call Http.get(system) because Scala Http class decompiles to java
  // class with 2 similar methods 'Http.get(system)' with difference in return type only
  for (final Method method : Http.class.getMethods())
    if (Modifier.isStatic(method.getModifiers()) && "get".equals(method.getName()) && Http.class.equals(method.getReturnType()))
      return (Http)method.invoke(null, system);

  return null;
}
 
Example #22
Source File: ClientConfigShould.java    From mutual-tls-ssl with Apache License 2.0 5 votes vote down vote up
@Test
public void createAkkaHttpClientWithSecurity() {
    SSLFactory sslFactory = createSSLFactory(false, true);

    Http http = victim.akkaHttpClient(sslFactory, ActorSystem.create());

    assertThat(http).isNotNull();
    verify(sslFactory, times(2)).getSslContext();
}
 
Example #23
Source File: Boot.java    From docker-nginx-consul with MIT License 5 votes vote down vote up
public static void main(String[] args) {
  // config
  final String appId = UUID.randomUUID().toString();
  final AppConfiguration appConfig = AppConfiguration.loadConfig(appId);

  // actor system init
  final ActorSystem system = ActorSystem.create();
  final Materializer materializer = ActorMaterializer.create(system);

  // service discovery actor
  final ActorRef serviceDiscoveryActor = system.actorOf(DiscoveryAgentActor.props(appConfig), "example-app-consul-service");

  // http init
  final Flow<HttpRequest, HttpResponse, NotUsed> routeFlow = new AppResource(appConfig).routes().flow(system, materializer);
  final CompletionStage<ServerBinding> binding = Http
      .get(system)
      .bindAndHandle(
          routeFlow,
          ConnectHttp.toHost(appConfig.host, appConfig.port),
          materializer
      );

  // exception handling
  binding.exceptionally(failure -> {
    System.err.println("Something very bad happened! " + failure.getMessage());
    system.terminate();
    return null;
  });

}
 
Example #24
Source File: HttpFlow.java    From ts-reaktive with MIT License 4 votes vote down vote up
public HttpFlow(Http http, Materializer materializer) {
    this.http = http;
    this.materializer = materializer;
}
 
Example #25
Source File: PoliciesRootActor.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
@SuppressWarnings("unused")
private PoliciesRootActor(final PoliciesConfig policiesConfig,
        final SnapshotAdapter<Policy> snapshotAdapter,
        final ActorRef pubSubMediator,
        final ActorMaterializer materializer) {

    final ActorSystem actorSystem = getContext().system();
    final ClusterShardingSettings shardingSettings =
            ClusterShardingSettings.create(actorSystem).withRole(CLUSTER_ROLE);

    final Props policySupervisorProps = PolicySupervisorActor.props(pubSubMediator, snapshotAdapter);

    final TagsConfig tagsConfig = policiesConfig.getTagsConfig();
    final ActorRef persistenceStreamingActor = startChildActor(PoliciesPersistenceStreamingActorCreator.ACTOR_NAME,
            PoliciesPersistenceStreamingActorCreator.props(tagsConfig.getStreamingCacheSize()));

    pubSubMediator.tell(DistPubSubAccess.put(getSelf()), getSelf());
    pubSubMediator.tell(DistPubSubAccess.put(persistenceStreamingActor), getSelf());

    final ClusterConfig clusterConfig = policiesConfig.getClusterConfig();
    final ActorRef policiesShardRegion = ClusterSharding.get(actorSystem)
            .start(PoliciesMessagingConstants.SHARD_REGION, policySupervisorProps, shardingSettings,
                    ShardRegionExtractor.of(clusterConfig.getNumberOfShards(), actorSystem));

    startChildActor(PolicyPersistenceOperationsActor.ACTOR_NAME,
            PolicyPersistenceOperationsActor.props(pubSubMediator, policiesConfig.getMongoDbConfig(),
                    actorSystem.settings().config(), policiesConfig.getPersistenceOperationsConfig()));

    retrieveStatisticsDetailsResponseSupplier = RetrieveStatisticsDetailsResponseSupplier.of(policiesShardRegion,
            PoliciesMessagingConstants.SHARD_REGION, log);

    final HealthCheckConfig healthCheckConfig = policiesConfig.getHealthCheckConfig();
    final HealthCheckingActorOptions.Builder hcBuilder =
            HealthCheckingActorOptions.getBuilder(healthCheckConfig.isEnabled(), healthCheckConfig.getInterval());
    if (healthCheckConfig.getPersistenceConfig().isEnabled()) {
        hcBuilder.enablePersistenceCheck();
    }

    final HealthCheckingActorOptions healthCheckingActorOptions = hcBuilder.build();
    final MetricsReporterConfig metricsReporterConfig =
            healthCheckConfig.getPersistenceConfig().getMetricsReporterConfig();
    final Props healthCheckingActorProps = DefaultHealthCheckingActorFactory.props(healthCheckingActorOptions,
            MongoHealthChecker.props(),
            MongoMetricsReporter.props(
                    metricsReporterConfig.getResolution(),
                    metricsReporterConfig.getHistory(),
                    pubSubMediator
            )
    );
    final ActorRef healthCheckingActor =
            startChildActor(DefaultHealthCheckingActorFactory.ACTOR_NAME, healthCheckingActorProps);

    final HttpConfig httpConfig = policiesConfig.getHttpConfig();
    String hostname = httpConfig.getHostname();
    if (hostname.isEmpty()) {
        hostname = LocalHostAddressSupplier.getInstance().get();
        log.info("No explicit hostname configured, using HTTP hostname <{}>.", hostname);
    }

    final CompletionStage<ServerBinding> binding = Http.get(actorSystem)
            .bindAndHandle(createRoute(actorSystem, healthCheckingActor).flow(actorSystem,
                    materializer), ConnectHttp.toHost(hostname, httpConfig.getPort()), materializer);

    binding.thenAccept(theBinding -> CoordinatedShutdown.get(actorSystem).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());
            })
    );
    binding.thenAccept(this::logServerBinding)
            .exceptionally(failure -> {
                log.error(failure, "Something very bad happened: {}", failure.getMessage());
                actorSystem.terminate();
                return null;
            });
}
 
Example #26
Source File: Messenger.java    From tutorials with MIT License 4 votes vote down vote up
private CompletionStage<HttpResponse> getRandomMessage() {
    int postId = ThreadLocalRandom.current().nextInt(0, 100);
    return Http.get(getContext().getSystem()).singleRequest(
      HttpRequest.create("https://jsonplaceholder.typicode.com/posts/" + postId)
    );
}
 
Example #27
Source File: GatewayRootActor.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
@SuppressWarnings("unused")
private GatewayRootActor(final GatewayConfig gatewayConfig, final ActorRef pubSubMediator,
        final ActorMaterializer materializer) {

    final ActorSystem actorSystem = context().system();

    final ClusterConfig clusterConfig = gatewayConfig.getClusterConfig();
    final int numberOfShards = clusterConfig.getNumberOfShards();

    log.info("Starting /user/{}", DevOpsCommandsActor.ACTOR_NAME);
    final ActorRef devOpsCommandsActor = actorSystem.actorOf(
            DevOpsCommandsActor.props(LogbackLoggingFacade.newInstance(), GatewayService.SERVICE_NAME,
                    InstanceIdentifierSupplier.getInstance().get()),
            DevOpsCommandsActor.ACTOR_NAME);

    final ActorRef conciergeEnforcerRouter =
            ConciergeEnforcerClusterRouterFactory.createConciergeEnforcerClusterRouter(getContext(),
                    numberOfShards);

    final ActorRef conciergeForwarder = startChildActor(ConciergeForwarderActor.ACTOR_NAME,
            ConciergeForwarderActor.props(pubSubMediator, conciergeEnforcerRouter));

    final ActorRef proxyActor = startChildActor(AbstractProxyActor.ACTOR_NAME,
            ProxyActor.props(pubSubMediator, devOpsCommandsActor, conciergeForwarder));

    pubSubMediator.tell(DistPubSubAccess.put(getSelf()), getSelf());

    final DittoProtocolSub dittoProtocolSub = DittoProtocolSub.of(getContext());

    final AuthenticationConfig authenticationConfig = gatewayConfig.getAuthenticationConfig();
    final DefaultHttpClientFacade httpClient =
            DefaultHttpClientFacade.getInstance(actorSystem, authenticationConfig.getHttpProxyConfig());

    final JwtAuthenticationFactory jwtAuthenticationFactory =
            JwtAuthenticationFactory.newInstance(authenticationConfig.getOAuthConfig(),
                    gatewayConfig.getCachesConfig().getPublicKeysConfig(), httpClient);

    final ProtocolAdapterProvider protocolAdapterProvider =
            ProtocolAdapterProvider.load(gatewayConfig.getProtocolConfig(), actorSystem);
    final HeaderTranslator headerTranslator = protocolAdapterProvider.getHttpHeaderTranslator();

    final ActorRef streamingActor = startChildActor(StreamingActor.ACTOR_NAME,
            StreamingActor.props(dittoProtocolSub, proxyActor, jwtAuthenticationFactory,
                    gatewayConfig.getStreamingConfig(), headerTranslator, pubSubMediator, conciergeForwarder));

    final HealthCheckConfig healthCheckConfig = gatewayConfig.getHealthCheckConfig();
    final ActorRef healthCheckActor = createHealthCheckActor(healthCheckConfig);

    final HttpConfig httpConfig = gatewayConfig.getHttpConfig();
    String hostname = httpConfig.getHostname();
    if (hostname.isEmpty()) {
        hostname = LocalHostAddressSupplier.getInstance().get();
        log.info("No explicit hostname configured, using HTTP hostname <{}>.", hostname);
    }

    final Route rootRoute = createRoute(actorSystem, gatewayConfig, proxyActor, streamingActor,
            healthCheckActor, pubSubMediator, healthCheckConfig, jwtAuthenticationFactory, protocolAdapterProvider,
            headerTranslator);
    final Route routeWithLogging = Directives.logRequest("http", Logging.DebugLevel(), () -> rootRoute);

    httpBinding = Http.get(actorSystem)
            .bindAndHandle(routeWithLogging.flow(actorSystem, materializer),
                    ConnectHttp.toHost(hostname, httpConfig.getPort()), materializer);

    httpBinding.thenAccept(theBinding -> {
                log.info("Serving HTTP requests on port <{}> ...", theBinding.localAddress().getPort());
                CoordinatedShutdown.get(actorSystem).addTask(
                        CoordinatedShutdown.PhaseServiceUnbind(), "shutdown_http_endpoint", () -> {
                            log.info("Gracefully shutting down user HTTP endpoint ...");
                            return theBinding.terminate(Duration.ofSeconds(10))
                                    .handle((httpTerminated, e) -> Done.getInstance());
                        });
            }
    ).exceptionally(failure -> {
        log.error(failure, "Something very bad happened: {}", failure.getMessage());
        actorSystem.terminate();
        return null;
    });
}
 
Example #28
Source File: AbstractBaseClientActorTest.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void testTLSConnectionWithoutCertificateCheck() {
    // GIVEN: server has a self-signed certificate (bind port number is random; connection port number is ignored)
    final Connection serverConnection = getHttpConnectionBuilderToLocalBinding(true, 443).build();
    final ClientCertificateCredentials credentials = ClientCertificateCredentials.newBuilder()
            .clientKey(TestConstants.Certificates.CLIENT_SELF_SIGNED_KEY)
            .clientCertificate(TestConstants.Certificates.CLIENT_SELF_SIGNED_CRT)
            .build();
    final SSLContext sslContext = SSLContextCreator.fromConnection(serverConnection, DittoHeaders.empty())
            .clientCertificate(credentials);
    final HttpsConnectionContext invalidHttpsContext = ConnectionContext.https(sslContext);

    final ActorSystem actorSystem = getActorSystem();
    final ServerBinding binding = Http.get(actorSystem)
            .bindAndHandle(Flow.fromSinkAndSource(Sink.ignore(), Source.empty()),
                    ConnectHttp.toHostHttps("127.0.0.1", 0).withCustomHttpsContext(invalidHttpsContext),
                    ActorMaterializer.create(actorSystem))
            .toCompletableFuture()
            .join();

    new TestKit(actorSystem) {{
        // WHEN: the connection is tested against a client actor that really tries to connect to the local port
        final Connection secureConnection = getConnection(true);
        final Connection insecureConnection = secureConnection.toBuilder()
                .uri(Uri.create(secureConnection.getUri()).port(binding.localAddress().getPort()).toString())
                .validateCertificate(false)
                .failoverEnabled(false)
                .build();
        final ActorRef underTest = watch(actorSystem.actorOf(
                DefaultClientActorPropsFactory.getInstance()
                        .getActorPropsForType(insecureConnection, getRef(), getRef())
        ));
        underTest.tell(TestConnection.of(insecureConnection, DittoHeaders.empty()), getRef());

        // THEN: the test should succeed, or it should fail with a different reason than SSL validation
        final Object response = expectMsgClass(Duration.ofSeconds(5), Object.class);
        if (response instanceof Status.Failure) {
            final DittoRuntimeException error =
                    (DittoRuntimeException) getEventualCause(((Status.Failure) response).cause());
            assertThat(error.getMessage())
                    .describedAs("error message")
                    .doesNotContain("unable to find valid certification path");
            assertThat(error.getDescription().orElse(""))
                    .describedAs("error description")
                    .doesNotContain("unable to find valid certification path");
        } else {
            assertThat(response).isInstanceOf(Status.Success.class);
        }
        expectTerminated(underTest);
    }};
}
 
Example #29
Source File: ThingsRootActor.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
@SuppressWarnings("unused")
private ThingsRootActor(final ThingsConfig thingsConfig,
        final ActorRef pubSubMediator,
        final ActorMaterializer materializer,
        final ThingPersistenceActorPropsFactory propsFactory) {

    final ActorSystem actorSystem = getContext().system();

    final ClusterConfig clusterConfig = thingsConfig.getClusterConfig();
    final ShardRegionExtractor shardRegionExtractor =
            ShardRegionExtractor.of(clusterConfig.getNumberOfShards(), actorSystem);
    final ThingEventPubSubFactory pubSubFactory = ThingEventPubSubFactory.of(getContext(), shardRegionExtractor);
    final DistributedPub<ThingEvent> distributedPub = pubSubFactory.startDistributedPub();

    final ActorRef thingsShardRegion = ClusterSharding.get(actorSystem)
            .start(ThingsMessagingConstants.SHARD_REGION,
                    getThingSupervisorActorProps(pubSubMediator, distributedPub, propsFactory),
                    ClusterShardingSettings.create(actorSystem).withRole(CLUSTER_ROLE),
                    shardRegionExtractor);

    startChildActor(ThingPersistenceOperationsActor.ACTOR_NAME,
            ThingPersistenceOperationsActor.props(pubSubMediator, thingsConfig.getMongoDbConfig(),
                    actorSystem.settings().config(), thingsConfig.getPersistenceOperationsConfig()));

    retrieveStatisticsDetailsResponseSupplier = RetrieveStatisticsDetailsResponseSupplier.of(thingsShardRegion,
            ThingsMessagingConstants.SHARD_REGION, log);

    final HealthCheckConfig healthCheckConfig = thingsConfig.getHealthCheckConfig();
    final HealthCheckingActorOptions.Builder hcBuilder =
            HealthCheckingActorOptions.getBuilder(healthCheckConfig.isEnabled(), healthCheckConfig.getInterval());
    if (healthCheckConfig.getPersistenceConfig().isEnabled()) {
        hcBuilder.enablePersistenceCheck();
    }

    final HealthCheckingActorOptions healthCheckingActorOptions = hcBuilder.build();
    final MetricsReporterConfig metricsReporterConfig =
            healthCheckConfig.getPersistenceConfig().getMetricsReporterConfig();
    final ActorRef healthCheckingActor = startChildActor(DefaultHealthCheckingActorFactory.ACTOR_NAME,
            DefaultHealthCheckingActorFactory.props(healthCheckingActorOptions,
                    MongoHealthChecker.props(),
                    MongoMetricsReporter.props(
                            metricsReporterConfig.getResolution(),
                            metricsReporterConfig.getHistory(),
                            pubSubMediator
                    )
            ));

    final TagsConfig tagsConfig = thingsConfig.getTagsConfig();
    final ActorRef eventStreamingActor =
            ThingsPersistenceStreamingActorCreator.startEventStreamingActor(tagsConfig.getStreamingCacheSize(),
                    this::startChildActor);
    final ActorRef snapshotStreamingActor =
            ThingsPersistenceStreamingActorCreator.startSnapshotStreamingActor(this::startChildActor);

    pubSubMediator.tell(DistPubSubAccess.put(getSelf()), getSelf());
    pubSubMediator.tell(DistPubSubAccess.put(eventStreamingActor), getSelf());
    pubSubMediator.tell(DistPubSubAccess.put(snapshotStreamingActor), getSelf());

    final HttpConfig httpConfig = thingsConfig.getHttpConfig();
    String hostname = httpConfig.getHostname();
    if (hostname.isEmpty()) {
        hostname = LocalHostAddressSupplier.getInstance().get();
        log.info("No explicit hostname configured, using HTTP hostname <{}>.", hostname);
    }
    final CompletionStage<ServerBinding> binding = Http.get(actorSystem)
            .bindAndHandle(
                    createRoute(actorSystem, healthCheckingActor).flow(actorSystem,
                            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());
            })
    );
    binding.thenAccept(this::logServerBinding)
            .exceptionally(failure -> {
                log.error(failure, "Something very bad happened: {}", failure.getMessage());
                actorSystem.terminate();
                return null;
            });
}
 
Example #30
Source File: AkkaHttpClientService.java    From mutual-tls-ssl with Apache License 2.0 4 votes vote down vote up
public AkkaHttpClientService(Http akkaHttpClient, ActorSystem actorSystem) {
    this.akkaHttpClient = akkaHttpClient;
    this.actorSystem = actorSystem;
}