akka.actor.AbstractActor Java Examples

The following examples show how to use akka.actor.AbstractActor. 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: CoffeeHouseTest.java    From oreilly-reactive-architecture-student with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldRestartWaiterAndResendPrepareCoffeeToBaristaOnFailure() {
    new JavaTestKit(system) {{
        createActor(CoffeeHouse.class, "resend-prepare-coffee", () -> new CoffeeHouse(Integer.MAX_VALUE) {
            @Override
            protected ActorRef createBarista() {
                return getRef();
            }

            @Override
            protected ActorRef createWaiter() { //stubbing out the waiter actor to always throw exception
                return context().actorOf(Props.create(AbstractActor.class, () -> new AbstractActor() {
                    @Override
                    public Receive createReceive() {
                        return receiveBuilder().matchAny(o -> {
                            throw new Waiter.FrustratedException(new Coffee.Akkaccino(), system.deadLetters());
                        }).build();
                    }
                }), "waiter");
            }
        });
        ActorRef waiter = expectActor(this, "/user/resend-prepare-coffee/waiter");
        waiter.tell("Blow up", ActorRef.noSender());
        expectMsgEquals(new Barista.PrepareCoffee(new Coffee.Akkaccino(), system.deadLetters()));
    }};
}
 
Example #2
Source File: CoffeeHouseTest.java    From oreilly-reactive-architecture-student with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldRestartWaiterAndResendPrepareCoffeeToBaristaOnFailure() {
    new JavaTestKit(system) {{
        createActor(CoffeeHouse.class, "resend-prepare-coffee", () -> new CoffeeHouse(Integer.MAX_VALUE) {
            @Override
            protected ActorRef createBarista() {
                return getRef();
            }

            @Override
            protected ActorRef createWaiter() { //stubbing out the waiter actor to always throw exception
                return context().actorOf(Props.create(AbstractActor.class, () -> new AbstractActor() {
                    @Override
                    public Receive createReceive() {
                        return receiveBuilder().matchAny(o -> {
                            throw new Waiter.FrustratedException(new Coffee.Akkaccino(), system.deadLetters());
                        }).build();
                    }
                }), "waiter");
            }
        });
        ActorRef waiter = expectActor(this, "/user/resend-prepare-coffee/waiter");
        waiter.tell("Blow up", ActorRef.noSender());
        expectMsgEquals(new Barista.PrepareCoffee(new Coffee.Akkaccino(), system.deadLetters()));
    }};
}
 
Example #3
Source File: CoffeeHouseTest.java    From oreilly-reactive-architecture-student with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldRestartWaiterAndResendPrepareCoffeeToBaristaOnFailure() {
    new JavaTestKit(system) {{
        createActor(CoffeeHouse.class, "resend-prepare-coffee", () -> new CoffeeHouse(Integer.MAX_VALUE) {
            @Override
            protected ActorRef createBarista() {
                return getRef();
            }

            @Override
            protected ActorRef createWaiter() { //stubbing out the waiter actor to always throw exception
                return context().actorOf(Props.create(AbstractActor.class, () -> new AbstractActor() {
                    @Override
                    public Receive createReceive() {
                        return receiveBuilder().matchAny(o -> {
                            //throw new Waiter.FrustratedException(new Coffee.Akkaccino(), system.deadLetters());
                        }).build();
                    }
                }), "waiter");
            }
        });
        ActorRef waiter = expectActor(this, "/user/resend-prepare-coffee/waiter");
        waiter.tell("Blow up", ActorRef.noSender());
        expectMsgEquals(new Barista.PrepareCoffee(new Coffee.Akkaccino(), system.deadLetters()));
    }};
}
 
Example #4
Source File: AkkaAgentIntercept.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
public static Object aroundReceiveStart(final Object thiz, final Object message) {
  if (!(message instanceof TracedMessage) && LocalSpanContext.get(COMPONENT_NAME) != null) {
    LocalSpanContext.get(COMPONENT_NAME).increment();
    return message;
  }

  final Tracer tracer = GlobalTracer.get();
  final SpanBuilder spanBuilder = tracer
    .buildSpan("receive")
    .withTag(Tags.COMPONENT, COMPONENT_NAME)
    .withTag(Tags.SPAN_KIND, Tags.SPAN_KIND_CONSUMER);

  final TracedMessage<?> tracedMessage;
  if (message instanceof TracedMessage) {
    tracedMessage = (TracedMessage<?>)message;
    spanBuilder.addReference(References.FOLLOWS_FROM, tracedMessage.spanContext(tracer));
  }
  else {
    tracedMessage = null;
    spanBuilder.withTag(Tags.MESSAGE_BUS_DESTINATION, ((AbstractActor)thiz).getSelf().path().toString());
  }

  final Span span = spanBuilder.start();
  final Scope scope = tracer.activateSpan(span);

  LocalSpanContext.set(COMPONENT_NAME, span, scope);

  return tracedMessage != null ? tracedMessage.getMessage() : message;
}
 
