|
| 1 | +package org.baeldung.lagom.helloworld.greeting.impl; |
| 2 | + |
| 3 | +import java.util.concurrent.CompletableFuture; |
| 4 | +import java.util.concurrent.ExecutionException; |
| 5 | + |
| 6 | +import org.baeldung.lagom.helloworld.greeting.api.GreetingService; |
| 7 | +import org.baeldung.lagom.helloworld.greeting.impl.GreetingCommand.ReceivedGreetingCommand; |
| 8 | +import org.baeldung.lagom.helloworld.weather.api.WeatherService; |
| 9 | +import org.baeldung.lagom.helloworld.weather.api.WeatherStats; |
| 10 | + |
| 11 | +import com.google.inject.Inject; |
| 12 | +import com.lightbend.lagom.javadsl.api.ServiceCall; |
| 13 | +import com.lightbend.lagom.javadsl.persistence.PersistentEntityRef; |
| 14 | +import com.lightbend.lagom.javadsl.persistence.PersistentEntityRegistry; |
| 15 | + |
| 16 | +import akka.NotUsed; |
| 17 | + |
| 18 | +public class GreetingServiceImpl implements GreetingService { |
| 19 | + |
| 20 | + private final PersistentEntityRegistry persistentEntityRegistry; |
| 21 | + private final WeatherService weatherService; |
| 22 | + |
| 23 | + @Inject |
| 24 | + public GreetingServiceImpl(PersistentEntityRegistry persistentEntityRegistry, WeatherService weatherService) { |
| 25 | + this.persistentEntityRegistry = persistentEntityRegistry; |
| 26 | + this.weatherService = weatherService; |
| 27 | + persistentEntityRegistry.register(GreetingEntity.class); |
| 28 | + } |
| 29 | + |
| 30 | + @Override |
| 31 | + public ServiceCall<NotUsed, String> handleGreetFrom(String user) { |
| 32 | + return request -> { |
| 33 | + // Look up the hello world entity for the given ID. |
| 34 | + PersistentEntityRef<GreetingCommand> ref = persistentEntityRegistry.refFor(GreetingEntity.class, user); |
| 35 | + CompletableFuture<String> greetingResponse = ref.ask(new ReceivedGreetingCommand(user)) |
| 36 | + .toCompletableFuture(); |
| 37 | + CompletableFuture<WeatherStats> todaysWeatherInfo = |
| 38 | + (CompletableFuture<WeatherStats>) weatherService.weatherStatsForToday().invoke(); |
| 39 | + try { |
| 40 | + return CompletableFuture.completedFuture(greetingResponse.get() + |
| 41 | + " Today's weather stats: " + todaysWeatherInfo.get().getMessage()); |
| 42 | + } catch (InterruptedException | ExecutionException e) { |
| 43 | + return CompletableFuture.completedFuture("Sorry Some Error at our end, working on it"); |
| 44 | + } |
| 45 | + }; |
| 46 | + } |
| 47 | + |
| 48 | +} |
0 commit comments