akka.pattern.Patterns Java Examples

The following examples show how to use akka.pattern.Patterns. 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: ByRoundTripSignalEnrichmentFacade.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public CompletionStage<JsonObject> retrievePartialThing(final ThingId thingId,
        final JsonFieldSelector jsonFieldSelector,
        final DittoHeaders dittoHeaders,
        @Nullable final Signal<?> concernedSignal) {

    if (concernedSignal instanceof ThingDeleted && !(ProtocolAdapter.isLiveSignal(concernedSignal))) {
        // twin deleted events should not be enriched, return empty JsonObject
        return CompletableFuture.completedFuture(JsonObject.empty());
    }

    // remove channel header to prevent looping on live messages
    final DittoHeaders headersWithoutChannel = dittoHeaders.toBuilder().channel(null).build();

    final RetrieveThing command =
            RetrieveThing.getBuilder(thingId, headersWithoutChannel)
                    .withSelectedFields(jsonFieldSelector)
                    .build();

    final CompletionStage<Object> askResult = Patterns.ask(commandHandler, command, askTimeout);

    return askResult.thenCompose(ByRoundTripSignalEnrichmentFacade::extractPartialThing);
}
 
Example #2
Source File: MesosResourceManager.java    From flink with Apache License 2.0 6 votes vote down vote up
/**
 * Tries to shut down the given actor gracefully.
 *
 * @param actorRef specifying the actor to shut down
 * @param timeout  for the graceful shut down
 * @return A future that finishes with {@code true} iff. the actor could be stopped gracefully
 * or {@code actorRef} was {@code null}.
 */
private CompletableFuture<Boolean> stopActor(@Nullable final ActorRef actorRef, FiniteDuration timeout) {
	if (actorRef == null) {
		return CompletableFuture.completedFuture(true);
	}

	return FutureUtils.toJava(Patterns.gracefulStop(actorRef, timeout))
		.exceptionally(
			(Throwable throwable) -> {
				// The actor did not stop gracefully in time, try to directly stop it
				actorSystem.stop(actorRef);

				log.warn("Could not stop actor {} gracefully.", actorRef.path(), throwable);

				return false;
			}
		);
}
 
Example #3
Source File: ArticleParseClusterClient.java    From learning-akka with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    Timeout timeout = new Timeout(Duration.create(5, "seconds"));

    ActorSystem system = ActorSystem.create("clientSystem");

    Set<ActorSelection> initialContacts = new HashSet<ActorSelection>();
    initialContacts.add(system.actorSelection("akka.tcp://[email protected]:2552/user/receptionist"));
    initialContacts.add(system.actorSelection("akka.tcp://[email protected]:2551/user/receptionist"));

    ActorRef receptionist = system.actorOf(ClusterClient.defaultProps(initialContacts));

    ClusterClient.Send msg = new ClusterClient.Send("/user/workers", articleToParse, false);

    Future f = Patterns.ask(receptionist, msg, timeout);
    String result = (String) Await.result(f, timeout.duration());
    System.out.println("result: " + result);
}
 
Example #4
Source File: FencedAkkaInvocationHandler.java    From flink with Apache License 2.0 6 votes vote down vote up
@Override
public <V> CompletableFuture<V> callAsyncWithoutFencing(Callable<V> callable, Time timeout) {
	checkNotNull(callable, "callable");
	checkNotNull(timeout, "timeout");

	if (isLocal) {
		@SuppressWarnings("unchecked")
		CompletableFuture<V> resultFuture = (CompletableFuture<V>) FutureUtils.toJava(
			Patterns.ask(
				getActorRef(),
				new UnfencedMessage<>(new CallAsync(callable)),
				timeout.toMilliseconds()));

		return resultFuture;
	} else {
		throw new RuntimeException("Trying to send a Runnable to a remote actor at " +
			getActorRef().path() + ". This is not supported.");
	}
}
 