Example #5
Source File: ActorFactoryBean.java    From akka-java-springfactory with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
private ActorRef doCreateObject() throws Exception {
	Props props;
	if (actorClass != null) {
		props = Props.create(new SpringCreator(ctx, Class.forName(actorClass), args));
	} else if (actorBeanName != null && actorBeanClass != null) {
		props = SpringProps.create(actorSystem, actorBeanName, (Class<? extends AbstractActor>) Class.forName(actorBeanClass));
	} else if (actorBeanClass != null) {
		props = SpringProps.create(actorSystem, (Class<? extends AbstractActor>) Class.forName(actorBeanClass));
	} else {
		props = SpringProps.create(actorSystem, actorBeanName);
	}

	if (props == null) {
		throw new BeanCreationException("Can not create ActorRef for given parameters, actorClass=" + actorClass + ", actorBeanClass=" + actorBeanClass + ", actorBeanName=" + actorBeanName);
	}

	if (routerConfig != null) {
		props = props.withRouter(routerConfig);
	}
	if (deploy != null) {
		props = props.withDeploy(deploy);
	}
	if (mailbox != null) {
		props = props.withMailbox(mailbox);
	}
	if (dispatcher != null) {
		props = props.withDispatcher(dispatcher);
	}

	return actorSystem.actorOf(props);
}
 
Example #6
Source File: AkkaRpcService.java    From flink with Apache License 2.0 5 votes vote down vote up
private <C extends RpcEndpoint & RpcGateway> SupervisorActor.ActorRegistration registerAkkaRpcActor(C rpcEndpoint) {
	final Class<? extends AbstractActor> akkaRpcActorType;

	if (rpcEndpoint instanceof FencedRpcEndpoint) {
		akkaRpcActorType = FencedAkkaRpcActor.class;
	} else {
		akkaRpcActorType = AkkaRpcActor.class;
	}

	synchronized (lock) {
		checkState(!stopped, "RpcService is stopped");

		final SupervisorActor.StartAkkaRpcActorResponse startAkkaRpcActorResponse = SupervisorActor.startAkkaRpcActor(
			supervisor.getActor(),
			actorTerminationFuture -> Props.create(
				akkaRpcActorType,
				rpcEndpoint,
				actorTerminationFuture,
				getVersion(),
				configuration.getMaximumFramesize()),
			rpcEndpoint.getEndpointId());

		final SupervisorActor.ActorRegistration actorRegistration = startAkkaRpcActorResponse.orElseThrow(cause -> new AkkaRpcRuntimeException(
			String.format("Could not create the %s for %s.",
				AkkaRpcActor.class.getSimpleName(),
				rpcEndpoint.getEndpointId()),
			cause));

		actors.put(actorRegistration.getActorRef(), rpcEndpoint);

		return actorRegistration;
	}
}
 
Example #7
Source File: SafeRecovery.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Creates a Receive for recovery such that exceptions are logged as warnings
 * and not thrown. Recovery messages causing exceptions have no effect.
 *
 * @param log The Akka logger to write warnings to.
 * @param receiveRecover The Receive to wrap around.
 *
 * @return the created Receive.
 */
public static AbstractActor.Receive wrapReceive(
        @Nullable final DiagnosticLoggingAdapter log,
        @Nonnull final AbstractActor.Receive receiveRecover) {
    return ReceiveBuilder.create().matchAny(x -> {
        try {
            receiveRecover.onMessage().apply(x);
        } catch (final Exception error) {
            if (log != null) {
                log.warning("Failed to recover from the following message (it is ignored): {}", x);
            }
        }
    }).build();
}
 
Example #8
Source File: ModifyConfigBehavior.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Injectable behavior to handle {@code ModifyConfig}.
 *
 * @return behavior to handle {@code ModifyConfig}.
 */