Example #5
Source File: KafkaSagaEventConsumer.java    From servicecomb-pack with Apache License 2.0 6 votes vote down vote up
private CompletionStage<String> sendSagaActor(BaseEvent event) {
  try {
    long begin = System.currentTimeMillis();
    metricsService.metrics().doActorReceived();
    // Use the synchronous method call to ensure that Kafka's Offset is set after the delivery is successful.
    Timeout timeout = new Timeout(Duration.create(10, "seconds"));
    Future<Object> future = Patterns.ask(sagaShardRegionActor, event, timeout);
    Await.result(future, timeout.duration());
    long end = System.currentTimeMillis();
    metricsService.metrics().doActorAccepted();
    metricsService.metrics().doActorAvgTime(end - begin);
    return CompletableFuture.completedFuture("OK");
  } catch (Exception ex) {
    LOG.error(ex.getMessage(),ex);
    metricsService.metrics().doActorRejected();
    throw new CompletionException(ex);
  }
}
 
Example #6
Source File: NoPolTask.java    From nopol with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void run(@NotNull ProgressIndicator progressIndicator) {
	if (ActorManager.runNopolLocally && !ActorManager.nopolIsRunning) {
		ActorManager.launchNopol();
	}
	Timeout timeout = new Timeout(scala.concurrent.duration.Duration.fromNanos(20*1000000000));// nano = 10^9
	EventSender.send(EventSender.Event.REPAIR_ATTEMPT);
	try {
		ConfigActor configActor = new ConfigActorImpl(nopolContext, Files.readAllBytes(Paths.get(outputZip)));
		this.future = Patterns.ask(ActorManager.remoteActor, configActor, timeout);
		if (Plugin.enableFancyRobot) {
			ApplicationManager.getApplication().invokeLater(runnerFancyRobot);
		}
		this.response = Await.result(future, timeout.duration());
	} catch (Exception e) {
		onError(e);
	}
}
 
Example #7
Source File: UdpWorkerTest.java    From parallec with Apache License 2.0 6 votes vote down vote up
@Test
public void testUdpWorkerBadMsgTypeDefaultType() {
    
    logger.info("IN testUdpWorkerBadMsgTypeDefaultType");
    ActorRef asyncWorker = null;
    try {
        // made a timeout
        int actorMaxOperationTimeoutSec = 15;
        asyncWorker = ActorConfig.createAndGetActorSystem().actorOf(
                Props.create(UdpWorker.class, actorMaxOperationTimeoutSec,
                        getUdpMetaSample(), LOCALHOST));
        
        final FiniteDuration duration = Duration.create(20,
                TimeUnit.SECONDS);
        Future<Object> future = Patterns
                .ask(asyncWorker, RequestWorkerMsgType.CHECK_FUTURE_STATE,
                        new Timeout(duration));
        ResponseOnSingeRequest response = (ResponseOnSingeRequest) Await
                .result(future, duration);

        logger.info("\nWorker response:" + response.toString());
    } catch (Throwable ex) {

        logger.error("Exception in test : " + ex);
    }
}
 
Example #8
Source File: InterServiceCommunicationImpl.java    From sunbird-lms-service with MIT License 6 votes vote down vote up
@Override
public Future<Object> getFuture(ActorRef actorRef, Request request) {
  if (null == actorRef) {
    ProjectLogger.log(
        "InterServiceCommunicationImpl:getFuture: actorRef is null", LoggerEnum.INFO);
    ProjectCommonException.throwServerErrorException(
        ResponseCode.unableToCommunicateWithActor,
        ResponseCode.unableToCommunicateWithActor.getErrorMessage());
  }
  try {
    return Patterns.ask(actorRef, request, t);
  } catch (Exception e) {
    ProjectLogger.log(
        "InterServiceCommunicationImpl:getFuture: Exception occured with error message = "
            + e.getMessage(),
        e);
    ProjectCommonException.throwServerErrorException(
        ResponseCode.unableToCommunicateWithActor,
        ResponseCode.unableToCommunicateWithActor.getErrorMessage());
  }
  return null;
}
 