default AbstractActor.Receive modifyConfigBehavior() {
    return ReceiveBuilder.create()
            .match(ModifyConfig.class, cmd -> {
                final Config newConfig = setConfig(ConfigFactory.parseString(cmd.getConfig().toString()));
                final JsonObject newConfigJson =
                        JsonObject.of(newConfig.root().render(ConfigRenderOptions.concise()));
                final ModifyConfigResponse response =
                        ModifyConfigResponse.of(newConfigJson, cmd.getDittoHeaders());
                sender().tell(response, self());
            })
            .build();
}
 
Example #9
Source File: AbstractHttpRequestActor.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public AbstractActor.Receive createReceive() {
    return ReceiveBuilder.create()
            .match(Status.Failure.class, failure -> {
                Throwable cause = failure.cause();
                if (cause instanceof JsonRuntimeException) {
                    // wrap JsonRuntimeExceptions
                    cause = new DittoJsonException((RuntimeException) cause);
                }
                if (cause instanceof DittoRuntimeException) {
                    handleDittoRuntimeException((DittoRuntimeException) cause);
                } else if (cause instanceof EntityStreamSizeException) {
                    logger.warning("Got EntityStreamSizeException when a 'Command' was expected which means that" +
                            " the max. allowed http payload size configured in Akka was overstepped in this" +
                            " request.");
                    completeWithResult(
                            HttpResponse.create().withStatus(HttpStatusCode.REQUEST_ENTITY_TOO_LARGE.toInt()));
                } else {
                    logger.error(cause, "Got unknown Status.Failure when a 'Command' was expected.");
                    completeWithResult(
                            HttpResponse.create().withStatus(HttpStatusCode.INTERNAL_SERVER_ERROR.toInt()));
                }
            })
            .match(Whoami.class, this::handleWhoami)
            .match(DittoRuntimeException.class, this::handleDittoRuntimeException)
            .match(ReceiveTimeout.class,
                    receiveTimeout -> handleDittoRuntimeException(GatewayServiceUnavailableException.newBuilder()
                            .dittoHeaders(DittoHeaders.empty())
                            .build()))
            .match(Command.class, command -> !isResponseRequired(command), this::handleCommandWithoutResponse)
            .match(ThingModifyCommand.class, this::handleThingModifyCommand)
            .match(MessageCommand.class, this::handleMessageCommand)
            .match(Command.class, command -> handleCommandWithResponse(command,
                    getResponseAwaitingBehavior(getTimeoutExceptionSupplier(command))))
            .matchAny(m -> {
                logger.warning("Got unknown message, expected a 'Command': {}", m);
                completeWithResult(HttpResponse.create().withStatus(HttpStatusCode.INTERNAL_SERVER_ERROR.toInt()));
            })
            .build();
}
 
Example #10
Source File: BackOffActor.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public AbstractActor.Receive createReceive() {
    return ReceiveBuilder.create()
            .match(BackOffWithAnswer.class, this::backOff)
            .match(BackOffWithSender.class, this::afterBackOff)
            .matchEquals(IsInBackOff.INSTANCE, this::handleIsInBackOff)
            .matchEquals(RESET_BACK_OFF, this::resetBackOff)
            .matchAny(m -> {
                log.warning("Unknown message: {}", m);
                unhandled(m);
            })
            .build();
}
 
Example #11
Source File: SpringProps.java    From akka-java-springfactory with MIT License 4 votes vote down vote up
public static Props create(ActorSystem actorSystem, String actorBeanName, Class<? extends AbstractActor> requiredType) {
    return SpringExtension.instance().get(actorSystem).create(actorBeanName, requiredType);
}
 
Example #12
Source File: SpringProps.java    From akka-java-springfactory with MIT License 4 votes vote down vote up
public static Props create(ActorSystem actorSystem, Class<? extends AbstractActor> requiredType) {
    return SpringExtension.instance().get(actorSystem).create(requiredType);
}
 
Example #13
Source File: Akka.java    From requirementsascode with Apache License 2.0 4 votes vote down vote up
static <T> ActorRef spawn(String actorName, ActorSystem system, Class<? extends AbstractActor> actorClass) {
	Props props = Props.create(actorClass);
	return system.actorOf(props, actorName);
}
 