Example #9
Source File: PersistenceIdSource.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
private static Source<EntityIdWithRevision, NotUsed> buildResumeSource(final PersistenceIdsConfig config,
        final ActorRef pubSubMediator,
        final String path) {

    final EntityIdWithRevision emptyLowerBound = new EmptyEntityIdWithRevision();

    final Function<EntityIdWithRevision, Source<EntityIdWithRevision, ?>> resumptionFunction =
            seed -> Source.single(requestStreamCommand(config, path, seed))
                    .mapAsync(1, command ->
                            Patterns.ask(pubSubMediator, command, config.getStreamRequestTimeout())
                                    .handle((result, error) -> Tuple3.create(command, result, error)))
                    .flatMapConcat(PersistenceIdSource::checkForErrors)
                    .flatMapConcat(PersistenceIdSource::handleSourceRef);

    final Function<List<EntityIdWithRevision>, EntityIdWithRevision> nextSeedFunction =
            finalElements -> finalElements.isEmpty()
                    ? emptyLowerBound
                    : finalElements.get(finalElements.size() - 1);

    // nextSeedFunction needs the last 1 element only.
    final int lookBehind = 1;

    return ResumeSource.onFailureWithBackoff(config.getMinBackoff(), config.getMaxBackoff(),
            config.getMaxRestarts(), config.getRecovery(), emptyLowerBound, resumptionFunction, lookBehind,
            nextSeedFunction);
}
 
Example #10
Source File: ThingCommandEnforcement.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Retrieve for response of a query command and limit the response according to a policy enforcer.
 *
 * @param commandWithReadSubjects the command to ask.
 * @param enforcer enforcer to build JsonView with.
 * @return always {@code true}.
 */
private CompletionStage<WithDittoHeaders> askThingsShardRegionAndBuildJsonView(
        final ThingQueryCommand commandWithReadSubjects, final Enforcer enforcer) {

    return Patterns.ask(thingsShardRegion, commandWithReadSubjects, getAskTimeout())
            .handle((response, error) -> {
                if (response instanceof ThingQueryCommandResponse) {
                    return reportJsonViewForThingQuery((ThingQueryCommandResponse) response, enforcer);
                } else if (response instanceof DittoRuntimeException) {
                    return (DittoRuntimeException) response;
                } else if (isAskTimeoutException(response, error)) {
                    final AskTimeoutException askTimeoutException = error instanceof AskTimeoutException
                            ? (AskTimeoutException) error
                            : (AskTimeoutException) response;
                    return reportTimeoutForThingQuery(commandWithReadSubjects, askTimeoutException);
                } else if (error != null) {
                    return reportUnexpectedError("before building JsonView", error);
                } else {
                    return reportUnknownResponse("before building JsonView", response);
                }
            });
}
 
Example #11
Source File: PingWorkerTest.java    From parallec with Apache License 2.0 6 votes vote down vote up
@Test
public void testTcpWorkerBadMsgType() {
    
    logger.info("IN testTcpWorkerBadMsgType");
    ActorRef asyncWorker = null;
    try {
        int actorMaxOperationTimeoutSec = 15;
        asyncWorker = ActorConfig.createAndGetActorSystem().actorOf(
                Props.create(PingWorker.class, actorMaxOperationTimeoutSec,
                        getPingMetaSample(), "www.google.com"));

        final FiniteDuration duration = Duration.create(20,
                TimeUnit.SECONDS);
        Future<Object> future = Patterns
                .ask(asyncWorker, new Integer(0),
                        new Timeout(duration));
        ResponseOnSingeRequest response = (ResponseOnSingeRequest) Await
                .result(future, duration);

        logger.info("\nWorker response:" + response.toString());
    } catch (Throwable ex) {

        logger.error("Exception in test : " + ex);
    }
}
 
Example #12
Source File: ThingCommandEnforcement.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
private CompletionStage<Policy> retrievePolicyWithEnforcement(final PolicyId policyId) {
    final Map<String, String> enhancedMap = new HashMap<>(dittoHeaders());
    enhancedMap.put(AbstractGraphActor.DITTO_INTERNAL_SPECIAL_ENFORCEMENT_LANE, "true");
    final DittoHeaders adjustedHeaders = DittoHeaders.of(enhancedMap);

    return Patterns.ask(conciergeForwarder(), RetrievePolicy.of(policyId, adjustedHeaders), getAskTimeout())
            .thenApply(response -> {
                if (response instanceof RetrievePolicyResponse) {
                    return ((RetrievePolicyResponse) response).getPolicy();
                } else if (response instanceof PolicyErrorResponse) {
                    throw ((PolicyErrorResponse) response).getDittoRuntimeException();
                } else if (response instanceof DittoRuntimeException) {
                    throw (DittoRuntimeException) response;
                } else {
                    log().error(
                            "Got an unexpected response while retrieving a Policy that should be copied" +
                                    " during Thing creation: {}", response);
                    throw GatewayInternalErrorException.newBuilder().build();
                }
            });

}
 