Example #14
Source File: PolicyPersistenceActorTest.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void checkForActivityOfNonexistentPolicy() {
    new TestKit(actorSystem) {
        {
            // GIVEN: a PolicyPersistenceActor is created in a parent that forwards all messages to us
            final PolicyId policyId = PolicyId.of("test.ns", "nonexistent.policy");
            final Props persistentActorProps =
                    PolicyPersistenceActor.props(policyId, new PolicyMongoSnapshotAdapter(), pubSubMediator);

            final TestProbe errorsProbe = TestProbe.apply(actorSystem);

            final Props parentProps = Props.create(Actor.class, () -> new AbstractActor() {

                @Override
                public void preStart() {
                    getContext().actorOf(persistentActorProps);
                }

                @Override
                public SupervisorStrategy supervisorStrategy() {
                    return new OneForOneStrategy(true,
                            DeciderBuilder.matchAny(throwable -> {
                                errorsProbe.ref().tell(throwable, getSelf());
                                return SupervisorStrategy.restart();
                            }).build());
                }

                @Override
                public Receive createReceive() {
                    return ReceiveBuilder.create()
                            .matchAny(message -> {
                                if (getTestActor().equals(getSender())) {
                                    getContext().actorSelection(getSelf().path().child("*"))
                                            .forward(message, getContext());
                                } else {
                                    getTestActor().forward(message, getContext());
                                }
                            })
                            .build();
                }
            });

            // WHEN: CheckForActivity is sent to a persistence actor of nonexistent policy after startup
            final ActorRef underTest = actorSystem.actorOf(parentProps);

            final Object checkForActivity = AbstractShardedPersistenceActor.checkForActivity(1L);
            underTest.tell(checkForActivity, getRef());
            underTest.tell(checkForActivity, getRef());
            underTest.tell(checkForActivity, getRef());

            // THEN: persistence actor requests shutdown
            expectMsg(PolicySupervisorActor.Control.PASSIVATE);

            // THEN: persistence actor should not throw anything.
            errorsProbe.expectNoMessage(scala.concurrent.duration.Duration.create(3, TimeUnit.SECONDS));
        }
    };
}
 
Example #15
Source File: ConnectionPersistenceActorTest.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void forwardSearchCommands() {
    new TestKit(actorSystem) {{
        final ConnectionId myConnectionId = ConnectionId.of(UUID.randomUUID().toString());
        final TestProbe clientActorsProbe = TestProbe.apply("clientActors", actorSystem);
        final TestProbe conciergeForwarderProbe = TestProbe.apply("conciergeForwarder", actorSystem);
        // Mock the client actors so that they forward all signals to clientActorsProbe with their own reference
        final ClientActorPropsFactory propsFactory = (a, b, c) -> Props.create(AbstractActor.class, () ->
                new AbstractActor() {
                    @Override
                    public Receive createReceive() {
                        return ReceiveBuilder.create()
                                .match(WithDittoHeaders.class, message ->
                                        clientActorsProbe.ref()
                                                .tell(WithSender.of(message, getSelf()), getSender())
                                )
                                .build();
                    }
                });
        final DittoProtocolSub dittoProtocolSub = Mockito.mock(DittoProtocolSub.class);
        when(dittoProtocolSub.subscribe(any(), any(), any())).thenReturn(CompletableFuture.completedStage(null));
        final Props connectionActorProps = Props.create(ConnectionPersistenceActor.class, () ->
                new ConnectionPersistenceActor(myConnectionId, dittoProtocolSub, conciergeForwarderProbe.ref(),
                        propsFactory, null, 999
                ));

        // GIVEN: connection persistence actor created with 2 client actors that are allowed to start on same node
        final ActorRef underTest = actorSystem.actorOf(connectionActorProps, myConnectionId.toString());
        underTest.tell(createClosedConnectionWith2Clients, getRef());
        expectMsgClass(CreateConnectionResponse.class);
        underTest.tell(OpenConnection.of(myConnectionId, DittoHeaders.empty()), getRef());
        assertThat(clientActorsProbe.expectMsgClass(WithSender.class).getMessage())
                .isInstanceOf(OpenConnection.class);
        clientActorsProbe.reply(new Status.Success("connected"));
        expectMsgClass(OpenConnectionResponse.class);

        // WHEN: 2 CreateSubscription commands are received
        // THEN: The 2 commands land in different client actors
        underTest.tell(CreateSubscription.of(DittoHeaders.empty()), getRef());
        underTest.tell(CreateSubscription.of(DittoHeaders.empty()), getRef());
        final WithSender<?> createSubscription1 = clientActorsProbe.expectMsgClass(WithSender.class);
        final WithSender<?> createSubscription2 = clientActorsProbe.expectMsgClass(WithSender.class);
        assertThat(createSubscription1.getSender()).isNotEqualTo(createSubscription2.getSender());

        // WHEN: RequestSubscription command is sent with the prefix of a received CreateSubscription command
        // THEN: The command lands in the same client actor
        final String subscriptionId1 =
                ((CreateSubscription) createSubscription1.getMessage()).getPrefix().orElseThrow() + "-suffix";
        underTest.tell(RequestFromSubscription.of(subscriptionId1, 99L, DittoHeaders.empty()), getRef());
        final WithSender<?> requestSubscription1 = clientActorsProbe.expectMsgClass(WithSender.class);
        assertThat(requestSubscription1.getMessage()).isInstanceOf(RequestFromSubscription.class);
        assertThat(requestSubscription1.getSender()).isEqualTo(createSubscription1.getSender());

        // Same for CancelSubscription
        final String subscriptionId2 =
                ((CreateSubscription) createSubscription2.getMessage()).getPrefix().orElseThrow() + "-suffix";
        underTest.tell(CancelSubscription.of(subscriptionId2, DittoHeaders.empty()), getRef());
        final WithSender<?> cancelSubscription2 = clientActorsProbe.expectMsgClass(WithSender.class);
        assertThat(cancelSubscription2.getSender()).isEqualTo(createSubscription2.getSender());
    }};
}
 
Example #16
Source File: Reaper.java    From akka-tutorial with Apache License 2.0 4 votes vote down vote up
public static void watchWithDefaultReaper(AbstractActor actor) {
	ActorSelection defaultReaper = actor.getContext().getSystem().actorSelection("/user/" + DEFAULT_NAME);
	defaultReaper.tell(new WatchMeMessage(), actor.getSelf());
}
 
Example #17
Source File: Reaper.java    From akka-tutorial with Apache License 2.0 4 votes vote down vote up
public static void watchWithDefaultReaper(AbstractActor actor) {
	ActorSelection defaultReaper = actor.getContext().getSystem().actorSelection("/user/" + DEFAULT_NAME);
	defaultReaper.tell(new WatchMeMessage(), actor.getSelf());
}
 
Example #18
Source File: SpringExtension.java    From akka-java-springfactory with MIT License 2 votes vote down vote up
/**
 * Create a Props for the specified actorBeanName using the
 * SpringActorProducer class.
 *
 * @param actorBeanName The name of the actor bean to create Props for
 * @param requiredType  Type of the actor bean must match. Can be an interface or superclass
 *                      of the actual class, or {@code null} for any match. For example, if the value
 *                      is {@code Object.class}, this method will succeed whatever the class of the
 *                      returned instance.
 * @return a Props that will create the actor bean using Spring
 */
public Props create(String actorBeanName, Class<? extends AbstractActor> requiredType) {
    return Props.create(SpringActorProducer.class,
            applicationContext, actorBeanName, requiredType);
}
 
Example #19
Source File: Reaper.java    From akka-tutorial with Apache License 2.0 2 votes vote down vote up
/**
 * Find the reaper actor of this actor system and let it watch the given actor.
 *
 * @param actor the actor to be watched
 * @see #DEFAULT_NAME the name of the default reaper
 */
public static void watchWithDefaultReaper(AbstractActor actor) {
	ActorSelection defaultReaper = actor.getContext().getSystem().actorSelection("/user/" + DEFAULT_NAME);
	defaultReaper.tell(new WatchMeMessage(), actor.getSelf());
}
 
Example #20
Source File: SpringExtension.java    From spring-boot-akka-event-sourcing-starter with Apache License 2.0 2 votes vote down vote up
/**
 * Create a Props for the specified actorBeanName using the SpringActorProducer class.
 *
 * @param actorBeanName The name of the actor bean to create Props for
 * @param requiredType  Type of the actor bean must match. Can be an interface or superclass of the actual class,
 *                      or {@code null} for any match. For example, if the value is {@code Object.class}, this method will succeed
 *                      whatever the class of the returned instance.
 * @return a Props that will create the actor bean using Spring
 */
public Props props(String actorBeanName, Class<? extends AbstractActor> requiredType) {
	return Props.create(SpringActorProducer.class, applicationContext, actorBeanName, requiredType);
}