Example #13
Source File: MesosResourceManager.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
/**
 * Tries to shut down the given actor gracefully.
 *
 * @param actorRef specifying the actor to shut down
 * @param timeout  for the graceful shut down
 * @return A future that finishes with {@code true} iff. the actor could be stopped gracefully
 * or {@code actorRef} was {@code null}.
 */
private CompletableFuture<Boolean> stopActor(@Nullable final ActorRef actorRef, FiniteDuration timeout) {
	if (actorRef == null) {
		return CompletableFuture.completedFuture(true);
	}

	return FutureUtils.toJava(Patterns.gracefulStop(actorRef, timeout))
		.exceptionally(
			(Throwable throwable) -> {
				// The actor did not stop gracefully in time, try to directly stop it
				actorSystem.stop(actorRef);

				log.warn("Could not stop actor {} gracefully.", actorRef.path(), throwable);

				return false;
			}
		);
}
 
Example #14
Source File: AbstractStreamingActor.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
private void startStreaming(final C command) {
    log.debug("Starting streaming due to command: {}", command);
    final int burst = getBurst(command);
    final Duration initialTimeout = getInitialTimeout(command);
    final Duration idleTimeout = getIdleTimeout(command);

    final CompletionStage<SourceRef<Object>> sourceRef =
            createSource(command)
                    .grouped(burst)
                    .map(this::batchMessages)
                    .initialTimeout(initialTimeout)
                    .idleTimeout(idleTimeout)
                    .runWith(StreamRefs.sourceRef(), materializer);

    Patterns.pipe(sourceRef, getContext().getDispatcher()).to(getSender());
}
 
Example #15
Source File: ActorAskCacheLoader.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public final CompletableFuture<Entry<V>> asyncLoad(final EntityIdWithResourceType key, final Executor executor) {
    final String resourceType = key.getResourceType();
    // provide correlation id to inner thread
    final Optional<String> correlationId = LogUtil.getCorrelationId();
    return CompletableFuture.supplyAsync(() -> {
        LogUtil.enhanceLogWithCorrelationId(correlationId);
        final EntityId entityId = key.getId();
        return getCommand(resourceType, entityId, key.getCacheLookupContext().orElse(null));
    }, executor).thenCompose(command -> {
        final ActorRef entityRegion = getEntityRegion(key.getResourceType());
        LOGGER.debug("Going to retrieve cache entry for key <{}> with command <{}>: ", key, command);
        return Patterns.ask(entityRegion, command, askTimeout)
                .thenApply(response -> transformResponse(
                        resourceType, response, key.getCacheLookupContext().orElse(null)))
                .toCompletableFuture();
    });
}
 
Example #16
Source File: PingWorkerTest.java    From parallec with Apache License 2.0 6 votes vote down vote up
@Test
public void testSlowAndPollProgress() {
    ActorRef asyncWorker = null;
    try {
        int actorMaxOperationTimeoutSec = 15;
        asyncWorker = ActorConfig.createAndGetActorSystem().actorOf(
                Props.create(PingWorker.class, actorMaxOperationTimeoutSec,
                        getPingMetaSample(), "www.google.com"));

        final FiniteDuration duration = Duration.create(20,
                TimeUnit.SECONDS);
        Future<Object> future = Patterns
                .ask(asyncWorker, RequestWorkerMsgType.PROCESS_REQUEST,
                        new Timeout(duration));

        ResponseOnSingeRequest response = (ResponseOnSingeRequest) Await
                .result(future, duration);

        logger.info("\nWorker response:" + response.toString());
    } catch (Throwable ex) {

        logger.error("Exception in test : " + ex);
    }
}
 
Example #17
Source File: BackgroundSyncStream.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
private Source<Metadata, NotUsed> retrievePolicyRevisionAndEmitMismatch(final PolicyId policyId,
        final Metadata indexed) {
    final SudoRetrievePolicyRevision command =
            SudoRetrievePolicyRevision.of(policyId, DittoHeaders.empty());
    final CompletionStage<Source<Metadata, NotUsed>> sourceCompletionStage =
            Patterns.ask(policiesShardRegion, command, policiesAskTimeout)
                    .handle((response, error) -> {
                        if (error != null) {
                            return Source.single(error)
                                    .log("ErrorRetrievingPolicyRevision " + policyId)
                                    .map(e -> indexed);
                        } else if (response instanceof SudoRetrievePolicyRevisionResponse) {
                            final long revision = ((SudoRetrievePolicyRevisionResponse) response).getRevision();
                            return indexed.getPolicyRevision()
                                    .filter(indexedPolicyRevision -> indexedPolicyRevision.equals(revision))
                                    .map(indexedPolicyRevision -> Source.<Metadata>empty())
                                    .orElseGet(() -> Source.single(indexed).log("PolicyRevisionMismatch"));
                        } else {
                            return Source.single(response)
                                    .log("UnexpectedPolicyResponse")
                                    .map(r -> indexed);
                        }
                    });
    return Source.fromSourceCompletionStage(sourceCompletionStage)
            .mapMaterializedValue(ignored -> NotUsed.getInstance());
}
 
Example #18
Source File: EnforcementFlow.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
private Source<SudoRetrieveThingResponse, NotUsed> sudoRetrieveThing(final ThingId thingId) {
    final SudoRetrieveThing command =
            SudoRetrieveThing.withOriginalSchemaVersion(thingId, DittoHeaders.empty());
    final CompletionStage<Source<SudoRetrieveThingResponse, NotUsed>> responseFuture =
            // using default thread-pool for asking Things shard region
            Patterns.ask(thingsShardRegion, command, thingsTimeout)
                    .handle((response, error) -> {
                        if (response instanceof SudoRetrieveThingResponse) {
                            return Source.single((SudoRetrieveThingResponse) response);
                        } else {
                            if (error != null) {
                                log.error("Failed " + command, error);
                            } else if (!(response instanceof ThingNotAccessibleException)) {
                                log.error("Unexpected response for <{}>: <{}>", command, response);
                            }
                            return Source.empty();
                        }
                    });

    return Source.fromSourceCompletionStage(responseFuture)
            .viaMat(Flow.create(), Keep.none());
}
 
Example #19
Source File: PolicyCommandEnforcement.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
private CompletionStage<WithDittoHeaders> askPoliciesShardRegionAndBuildJsonView(
        final PolicyQueryCommand commandWithReadSubjects,
        final Enforcer enforcer) {

    return Patterns.ask(policiesShardRegion, commandWithReadSubjects, getAskTimeout())
            .handle((response, error) -> {
                if (response instanceof PolicyQueryCommandResponse) {
                    return reportJsonViewForPolicyQuery((PolicyQueryCommandResponse<?>) response, enforcer);
                } else if (response instanceof DittoRuntimeException) {
                    throw (DittoRuntimeException) response;
                } else if (isAskTimeoutException(response, error)) {
                    throw reportTimeoutForPolicyQuery(commandWithReadSubjects, (AskTimeoutException) response);
                } else if (error != null) {
                    throw reportUnexpectedError("before building JsonView", error);
                } else {
                    throw reportUnknownResponse("before building JsonView", response);
                }
            });
}
 
Example #20
Source File: ThingCommandEnforcement.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
private CompletionStage<CreateThing> createPolicyAndThing(final CreatePolicy createPolicy,
        final CreateThing createThingWithoutPolicyId) {

    final CreateThing createThing = CreateThing.of(
            createThingWithoutPolicyId.getThing().setPolicyId(createPolicy.getEntityId()),
            null,
            createThingWithoutPolicyId.getDittoHeaders());

    invalidatePolicyCache(createPolicy.getEntityId());
    return preEnforcer.apply(createPolicy)
            .thenCompose(msg -> Patterns.ask(policiesShardRegion, msg, getAskTimeout()))
            .thenApply(policyResponse -> {
                handlePolicyResponseForCreateThing(createPolicy, createThing, policyResponse);

                invalidateThingCaches(createThing.getThingEntityId());

                return createThing;
            });
}
 
Example #21
Source File: ThingCommandEnforcement.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Retrieve inlined policy after retrieving a thing. Do not report errors.
 *
 * @param retrieveThing the original command.
 * @param retrievePolicy the command to retrieve the thing's policy.
 * @return future response from policies-shard-region.
 */
private CompletionStage<Optional<RetrievePolicyResponse>> retrieveInlinedPolicyForThing(
        final RetrieveThing retrieveThing, final RetrievePolicy retrievePolicy) {

    return preEnforcer.apply(retrievePolicy)
            .thenCompose(msg -> Patterns.ask(policiesShardRegion, msg, getAskTimeout()))
            .handle((response, error) -> {
                LOGGER.debug("Response of policiesShardRegion: <{}>", response);
                if (response instanceof RetrievePolicyResponse) {
                    return Optional.of((RetrievePolicyResponse) response);
                } else if (error != null) {
                    log(error).error(error, "retrieving inlined policy after RetrieveThing");
                } else {
                    log(response).info(
                            "No authorized response when retrieving inlined policy <{}> for thing <{}>: {}",
                            retrievePolicy.getEntityId(), retrieveThing.getThingEntityId(), response);
                }
                return Optional.empty();
            });
}
 
Example #22
Source File: ConnectionPersistenceActor.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private CompletionStage<Object> broadcastToClientActorsIfStarted(final Command<?> cmd) {
    if (clientActorRouter != null && entity != null) {
        // wrap in Broadcast message because these management messages must be delivered to each client actor
        final Broadcast broadcast = new Broadcast(cmd);
        return processClientAskResult(Patterns.ask(clientActorRouter, broadcast, clientActorAskTimeout));
    } else {
        return CompletableFuture.completedFuture(null);
    }
}
 
Example #23
Source File: UdpWorkerTest.java    From parallec with Apache License 2.0 5 votes vote down vote up
@Test
public void testUdpWorkerDupAndCancel() {
    ActorRef asyncWorker = null;
    logger.info("IN testUdpWorkerDupAndCancel");
    try {
        
        // Start new job
        

        int actorMaxOperationTimeoutSec = 15;
        asyncWorker = ActorConfig.createAndGetActorSystem().actorOf(
                Props.create(UdpWorker.class, actorMaxOperationTimeoutSec,
                        getUdpMetaSample(), LOCALHOST));

        final FiniteDuration duration = Duration.create(20,
                TimeUnit.SECONDS);
        Future<Object> future = Patterns
                .ask(asyncWorker, RequestWorkerMsgType.PROCESS_REQUEST,
                        new Timeout(duration));
        // test dup
        asyncWorker.tell(RequestWorkerMsgType.PROCESS_REQUEST, asyncWorker);

        // test cancel
        asyncWorker.tell(RequestWorkerMsgType.CANCEL, asyncWorker);
        ResponseOnSingeRequest response = (ResponseOnSingeRequest) Await
                .result(future, duration);

        
        logger.info("\nWorker response:" + response.toString());
        
    } catch (Throwable ex) {

        logger.error("Exception in test : " + ex);
    }
}
 
Example #24
Source File: SearchActor.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private <T extends Command> void executeCount(final T countCommand,
        final Function<T, Query> queryParseFunction,
        final boolean isSudo) {
    final DittoHeaders dittoHeaders = countCommand.getDittoHeaders();
    final Optional<String> correlationIdOpt = dittoHeaders.getCorrelationId();
    LogUtil.enhanceLogWithCorrelationId(log, correlationIdOpt);
    log.info("Processing CountThings command: {}", countCommand);
    final JsonSchemaVersion version = countCommand.getImplementedSchemaVersion();

    final String queryType = "count";

    final StartedTimer countTimer = startNewTimer(version, queryType);

    final StartedTimer queryParsingTimer = countTimer.startNewSegment(QUERY_PARSING_SEGMENT_NAME);

    final ActorRef sender = getSender();

    final Source<Object, ?> replySource = createQuerySource(queryParseFunction, countCommand)
            .flatMapConcat(query -> {
                LogUtil.enhanceLogWithCorrelationId(log, correlationIdOpt);
                stopTimer(queryParsingTimer);
                final StartedTimer databaseAccessTimer =
                        countTimer.startNewSegment(DATABASE_ACCESS_SEGMENT_NAME);

                final Source<Long, NotUsed> countResultSource = isSudo
                        ? searchPersistence.sudoCount(query)
                        : searchPersistence.count(query,
                        countCommand.getDittoHeaders().getAuthorizationContext().getAuthorizationSubjectIds());

                return processSearchPersistenceResult(countResultSource, dittoHeaders)
                        .via(Flow.fromFunction(result -> {
                            stopTimer(databaseAccessTimer);
                            return result;
                        }))
                        .map(count -> CountThingsResponse.of(count, dittoHeaders));
            })
            .via(stopTimerAndHandleError(countTimer, countCommand));

    Patterns.pipe(replySource.runWith(Sink.head(), materializer), getContext().dispatcher()).to(sender);
}
 
Example #25
Source File: AmqpClientActor.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected CompletionStage<Status.Status> doTestConnection(final Connection connection) {
    // delegate to child actor because the QPID JMS client is blocking until connection is opened/closed
    return Patterns.ask(getTestConnectionHandler(connection),
            new JmsConnect(getSender()), clientConfig.getTestingTimeout())
            // compose the disconnect because otherwise the actor hierarchy might be stopped too fast
            .thenCompose(response -> {
                log.debug("Closing JMS connection after testing connection.");
                if (response instanceof JmsConnected) {
                    final JmsConnection jmsConnection = ((JmsConnected) response).connection;
                    final JmsDisconnect jmsDisconnect = new JmsDisconnect(ActorRef.noSender(), jmsConnection);
                    return Patterns.ask(getDisconnectConnectionHandler(connection), jmsDisconnect,
                            clientConfig.getTestingTimeout())
                            // replace jmsDisconnected message with original response
                            .thenApply(jmsDisconnected -> response);
                } else {
                    return CompletableFuture.completedFuture(response);
                }
            })
            .handle((response, throwable) -> {
                if (throwable != null || response instanceof Status.Failure || response instanceof Throwable) {
                    final Throwable ex =
                            response instanceof Status.Failure ? ((Status.Failure) response).cause() :
                                    response instanceof Throwable ? (Throwable) response : throwable;
                    final ConnectionFailedException failedException =
                            ConnectionFailedException.newBuilder(connectionId())
                                    .description("The requested Connection could not be connected due to '" +
                                            ex.getClass().getSimpleName() + ": " + ex.getMessage() + "'")
                                    .cause(ex).build();
                    return new Status.Failure(failedException);
                } else if (response instanceof ConnectionFailure) {
                    return ((ConnectionFailure) response).getFailure();
                } else {
                    return new Status.Success(response);
                }
            });
}
 
Example #26
Source File: HttpWorkerTest.java    From parallec with Apache License 2.0 5 votes vote down vote up
/**
 * fake a NPE of logger; do not forget to reset it or other tests will fail.
 */
@Test
public void testHttpWorkerException() {
    ActorRef asyncWorker = null;
    try {
        // Start new job
        
        int actorMaxOperationTimeoutSec = 15;
        HttpWorker.setLogger(null);
        String urlComplete = "http://www.parallec.io/validateInternals.html";
        asyncWorker = ActorConfig.createAndGetActorSystem().actorOf(
                Props.create(HttpWorker.class, actorMaxOperationTimeoutSec,
                        HttpClientStore.getInstance()
                                .getCurrentDefaultClient(), urlComplete,
                        HttpMethod.GET, "", null,null));
        ;

        final FiniteDuration duration = Duration.create(20,
                TimeUnit.SECONDS);
        Future<Object> future = Patterns
                .ask(asyncWorker, RequestWorkerMsgType.PROCESS_REQUEST,
                        new Timeout(duration));

        ResponseOnSingeRequest response = (ResponseOnSingeRequest) Await
                .result(future, duration);

        logger.info("\nWorker response:" + response.toString());
    } catch (Throwable ex) {
        logger.error("Exception in test : " + ex);
    }
    HttpWorker.setLogger(LoggerFactory.getLogger(HttpWorker.class));
}
 
Example #27
Source File: HttpWorkerTest.java    From parallec with Apache License 2.0 5 votes vote down vote up
@Test
public void testHttpWorkerTimeoutException() {
    ActorRef asyncWorker = null;
    try {
        // Start new job
        
        // made a timeout
        int actorMaxOperationTimeoutSec = 0;
        String urlComplete = "http://www.parallec.io/validateInternals.html";
        pc.getHttpClientStore();
        asyncWorker = ActorConfig.createAndGetActorSystem().actorOf(
                Props.create(HttpWorker.class, actorMaxOperationTimeoutSec,
                        HttpClientStore.getInstance()
                                .getCurrentDefaultClient(), urlComplete,
                        HttpMethod.GET, "", null,null));

        final FiniteDuration duration = Duration.create(20,
                TimeUnit.SECONDS);
        Future<Object> future = Patterns
                .ask(asyncWorker, RequestWorkerMsgType.PROCESS_REQUEST,
                        new Timeout(duration));
        ResponseOnSingeRequest response = (ResponseOnSingeRequest) Await
                .result(future, duration);

        logger.info("\nWorker response:" + response.toString());
    } catch (Throwable ex) {

        logger.error("Exception in test : " + ex);
    }
}
 
Example #28
Source File: HttpWorkerTest.java    From parallec with Apache License 2.0 5 votes vote down vote up
@Test
public void testHttpWorkerBadMsgType() {
    ActorRef asyncWorker = null;
    try {
        String urlComplete = "http://www.parallec.io/validateInternals.html";
        pc.getHttpClientStore();
        int actorMaxOperationTimeoutSec = 0;
        asyncWorker = ActorConfig.createAndGetActorSystem().actorOf(
                Props.create(HttpWorker.class, actorMaxOperationTimeoutSec,
                        HttpClientStore.getInstance()
                                .getCurrentDefaultClient(), urlComplete,
                        HttpMethod.GET, "", null,null));

        final FiniteDuration duration = Duration.create(20,
                TimeUnit.SECONDS);
        Future<Object> future = Patterns
                .ask(asyncWorker, RequestWorkerMsgType.PROCESS_REQUEST,
                        new Timeout(duration));

        // test invalid type
        asyncWorker.tell(new Integer(0), asyncWorker);
        asyncWorker.tell(RequestWorkerMsgType.CHECK_FUTURE_STATE,
                asyncWorker);
        ResponseOnSingeRequest response = (ResponseOnSingeRequest) Await
                .result(future, duration);

        logger.info("\nWorker response:" + response.toString());
    } catch (Throwable ex) {

        logger.error("Exception in test : " + ex);
    }
    // made a timeout
}
 
Example #29
Source File: ThingsMetadataSource.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private Source<SourceRef<?>, NotUsed> requestStream(final ThingId lowerBound) {
    final Object startStreamCommand = getStartStreamCommand(lowerBound);
    return Source.fromCompletionStage(Patterns.ask(pubSubMediator, startStreamCommand, idleTimeout))
            .flatMapConcat(response -> {
                if (response instanceof SourceRef<?>) {
                    return Source.single((SourceRef<?>) response);
                } else {
                    return Source.failed(new ClassCastException("Not a SourceRef: " + response));
                }
            });
}
 
Example #30
Source File: UdpWorkerTest.java    From parallec with Apache License 2.0 5 votes vote down vote up
@Test
public void testUdpWorkerNormalCheckComplete() {
    ActorRef asyncWorker = null;
    logger.info("IN testUdpWorkerNormalCheckComplete");
    try {
        // Start new job
        

        int actorMaxOperationTimeoutSec = 15;
        asyncWorker = ActorConfig.createAndGetActorSystem().actorOf(
                Props.create(UdpWorker.class, actorMaxOperationTimeoutSec,
                        getUdpMetaSample(), LOCALHOST));

        final FiniteDuration duration = Duration.create(20,
                TimeUnit.SECONDS);
        Future<Object> future = Patterns
                .ask(asyncWorker, RequestWorkerMsgType.PROCESS_REQUEST,
                        new Timeout(duration));

        ResponseOnSingeRequest response = (ResponseOnSingeRequest) Await
                .result(future, duration);

        logger.info("\nWorker response:" + response.toString());
    } catch (Throwable ex) {

        logger.error("Exception in test : " + ex);
    }
}