Repository: temporalio/samples-java Branch: main Commit: 1fd2eef51384 Files: 632 Total size: 1.3 MB Directory structure: gitextract_xaqm8zrf/ ├── .github/ │ ├── CODEOWNERS │ ├── dependabot.yml │ └── workflows/ │ └── ci.yml ├── .gitignore ├── LICENSE ├── README.md ├── build.gradle ├── core/ │ ├── build.gradle │ └── src/ │ ├── main/ │ │ ├── java/ │ │ │ └── io/ │ │ │ └── temporal/ │ │ │ └── samples/ │ │ │ ├── apikey/ │ │ │ │ ├── ApiKeyWorker.java │ │ │ │ ├── MyWorkflow.java │ │ │ │ ├── MyWorkflowImpl.java │ │ │ │ ├── README.md │ │ │ │ └── Starter.java │ │ │ ├── asyncchild/ │ │ │ │ ├── ChildWorkflow.java │ │ │ │ ├── ChildWorkflowImpl.java │ │ │ │ ├── ParentWorkflow.java │ │ │ │ ├── ParentWorkflowImpl.java │ │ │ │ ├── README.md │ │ │ │ └── Starter.java │ │ │ ├── asyncuntypedchild/ │ │ │ │ ├── ChildWorkflow.java │ │ │ │ ├── ChildWorkflowImpl.java │ │ │ │ ├── ParentWorkflow.java │ │ │ │ ├── ParentWorkflowImpl.java │ │ │ │ ├── README.md │ │ │ │ └── Starter.java │ │ │ ├── autoheartbeat/ │ │ │ │ ├── AutoHeartbeatUtil.java │ │ │ │ ├── README.md │ │ │ │ ├── Starter.java │ │ │ │ ├── activities/ │ │ │ │ │ ├── AutoActivities.java │ │ │ │ │ └── AutoActivitiesImpl.java │ │ │ │ ├── interceptor/ │ │ │ │ │ ├── AutoHeartbeatActivityInboundCallsInterceptor.java │ │ │ │ │ └── AutoHeartbeatWorkerInterceptor.java │ │ │ │ └── workflows/ │ │ │ │ ├── AutoWorkflow.java │ │ │ │ └── AutoWorkflowImpl.java │ │ │ ├── batch/ │ │ │ │ ├── heartbeatingactivity/ │ │ │ │ │ ├── HeartbeatingActivityBatchStarter.java │ │ │ │ │ ├── HeartbeatingActivityBatchWorker.java │ │ │ │ │ ├── HeartbeatingActivityBatchWorkflow.java │ │ │ │ │ ├── HeartbeatingActivityBatchWorkflowImpl.java │ │ │ │ │ ├── README.md │ │ │ │ │ ├── RecordLoader.java │ │ │ │ │ ├── RecordLoaderImpl.java │ │ │ │ │ ├── RecordProcessor.java │ │ │ │ │ ├── RecordProcessorActivity.java │ │ │ │ │ ├── RecordProcessorActivityImpl.java │ │ │ │ │ ├── RecordProcessorImpl.java │ │ │ │ │ └── SingleRecord.java │ │ │ │ ├── iterator/ │ │ │ │ │ ├── IteratorBatchStarter.java │ │ │ │ │ ├── IteratorBatchWorker.java │ │ │ │ │ ├── IteratorBatchWorkflow.java │ │ │ │ │ ├── IteratorBatchWorkflowImpl.java │ │ │ │ │ ├── README.md │ │ │ │ │ ├── RecordLoader.java │ │ │ │ │ ├── RecordLoaderImpl.java │ │ │ │ │ ├── RecordProcessorWorkflow.java │ │ │ │ │ ├── RecordProcessorWorkflowImpl.java │ │ │ │ │ └── SingleRecord.java │ │ │ │ └── slidingwindow/ │ │ │ │ ├── BatchProgress.java │ │ │ │ ├── BatchWorkflow.java │ │ │ │ ├── BatchWorkflowImpl.java │ │ │ │ ├── ProcessBatchInput.java │ │ │ │ ├── README.md │ │ │ │ ├── RecordIterable.java │ │ │ │ ├── RecordLoader.java │ │ │ │ ├── RecordLoaderImpl.java │ │ │ │ ├── RecordProcessorWorkflow.java │ │ │ │ ├── RecordProcessorWorkflowImpl.java │ │ │ │ ├── SingleRecord.java │ │ │ │ ├── SlidingWindowBatchStarter.java │ │ │ │ ├── SlidingWindowBatchWorker.java │ │ │ │ ├── SlidingWindowBatchWorkflow.java │ │ │ │ └── SlidingWindowBatchWorkflowImpl.java │ │ │ ├── bookingsaga/ │ │ │ │ ├── Booking.java │ │ │ │ ├── README.md │ │ │ │ ├── TripBookingActivities.java │ │ │ │ ├── TripBookingActivitiesImpl.java │ │ │ │ ├── TripBookingClient.java │ │ │ │ ├── TripBookingWorker.java │ │ │ │ ├── TripBookingWorkflow.java │ │ │ │ └── TripBookingWorkflowImpl.java │ │ │ ├── bookingsyncsaga/ │ │ │ │ ├── Booking.java │ │ │ │ ├── README.md │ │ │ │ ├── TripBookingActivities.java │ │ │ │ ├── TripBookingActivitiesImpl.java │ │ │ │ ├── TripBookingClient.java │ │ │ │ ├── TripBookingWorker.java │ │ │ │ ├── TripBookingWorkflow.java │ │ │ │ └── TripBookingWorkflowImpl.java │ │ │ ├── common/ │ │ │ │ └── QueryWorkflowExecution.java │ │ │ ├── countinterceptor/ │ │ │ │ ├── ClientCounter.java │ │ │ │ ├── InterceptorStarter.java │ │ │ │ ├── README.md │ │ │ │ ├── SimpleClientCallsInterceptor.java │ │ │ │ ├── SimpleClientInterceptor.java │ │ │ │ ├── SimpleCountActivityInboundCallsInterceptor.java │ │ │ │ ├── SimpleCountWorkerInterceptor.java │ │ │ │ ├── SimpleCountWorkflowInboundCallsInterceptor.java │ │ │ │ ├── SimpleCountWorkflowOutboundCallsInterceptor.java │ │ │ │ ├── WorkerCounter.java │ │ │ │ ├── activities/ │ │ │ │ │ ├── MyActivities.java │ │ │ │ │ └── MyActivitiesImpl.java │ │ │ │ └── workflow/ │ │ │ │ ├── MyChildWorkflow.java │ │ │ │ ├── MyChildWorkflowImpl.java │ │ │ │ ├── MyWorkflow.java │ │ │ │ └── MyWorkflowImpl.java │ │ │ ├── customannotation/ │ │ │ │ ├── BenignExceptionTypes.java │ │ │ │ ├── BenignExceptionTypesAnnotationInterceptor.java │ │ │ │ ├── CustomAnnotation.java │ │ │ │ └── README.md │ │ │ ├── customchangeversion/ │ │ │ │ ├── CustomChangeVersionActivities.java │ │ │ │ ├── CustomChangeVersionActivitiesImpl.java │ │ │ │ ├── CustomChangeVersionStarter.java │ │ │ │ ├── CustomChangeVersionWorkflow.java │ │ │ │ ├── CustomChangeVersionWorkflowImpl.java │ │ │ │ └── README.md │ │ │ ├── dsl/ │ │ │ │ ├── DslActivities.java │ │ │ │ ├── DslActivitiesImpl.java │ │ │ │ ├── DslWorkflow.java │ │ │ │ ├── DslWorkflowImpl.java │ │ │ │ ├── README.md │ │ │ │ ├── Starter.java │ │ │ │ └── model/ │ │ │ │ ├── Flow.java │ │ │ │ └── FlowAction.java │ │ │ ├── earlyreturn/ │ │ │ │ ├── EarlyReturnClient.java │ │ │ │ ├── EarlyReturnWorker.java │ │ │ │ ├── README.md │ │ │ │ ├── Transaction.java │ │ │ │ ├── TransactionActivities.java │ │ │ │ ├── TransactionActivitiesImpl.java │ │ │ │ ├── TransactionRequest.java │ │ │ │ ├── TransactionWorkflow.java │ │ │ │ ├── TransactionWorkflowImpl.java │ │ │ │ └── TxResult.java │ │ │ ├── encodefailures/ │ │ │ │ ├── CustomerAgeCheck.java │ │ │ │ ├── CustomerAgeCheckImpl.java │ │ │ │ ├── InvalidCustomerException.java │ │ │ │ ├── MyCustomer.java │ │ │ │ ├── README.md │ │ │ │ ├── SimplePrefixPayloadCodec.java │ │ │ │ └── Starter.java │ │ │ ├── encryptedpayloads/ │ │ │ │ ├── CryptCodec.java │ │ │ │ └── EncryptedPayloadsActivity.java │ │ │ ├── envconfig/ │ │ │ │ ├── LoadFromFile.java │ │ │ │ ├── LoadProfile.java │ │ │ │ └── README.md │ │ │ ├── excludefrominterceptor/ │ │ │ │ ├── README.md │ │ │ │ ├── RunMyWorkflows.java │ │ │ │ ├── activities/ │ │ │ │ │ ├── ForInterceptorActivities.java │ │ │ │ │ ├── ForInterceptorActivitiesImpl.java │ │ │ │ │ ├── MyActivities.java │ │ │ │ │ └── MyActivitiesImpl.java │ │ │ │ ├── interceptor/ │ │ │ │ │ ├── MyActivityInboundCallsInterceptor.java │ │ │ │ │ ├── MyWorkerInterceptor.java │ │ │ │ │ ├── MyWorkflowInboundCallsInterceptor.java │ │ │ │ │ └── MyWorkflowOutboundCallsInterceptor.java │ │ │ │ └── workflows/ │ │ │ │ ├── MyWorkflow.java │ │ │ │ ├── MyWorkflowOne.java │ │ │ │ ├── MyWorkflowOneImpl.java │ │ │ │ ├── MyWorkflowTwo.java │ │ │ │ └── MyWorkflowTwoImpl.java │ │ │ ├── fileprocessing/ │ │ │ │ ├── FileProcessingStarter.java │ │ │ │ ├── FileProcessingWorker.java │ │ │ │ ├── FileProcessingWorkflow.java │ │ │ │ ├── FileProcessingWorkflowImpl.java │ │ │ │ ├── README.md │ │ │ │ ├── StoreActivities.java │ │ │ │ └── StoreActivitiesImpl.java │ │ │ ├── getresultsasync/ │ │ │ │ ├── MyWorkflow.java │ │ │ │ ├── MyWorkflowImpl.java │ │ │ │ ├── README.md │ │ │ │ ├── Starter.java │ │ │ │ └── Worker.java │ │ │ ├── hello/ │ │ │ │ ├── HelloAccumulator.java │ │ │ │ ├── HelloActivity.java │ │ │ │ ├── HelloActivityExclusiveChoice.java │ │ │ │ ├── HelloActivityRetry.java │ │ │ │ ├── HelloAsync.java │ │ │ │ ├── HelloAsyncActivityCompletion.java │ │ │ │ ├── HelloAsyncLambda.java │ │ │ │ ├── HelloAwait.java │ │ │ │ ├── HelloCancellationScope.java │ │ │ │ ├── HelloCancellationScopeWithTimer.java │ │ │ │ ├── HelloChild.java │ │ │ │ ├── HelloCron.java │ │ │ │ ├── HelloDelayedStart.java │ │ │ │ ├── HelloDetachedCancellationScope.java │ │ │ │ ├── HelloDynamic.java │ │ │ │ ├── HelloEagerWorkflowStart.java │ │ │ │ ├── HelloException.java │ │ │ │ ├── HelloLocalActivity.java │ │ │ │ ├── HelloParallelActivity.java │ │ │ │ ├── HelloPeriodic.java │ │ │ │ ├── HelloPolymorphicActivity.java │ │ │ │ ├── HelloQuery.java │ │ │ │ ├── HelloSaga.java │ │ │ │ ├── HelloSchedules.java │ │ │ │ ├── HelloSearchAttributes.java │ │ │ │ ├── HelloSideEffect.java │ │ │ │ ├── HelloSignal.java │ │ │ │ ├── HelloSignalWithStartAndWorkflowInit.java │ │ │ │ ├── HelloSignalWithTimer.java │ │ │ │ ├── HelloStandaloneActivity.java │ │ │ │ ├── HelloTypedSearchAttributes.java │ │ │ │ ├── HelloUpdate.java │ │ │ │ ├── HelloWorkflowTimer.java │ │ │ │ └── README.md │ │ │ ├── keymanagementencryption/ │ │ │ │ └── awsencryptionsdk/ │ │ │ │ ├── EncryptedPayloads.java │ │ │ │ ├── KeyringCodec.java │ │ │ │ └── README.md │ │ │ ├── listworkflows/ │ │ │ │ ├── Customer.java │ │ │ │ ├── CustomerActivities.java │ │ │ │ ├── CustomerActivitiesImpl.java │ │ │ │ ├── CustomerWorkflow.java │ │ │ │ ├── CustomerWorkflowImpl.java │ │ │ │ ├── README.md │ │ │ │ └── Starter.java │ │ │ ├── metrics/ │ │ │ │ ├── MetricsStarter.java │ │ │ │ ├── MetricsUtils.java │ │ │ │ ├── MetricsWorker.java │ │ │ │ ├── README.md │ │ │ │ ├── activities/ │ │ │ │ │ ├── MetricsActivities.java │ │ │ │ │ └── MetricsActivitiesImpl.java │ │ │ │ └── workflow/ │ │ │ │ ├── MetricsWorkflow.java │ │ │ │ └── MetricsWorkflowImpl.java │ │ │ ├── moneybatch/ │ │ │ │ ├── Account.java │ │ │ │ ├── AccountActivityWorker.java │ │ │ │ ├── AccountImpl.java │ │ │ │ ├── AccountTransferWorker.java │ │ │ │ ├── AccountTransferWorkflow.java │ │ │ │ ├── AccountTransferWorkflowImpl.java │ │ │ │ ├── README.md │ │ │ │ └── TransferRequester.java │ │ │ ├── moneytransfer/ │ │ │ │ ├── Account.java │ │ │ │ ├── AccountActivityWorker.java │ │ │ │ ├── AccountImpl.java │ │ │ │ ├── AccountTransferWorker.java │ │ │ │ ├── AccountTransferWorkflow.java │ │ │ │ ├── AccountTransferWorkflowImpl.java │ │ │ │ ├── README.MD │ │ │ │ └── TransferRequester.java │ │ │ ├── nexus/ │ │ │ │ ├── README.MD │ │ │ │ ├── caller/ │ │ │ │ │ ├── CallerStarter.java │ │ │ │ │ ├── CallerWorker.java │ │ │ │ │ ├── EchoCallerWorkflow.java │ │ │ │ │ ├── EchoCallerWorkflowImpl.java │ │ │ │ │ ├── HelloCallerWorkflow.java │ │ │ │ │ └── HelloCallerWorkflowImpl.java │ │ │ │ ├── handler/ │ │ │ │ │ ├── EchoClient.java │ │ │ │ │ ├── EchoClientImpl.java │ │ │ │ │ ├── HandlerWorker.java │ │ │ │ │ ├── HelloHandlerWorkflow.java │ │ │ │ │ ├── HelloHandlerWorkflowImpl.java │ │ │ │ │ └── SampleNexusServiceImpl.java │ │ │ │ ├── options/ │ │ │ │ │ └── ClientOptions.java │ │ │ │ └── service/ │ │ │ │ ├── SampleNexusService.java │ │ │ │ └── description.md │ │ │ ├── nexuscancellation/ │ │ │ │ ├── README.MD │ │ │ │ ├── caller/ │ │ │ │ │ ├── CallerStarter.java │ │ │ │ │ ├── CallerWorker.java │ │ │ │ │ ├── HelloCallerWorkflow.java │ │ │ │ │ └── HelloCallerWorkflowImpl.java │ │ │ │ └── handler/ │ │ │ │ ├── HandlerWorker.java │ │ │ │ └── HelloHandlerWorkflowImpl.java │ │ │ ├── nexuscontextpropagation/ │ │ │ │ ├── README.MD │ │ │ │ ├── caller/ │ │ │ │ │ ├── CallerStarter.java │ │ │ │ │ ├── CallerWorker.java │ │ │ │ │ ├── EchoCallerWorkflowImpl.java │ │ │ │ │ └── HelloCallerWorkflowImpl.java │ │ │ │ ├── handler/ │ │ │ │ │ ├── HandlerWorker.java │ │ │ │ │ ├── HelloHandlerWorkflowImpl.java │ │ │ │ │ └── SampleNexusServiceImpl.java │ │ │ │ └── propagation/ │ │ │ │ ├── MDCContextPropagator.java │ │ │ │ └── NexusMDCContextInterceptor.java │ │ │ ├── nexusmessaging/ │ │ │ │ ├── README.md │ │ │ │ ├── callerpattern/ │ │ │ │ │ ├── README.md │ │ │ │ │ ├── caller/ │ │ │ │ │ │ ├── CallerStarter.java │ │ │ │ │ │ ├── CallerWorker.java │ │ │ │ │ │ ├── CallerWorkflow.java │ │ │ │ │ │ └── CallerWorkflowImpl.java │ │ │ │ │ ├── handler/ │ │ │ │ │ │ ├── GreetingActivity.java │ │ │ │ │ │ ├── GreetingActivityImpl.java │ │ │ │ │ │ ├── GreetingWorkflow.java │ │ │ │ │ │ ├── GreetingWorkflowImpl.java │ │ │ │ │ │ ├── HandlerWorker.java │ │ │ │ │ │ └── NexusGreetingServiceImpl.java │ │ │ │ │ └── service/ │ │ │ │ │ ├── Language.java │ │ │ │ │ └── NexusGreetingService.java │ │ │ │ └── ondemandpattern/ │ │ │ │ ├── README.md │ │ │ │ ├── caller/ │ │ │ │ │ ├── CallerRemoteStarter.java │ │ │ │ │ ├── CallerRemoteWorker.java │ │ │ │ │ ├── CallerRemoteWorkflow.java │ │ │ │ │ └── CallerRemoteWorkflowImpl.java │ │ │ │ ├── handler/ │ │ │ │ │ ├── GreetingActivity.java │ │ │ │ │ ├── GreetingActivityImpl.java │ │ │ │ │ ├── GreetingWorkflow.java │ │ │ │ │ ├── GreetingWorkflowImpl.java │ │ │ │ │ ├── HandlerWorker.java │ │ │ │ │ └── NexusRemoteGreetingServiceImpl.java │ │ │ │ └── service/ │ │ │ │ ├── Language.java │ │ │ │ └── NexusRemoteGreetingService.java │ │ │ ├── nexusmultipleargs/ │ │ │ │ ├── README.MD │ │ │ │ ├── caller/ │ │ │ │ │ ├── CallerStarter.java │ │ │ │ │ ├── CallerWorker.java │ │ │ │ │ ├── EchoCallerWorkflow.java │ │ │ │ │ ├── EchoCallerWorkflowImpl.java │ │ │ │ │ ├── HelloCallerWorkflow.java │ │ │ │ │ └── HelloCallerWorkflowImpl.java │ │ │ │ └── handler/ │ │ │ │ ├── HandlerWorker.java │ │ │ │ ├── HelloHandlerWorkflow.java │ │ │ │ ├── HelloHandlerWorkflowImpl.java │ │ │ │ └── SampleNexusServiceImpl.java │ │ │ ├── packetdelivery/ │ │ │ │ ├── Packet.java │ │ │ │ ├── PacketDelivery.java │ │ │ │ ├── PacketDeliveryActivities.java │ │ │ │ ├── PacketDeliveryActivitiesImpl.java │ │ │ │ ├── PacketDeliveryWorkflow.java │ │ │ │ ├── PacketDeliveryWorkflowImpl.java │ │ │ │ ├── PacketUtils.java │ │ │ │ ├── README.md │ │ │ │ └── Starter.java │ │ │ ├── payloadconverter/ │ │ │ │ ├── cloudevents/ │ │ │ │ │ ├── CEWorkflow.java │ │ │ │ │ ├── CEWorkflowImpl.java │ │ │ │ │ ├── CloudEventsPayloadConverter.java │ │ │ │ │ ├── README.md │ │ │ │ │ └── Starter.java │ │ │ │ └── crypto/ │ │ │ │ ├── CryptoWorkflow.java │ │ │ │ ├── CryptoWorkflowImpl.java │ │ │ │ ├── MyCustomer.java │ │ │ │ ├── README.md │ │ │ │ └── Starter.java │ │ │ ├── peractivityoptions/ │ │ │ │ ├── FailingActivities.java │ │ │ │ ├── FailingActivitiesImpl.java │ │ │ │ ├── PerActivityOptionsWorkflow.java │ │ │ │ ├── PerActivityOptionsWorkflowImpl.java │ │ │ │ ├── README.md │ │ │ │ └── Starter.java │ │ │ ├── polling/ │ │ │ │ ├── PollingActivities.java │ │ │ │ ├── PollingWorkflow.java │ │ │ │ ├── README.md │ │ │ │ ├── TestService.java │ │ │ │ ├── frequent/ │ │ │ │ │ ├── FrequentPollingActivityImpl.java │ │ │ │ │ ├── FrequentPollingStarter.java │ │ │ │ │ ├── FrequentPollingWorkflowImpl.java │ │ │ │ │ └── README.md │ │ │ │ ├── infrequent/ │ │ │ │ │ ├── InfrequentPollingActivityImpl.java │ │ │ │ │ ├── InfrequentPollingStarter.java │ │ │ │ │ ├── InfrequentPollingWorkflowImpl.java │ │ │ │ │ └── README.md │ │ │ │ ├── infrequentwithretryafter/ │ │ │ │ │ ├── InfrequentPollingWithRetryAfterActivityImpl.java │ │ │ │ │ ├── InfrequentPollingWithRetryAfterStarter.java │ │ │ │ │ ├── InfrequentPollingWithRetryAfterWorkflowImpl.java │ │ │ │ │ └── README.md │ │ │ │ └── periodicsequence/ │ │ │ │ ├── PeriodicPollingActivityImpl.java │ │ │ │ ├── PeriodicPollingChildWorkflowImpl.java │ │ │ │ ├── PeriodicPollingStarter.java │ │ │ │ ├── PeriodicPollingWorkflowImpl.java │ │ │ │ ├── PollingChildWorkflow.java │ │ │ │ └── README.md │ │ │ ├── retryonsignalinterceptor/ │ │ │ │ ├── FailureRequester.java │ │ │ │ ├── MyActivity.java │ │ │ │ ├── MyActivityImpl.java │ │ │ │ ├── MyWorkflow.java │ │ │ │ ├── MyWorkflowImpl.java │ │ │ │ ├── MyWorkflowWorker.java │ │ │ │ ├── QueryRequester.java │ │ │ │ ├── README.MD │ │ │ │ ├── RetryOnSignalInterceptorListener.java │ │ │ │ ├── RetryOnSignalWorkerInterceptor.java │ │ │ │ ├── RetryOnSignalWorkflowInboundCallsInterceptor.java │ │ │ │ ├── RetryOnSignalWorkflowOutboundCallsInterceptor.java │ │ │ │ └── RetryRequester.java │ │ │ ├── safemessagepassing/ │ │ │ │ ├── ClusterManagerActivities.java │ │ │ │ ├── ClusterManagerActivitiesImpl.java │ │ │ │ ├── ClusterManagerWorkflow.java │ │ │ │ ├── ClusterManagerWorkflowImpl.java │ │ │ │ ├── ClusterManagerWorkflowStarter.java │ │ │ │ ├── ClusterManagerWorkflowWorker.java │ │ │ │ └── README.md │ │ │ ├── sleepfordays/ │ │ │ │ ├── README.md │ │ │ │ ├── SendEmailActivity.java │ │ │ │ ├── SendEmailActivityImpl.java │ │ │ │ ├── SleepForDaysImpl.java │ │ │ │ ├── SleepForDaysWorkflow.java │ │ │ │ ├── Starter.java │ │ │ │ └── Worker.java │ │ │ ├── ssl/ │ │ │ │ ├── MyWorkflow.java │ │ │ │ ├── MyWorkflowImpl.java │ │ │ │ ├── README.md │ │ │ │ ├── SslEnabledWorkerCustomCA.java │ │ │ │ └── Starter.java │ │ │ ├── standaloneactivities/ │ │ │ │ ├── CountActivities.java │ │ │ │ ├── ExecuteActivity.java │ │ │ │ ├── GreetingActivities.java │ │ │ │ ├── GreetingActivitiesImpl.java │ │ │ │ ├── ListActivities.java │ │ │ │ ├── README.md │ │ │ │ ├── StandaloneActivityWorker.java │ │ │ │ └── StartActivity.java │ │ │ ├── terminateworkflow/ │ │ │ │ ├── MyWorkflow.java │ │ │ │ ├── MyWorkflowImpl.java │ │ │ │ ├── README.md │ │ │ │ └── Starter.java │ │ │ ├── tracing/ │ │ │ │ ├── JaegerUtils.java │ │ │ │ ├── README.md │ │ │ │ ├── Starter.java │ │ │ │ ├── TracingWorker.java │ │ │ │ └── workflow/ │ │ │ │ ├── TracingActivities.java │ │ │ │ ├── TracingActivitiesImpl.java │ │ │ │ ├── TracingChildWorkflow.java │ │ │ │ ├── TracingChildWorkflowImpl.java │ │ │ │ ├── TracingWorkflow.java │ │ │ │ └── TracingWorkflowImpl.java │ │ │ ├── updatabletimer/ │ │ │ │ ├── DynamicSleepWorkflow.java │ │ │ │ ├── DynamicSleepWorkflowImpl.java │ │ │ │ ├── DynamicSleepWorkflowStarter.java │ │ │ │ ├── DynamicSleepWorkflowWorker.java │ │ │ │ ├── README.md │ │ │ │ ├── UpdatableTimer.java │ │ │ │ └── WakeUpTimeUpdater.java │ │ │ └── workerversioning/ │ │ │ ├── Activities.java │ │ │ ├── ActivitiesImpl.java │ │ │ ├── AutoUpgradingWorkflow.java │ │ │ ├── AutoUpgradingWorkflowV1Impl.java │ │ │ ├── AutoUpgradingWorkflowV1bImpl.java │ │ │ ├── PinnedWorkflow.java │ │ │ ├── PinnedWorkflowV1Impl.java │ │ │ ├── PinnedWorkflowV2Impl.java │ │ │ ├── README.md │ │ │ ├── Starter.java │ │ │ ├── WorkerV1.java │ │ │ ├── WorkerV1_1.java │ │ │ └── WorkerV2.java │ │ └── resources/ │ │ ├── config.toml │ │ ├── dsl/ │ │ │ └── sampleflow.json │ │ └── logback.xml │ └── test/ │ ├── java/ │ │ └── io/ │ │ └── temporal/ │ │ └── samples/ │ │ ├── asyncchild/ │ │ │ └── AsyncChildTest.java │ │ ├── asyncuntypedchild/ │ │ │ └── AsyncUntypedChildTest.java │ │ ├── batch/ │ │ │ ├── heartbeatingactivity/ │ │ │ │ └── HeartbeatingActivityBatchWorkflowTest.java │ │ │ ├── iterator/ │ │ │ │ └── IteratorIteratorBatchWorkflowTest.java │ │ │ └── slidingwindow/ │ │ │ └── SlidingWindowBatchWorkflowTest.java │ │ ├── bookingsaga/ │ │ │ └── TripBookingWorkflowTest.java │ │ ├── bookingsyncsaga/ │ │ │ └── TripBookingWorkflowTest.java │ │ ├── countinterceptor/ │ │ │ ├── ClientCountInterceptorTest.java │ │ │ └── WorkerCountInterceptorTest.java │ │ ├── dsl/ │ │ │ └── DslWorkflowTest.java │ │ ├── earlyreturn/ │ │ │ └── TransactionWorkflowTest.java │ │ ├── encodefailures/ │ │ │ └── EncodeFailuresTest.java │ │ ├── excludefrominterceptor/ │ │ │ └── ExcludeFromInterceptorTest.java │ │ ├── fileprocessing/ │ │ │ └── FileProcessingTest.java │ │ ├── getresultsasync/ │ │ │ └── GetResultsAsyncTest.java │ │ ├── hello/ │ │ │ ├── HelloAccumulatorTest.java │ │ │ ├── HelloActivityExclusiveChoiceJUnit5Test.java │ │ │ ├── HelloActivityExclusiveChoiceTest.java │ │ │ ├── HelloActivityJUnit5Test.java │ │ │ ├── HelloActivityReplayTest.java │ │ │ ├── HelloActivityRetryTest.java │ │ │ ├── HelloActivityTest.java │ │ │ ├── HelloAsyncActivityCompletionTest.java │ │ │ ├── HelloAsyncLambdaTest.java │ │ │ ├── HelloAsyncTest.java │ │ │ ├── HelloAwaitTest.java │ │ │ ├── HelloCancellationScopeTest.java │ │ │ ├── HelloCancellationScopeWithTimerTest.java │ │ │ ├── HelloChildJUnit5Test.java │ │ │ ├── HelloChildTest.java │ │ │ ├── HelloCronTest.java │ │ │ ├── HelloDelayedStartTest.java │ │ │ ├── HelloDetachedCancellationScopeTest.java │ │ │ ├── HelloDynamicActivityJUnit5Test.java │ │ │ ├── HelloDynamicTest.java │ │ │ ├── HelloEagerWorkflowStartTest.java │ │ │ ├── HelloExceptionTest.java │ │ │ ├── HelloLocalActivityTest.java │ │ │ ├── HelloParallelActivityTest.java │ │ │ ├── HelloPeriodicTest.java │ │ │ ├── HelloPolymorphicActivityTest.java │ │ │ ├── HelloQueryTest.java │ │ │ ├── HelloSearchAttributesTest.java │ │ │ ├── HelloSideEffectTest.java │ │ │ ├── HelloSignalTest.java │ │ │ ├── HelloSignalWithStartAndWorkflowInitTest.java │ │ │ ├── HelloSignalWithTimerTest.java │ │ │ ├── HelloStandaloneActivityTest.java │ │ │ ├── HelloUpdateAndCancellationTest.java │ │ │ ├── HelloUpdateTest.java │ │ │ └── HelloWorkflowTimerTest.java │ │ ├── interceptorreplaytest/ │ │ │ └── InterceptorReplayTest.java │ │ ├── listworkflows/ │ │ │ └── ListWorkflowsTest.java │ │ ├── metrics/ │ │ │ └── MetricsTest.java │ │ ├── moneybatch/ │ │ │ └── TransferWorkflowTest.java │ │ ├── moneytransfer/ │ │ │ └── TransferWorkflowTest.java │ │ ├── nexus/ │ │ │ └── caller/ │ │ │ ├── CallerWorkflowJunit5MockTest.java │ │ │ ├── CallerWorkflowJunit5Test.java │ │ │ ├── CallerWorkflowMockTest.java │ │ │ ├── CallerWorkflowTest.java │ │ │ ├── NexusServiceJunit5Test.java │ │ │ └── NexusServiceMockTest.java │ │ ├── payloadconverter/ │ │ │ ├── CloudEventsPayloadConverterTest.java │ │ │ └── CryptoPayloadConverterTest.java │ │ ├── peractivityoptions/ │ │ │ └── PerActivityOptionsTest.java │ │ ├── polling/ │ │ │ ├── FrequentPollingTest.java │ │ │ ├── InfrequentPollingTest.java │ │ │ └── PeriodicPollingTest.java │ │ ├── retryonsignalinterceptor/ │ │ │ └── RetryOnSignalInterceptorTest.java │ │ ├── safemessagepassing/ │ │ │ └── ClusterManagerWorkflowWorkerTest.java │ │ ├── sleepfordays/ │ │ │ ├── SleepForDaysJUnit5Test.java │ │ │ └── SleepForDaysTest.java │ │ ├── standaloneactivities/ │ │ │ └── StandaloneActivitiesTest.java │ │ ├── terminateworkflow/ │ │ │ └── TerminateWorkflowTest.java │ │ └── tracing/ │ │ └── TracingTest.java │ └── resources/ │ └── dsl/ │ └── sampleflow.json ├── docker/ │ └── github/ │ ├── Dockerfile │ ├── README.md │ └── docker-compose.yaml ├── gradle/ │ ├── springai.gradle │ └── wrapper/ │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradle.properties ├── gradlew ├── gradlew.bat ├── settings.gradle ├── springai/ │ ├── basic/ │ │ ├── build.gradle │ │ └── src/ │ │ └── main/ │ │ ├── java/ │ │ │ └── io/ │ │ │ └── temporal/ │ │ │ └── samples/ │ │ │ └── springai/ │ │ │ └── chat/ │ │ │ ├── ChatExampleApplication.java │ │ │ ├── ChatWorkflow.java │ │ │ ├── ChatWorkflowImpl.java │ │ │ ├── StringTools.java │ │ │ ├── TimestampTools.java │ │ │ ├── WeatherActivity.java │ │ │ └── WeatherActivityImpl.java │ │ └── resources/ │ │ └── application.yaml │ ├── mcp/ │ │ ├── build.gradle │ │ └── src/ │ │ └── main/ │ │ ├── java/ │ │ │ └── io/ │ │ │ └── temporal/ │ │ │ └── samples/ │ │ │ └── springai/ │ │ │ └── mcp/ │ │ │ ├── McpApplication.java │ │ │ ├── McpWorkflow.java │ │ │ └── McpWorkflowImpl.java │ │ └── resources/ │ │ └── application.yaml │ ├── multimodel/ │ │ ├── build.gradle │ │ └── src/ │ │ └── main/ │ │ ├── java/ │ │ │ └── io/ │ │ │ └── temporal/ │ │ │ └── samples/ │ │ │ └── springai/ │ │ │ └── multimodel/ │ │ │ ├── ChatModelConfig.java │ │ │ ├── MultiModelApplication.java │ │ │ ├── MultiModelWorkflow.java │ │ │ └── MultiModelWorkflowImpl.java │ │ └── resources/ │ │ └── application.yaml │ └── rag/ │ ├── build.gradle │ └── src/ │ └── main/ │ ├── java/ │ │ └── io/ │ │ └── temporal/ │ │ └── samples/ │ │ └── springai/ │ │ └── rag/ │ │ ├── RagApplication.java │ │ ├── RagWorkflow.java │ │ ├── RagWorkflowImpl.java │ │ └── VectorStoreConfig.java │ └── resources/ │ └── application.yaml ├── springboot/ │ ├── build.gradle │ └── src/ │ ├── main/ │ │ ├── java/ │ │ │ └── io/ │ │ │ └── temporal/ │ │ │ └── samples/ │ │ │ └── springboot/ │ │ │ ├── SamplesController.java │ │ │ ├── TemporalSpringbootSamplesApplication.java │ │ │ ├── actuator/ │ │ │ │ ├── README.md │ │ │ │ └── WorkerActuatorEndpoint.java │ │ │ ├── camel/ │ │ │ │ ├── CamelConfig.java │ │ │ │ ├── CamelResource.java │ │ │ │ ├── CamelRoutes.java │ │ │ │ ├── OfficeOrder.java │ │ │ │ ├── OrderActivity.java │ │ │ │ ├── OrderActivityImpl.java │ │ │ │ ├── OrderRepository.java │ │ │ │ ├── OrderWorkflow.java │ │ │ │ ├── OrderWorkflowImpl.java │ │ │ │ └── README.md │ │ │ ├── customize/ │ │ │ │ ├── CustomizeActivity.java │ │ │ │ ├── CustomizeActivityImpl.java │ │ │ │ ├── CustomizeWorkflow.java │ │ │ │ ├── CustomizeWorkflowImpl.java │ │ │ │ ├── README.md │ │ │ │ └── TemporalOptionsConfig.java │ │ │ ├── hello/ │ │ │ │ ├── HelloActivity.java │ │ │ │ ├── HelloActivityImpl.java │ │ │ │ ├── HelloWorkflow.java │ │ │ │ ├── HelloWorkflowImpl.java │ │ │ │ ├── README.md │ │ │ │ └── model/ │ │ │ │ └── Person.java │ │ │ ├── kafka/ │ │ │ │ ├── KafkaActivity.java │ │ │ │ ├── KafkaActivityImpl.java │ │ │ │ ├── KafkaConfig.java │ │ │ │ ├── MessageController.java │ │ │ │ ├── MessageWorkflow.java │ │ │ │ ├── MessageWorkflowImpl.java │ │ │ │ └── README.md │ │ │ ├── metrics/ │ │ │ │ └── README.md │ │ │ └── update/ │ │ │ ├── ProductNotAvailableForAmountException.java │ │ │ ├── PurchaseActivities.java │ │ │ ├── PurchaseActivitiesImpl.java │ │ │ ├── PurchaseWorkflow.java │ │ │ ├── PurchaseWorkflowImpl.java │ │ │ ├── README.md │ │ │ ├── ResourceNotFoundException.java │ │ │ └── model/ │ │ │ ├── Product.java │ │ │ ├── ProductRepository.java │ │ │ └── Purchase.java │ │ └── resources/ │ │ ├── application-tc.yaml │ │ ├── application.yaml │ │ ├── data.sql │ │ ├── static/ │ │ │ └── js/ │ │ │ ├── jquery.sse.js │ │ │ └── samplessse.js │ │ └── templates/ │ │ ├── actuator.html │ │ ├── camel.html │ │ ├── customize.html │ │ ├── fragments.html │ │ ├── hello.html │ │ ├── index.html │ │ ├── kafka.html │ │ ├── metrics.html │ │ └── update.html │ └── test/ │ ├── java/ │ │ └── io/ │ │ └── temporal/ │ │ └── samples/ │ │ └── springboot/ │ │ ├── CamelSampleTest.java │ │ ├── CustomizeSampleTest.java │ │ ├── HelloSampleTest.java │ │ ├── HelloSampleTestMockedActivity.java │ │ ├── KafkaConsumerTestHelper.java │ │ ├── KafkaSampleTest.java │ │ └── UpdateSampleTest.java │ └── resources/ │ ├── application.yaml │ └── data.sql └── springboot-basic/ ├── build.gradle └── src/ ├── main/ │ ├── java/ │ │ └── io/ │ │ └── temporal/ │ │ └── samples/ │ │ └── springboot/ │ │ ├── SamplesController.java │ │ ├── TemporalSpringbootSamplesApplication.java │ │ └── hello/ │ │ ├── HelloActivity.java │ │ ├── HelloActivityImpl.java │ │ ├── HelloWorkflow.java │ │ ├── HelloWorkflowImpl.java │ │ ├── README.md │ │ └── model/ │ │ └── Person.java │ └── resources/ │ ├── application-tc.yaml │ ├── application.yaml │ ├── static/ │ │ └── js/ │ │ ├── jquery.sse.js │ │ └── samplessse.js │ └── templates/ │ ├── fragments.html │ ├── hello.html │ └── index.html └── test/ ├── java/ │ └── io/ │ └── temporal/ │ └── samples/ │ └── springboot/ │ └── HelloSampleTest.java └── resources/ └── application.yaml ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/CODEOWNERS ================================================ # Primary owners * @tsurdilo @temporalio/sdk @antmendoza # Below are owners for samples for modules # that are owned by teams other than the SDK team. # For each one, we add the owning team, as well as # @temporalio/sdk, so the SDK team can continue to # manage repo-wide concerns /springai/ @temporalio/ai-sdk @temporalio/sdk ================================================ FILE: .github/dependabot.yml ================================================ version: 2 updates: - package-ecosystem: "gradle" directory: "/" schedule: interval: "weekly" - package-ecosystem: "github-actions" directory: "/" schedule: interval: "weekly" ================================================ FILE: .github/workflows/ci.yml ================================================ name: "Continuous Integration" on: [push, pull_request] permissions: contents: read jobs: validation: name: "Gradle wrapper validation" runs-on: ubuntu-latest steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 - uses: gradle/actions/wrapper-validation@ac396bf1a80af16236baf54bd7330ae21dc6ece5 # v6 unittest: name: Unit Tests runs-on: ubuntu-latest timeout-minutes: 15 steps: - name: Checkout repo uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 with: fetch-depth: 0 submodules: recursive ref: ${{ github.event.pull_request.head.sha }} - name: Run unit tests run: | docker compose -f ./docker/github/docker-compose.yaml up --exit-code-from unit-test unit-test code_format: name: Code format runs-on: ubuntu-latest timeout-minutes: 20 steps: - name: Checkout repo uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 with: fetch-depth: 0 submodules: recursive ref: ${{ github.event.pull_request.head.sha }} - name: Set up Java uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5 with: java-version: "17" distribution: "temurin" - name: Set up Gradle uses: gradle/actions/setup-gradle@ac396bf1a80af16236baf54bd7330ae21dc6ece5 # v6 - name: Run copyright and code format checks run: ./gradlew --no-daemon spotlessCheck ================================================ FILE: .gitignore ================================================ target .*.swp .*.swo *.iml .DS_Store .idea .gradle **/build/ **/out/ .classpath .project .settings/ bin/ core/.vscode/ .claude/ ================================================ FILE: LICENSE ================================================ Temporal Java SDK Copyright (c) 2025 Temporal Technologies, Inc. All Rights Reserved Copyright (c) 2017 Uber Technologies, Inc. All Rights Reserved Copyright 2012-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: README.md ================================================ # Temporal Java SDK Samples This repository contains samples that demonstrate various capabilities of Temporal using the [Java SDK](https://github.com/temporalio/sdk-java). It contains the following modules: * [Core](/core): showcases many different SDK features. * [SpringBoot](/springboot): showcases SpringBoot autoconfig integration. * [SpringBoot Basic](/springboot-basic): Minimal sample showing SpringBoot autoconfig integration without any extra external dependencies. * [Spring AI](/springai): demonstrates the Temporal Spring AI integration — durable AI agents with chat models, tools, MCP servers, vector stores, and embeddings. ## Learn more about Temporal and Java SDK - [Temporal Server repo](https://github.com/temporalio/temporal) - [Java SDK repo](https://github.com/temporalio/sdk-java) - [Java SDK Guide](https://docs.temporal.io/dev-guide/java) ## Requirements - Java 17+ - Local Temporal Server, easiest to get started would be using [Temporal CLI](https://github.com/temporalio/cli). For more options see docs [here](https://docs.temporal.io/kb/all-the-ways-to-run-a-cluster). ## Build and run tests 1. Clone this repository: git clone https://github.com/temporalio/samples-java cd samples-java 2. Build and run Tests ./gradlew build ## Running Samples: You can run both "Core" and "SpringBoot" samples from the main samples project directory. Details on how to run each sample can be found in following two sections. To skip to SpringBoot samples click [here](#Running-SpringBoot-Samples). ### Running "Core" samples See the README.md file in each main sample directory for cut/paste Gradle command to run specific example. #### Hello samples - [**Hello**](/core/src/main/java/io/temporal/samples/hello): This sample includes a number of individual Workflows that can be executed independently. Each one demonstrates something specific. - [**HelloAccumulator**](/core/src/main/java/io/temporal/samples/hello/HelloAccumulator.java): Demonstrates a Workflow Definition that accumulates signals and continues as new. - [**HelloActivity**](/core/src/main/java/io/temporal/samples/hello/HelloActivity.java): Demonstrates a Workflow Definition that executes a single Activity. - [**HelloActivityRetry**](/core/src/main/java/io/temporal/samples/hello/HelloActivityRetry.java): Demonstrates how to Retry an Activity Execution. - [**HelloActivityExclusiveChoice**](/core/src/main/java/io/temporal/samples/hello/HelloActivityExclusiveChoice.java): Demonstrates how to execute Activities based on dynamic input. - [**HelloAsync**](/core/src/main/java/io/temporal/samples/hello/HelloAsync.java): Demonstrates how to execute Activities asynchronously and wait for them using Promises. - [**HelloAwait**](/core/src/main/java/io/temporal/samples/hello/HelloAwait.java): Demonstrates how to use Await statement to wait for a condition. - [**HelloParallelActivity**](/core/src/main/java/io/temporal/samples/hello/HelloParallelActivity.java): Demonstrates how to execute multiple Activities in parallel, asynchronously, and wait for them using `Promise.allOf`. - [**HelloAsyncActivityCompletion**](/core/src/main/java/io/temporal/samples/hello/HelloAsyncActivityCompletion.java): Demonstrates how to complete an Activity Execution asynchronously. - [**HelloAsyncLambda**](/core/src/main/java/io/temporal/samples/hello/HelloAsyncLambda.java): Demonstrates how to execute part of a Workflow asynchronously in a separate task (thread). - [**HelloCancellationScope**](/core/src/main/java/io/temporal/samples/hello/HelloCancellationScope.java): Demonstrates how to explicitly cancel parts of a Workflow Execution. - [**HelloCancellationScopeWithTimer**](/core/src/main/java/io/temporal/samples/hello/HelloCancellationScopeWithTimer.java): Demonstrates how to cancel activity when workflow timer fires and complete execution. This can prefered over using workflow run/execution timeouts. - [**HelloDetachedCancellationScope**](/core/src/main/java/io/temporal/samples/hello/HelloDetachedCancellationScope.java): Demonstrates how to execute cleanup code after a Workflow Execution has been explicitly cancelled. - [**HelloChild**](/core/src/main/java/io/temporal/samples/hello/HelloChild.java): Demonstrates how to execute a simple Child Workflow. - [**HelloCron**](/core/src/main/java/io/temporal/samples/hello/HelloCron.java): Demonstrates how to execute a Workflow according to a cron schedule. - [**HelloDynamic**](/core/src/main/java/io/temporal/samples/hello/HelloDynamic.java): Demonstrates how to use `DynamicWorkflow` and `DynamicActivity` interfaces. - [**HelloEagerWorkflowStart**](/core/src/main/java/io/temporal/samples/hello/HelloEagerWorkflowStart.java): Demonstrates the use of a eager workflow start. - [**HelloPeriodic**](/core/src/main/java/io/temporal/samples/hello/HelloPeriodic.java): Demonstrates the use of the Continue-As-New feature. - [**HelloException**](/core/src/main/java/io/temporal/samples/hello/HelloException.java): Demonstrates how to handle exception propagation and wrapping. - [**HelloLocalActivity**](/core/src/main/java/io/temporal/samples/hello/HelloLocalActivity.java): Demonstrates the use of a [Local Activity](https://docs.temporal.io/docs/jargon/mesh/#local-activity). - [**HelloPolymorphicActivity**](/core/src/main/java/io/temporal/samples/hello/HelloPolymorphicActivity.java): Demonstrates Activity Definitions that extend a common interface. - [**HelloQuery**](/core/src/main/java/io/temporal/samples/hello/HelloQuery.java): Demonstrates how to Query the state of a Workflow Execution. - [**HelloSchedules**](/core/src/main/java/io/temporal/samples/hello/HelloSchedules.java): Demonstrates how to create and interact with a Schedule. - [**HelloSignal**](/core/src/main/java/io/temporal/samples/hello/HelloSignal.java): Demonstrates how to send and handle a Signal. - [**HelloSaga**](/core/src/main/java/io/temporal/samples/hello/HelloSaga.java): Demonstrates how to use the SAGA feature. - [**HelloSearchAttributes**](/core/src/main/java/io/temporal/samples/hello/HelloSearchAttributes.java): Demonstrates how to add custom Search Attributes to Workflow Executions. - [**HelloSideEffect**](/core/src/main/java/io/temporal/samples/hello/HelloSideEffect.java)**: Demonstrates how to implement a Side Effect. - [**HelloUpdate**](/core/src/main/java/io/temporal/samples/hello/HelloUpdate.java): Demonstrates how to create and interact with an Update. - [**HelloDelayedStart**](/core/src/main/java/io/temporal/samples/hello/HelloDelayedStart.java): Demonstrates how to use delayed start config option when starting a Workflow Executions. - [**HelloSignalWithTimer**](/core/src/main/java/io/temporal/samples/hello/HelloSignalWithTimer.java): Demonstrates how to use collect signals for certain amount of time and then process last one. - [**HelloWorkflowTimer**](/core/src/main/java/io/temporal/samples/hello/HelloWorkflowTimer.java): Demonstrates how we can use workflow timer to restrict duration of workflow execution instead of workflow run/execution timeouts. - [**Auto-Heartbeating**](/core/src/main/java/io/temporal/samples/autoheartbeat/): Demonstrates use of Auto-heartbeating utility via activity interceptor. - [**HelloSignalWithStartAndWorkflowInit**](/core/src/main/java/io/temporal/samples/hello/HelloSignalWithStartAndWorkflowInit.java): Demonstrates how WorkflowInit can be useful with SignalWithStart to initialize workflow variables. - [**HelloStandaloneActivity**](/core/src/main/java/io/temporal/samples/hello/HelloStandaloneActivity.java): Demonstrates how to execute a Standalone Activity directly from an ActivityClient, without a Workflow. #### Scenario-based samples - [**File Processing Sample**](/core/src/main/java/io/temporal/samples/fileprocessing): Demonstrates how to route tasks to specific Workers. This sample has a set of Activities that download a file, processes it, and uploads the result to a destination. Any Worker can execute the first Activity. However, the second and third Activities must be executed on the same host as the first one. - [**Booking SAGA**](/core/src/main/java/io/temporal/samples/bookingsaga): Demonstrates Temporals take on the Camunda BPMN "trip booking" example. - [**Synchronous Booking SAGA**](/core/src/main/java/io/temporal/samples/bookingsyncsaga): Demonstrates low latency SAGA with potentially long compensations. - [**Money Transfer**](/core/src/main/java/io/temporal/samples/moneytransfer): Demonstrates the use of a dedicated Activity Worker. - [**Money Batch**](/core/src/main/java/io/temporal/samples/moneybatch): Demonstrates a situation where a single deposit should be initiated for multiple withdrawals. For example, a seller might want to be paid once per fixed number of transactions. This sample can be easily extended to perform a payment based on more complex criteria, such as at a specific time or an accumulated amount. The sample also demonstrates how to Signal the Workflow when it executes (*Signal with start*). If the Workflow is already executing, it just receives the Signal. If it is not executing, then the Workflow executes first, and then the Signal is delivered to it. *Signal with start* is a "lazy" way to execute Workflows when Signaling them. - [**Domain-Specific-Language - Define sequence of steps in JSON**](/core/src/main/java/io/temporal/samples/dsl): Demonstrates using domain specific language (DSL) defined in JSON to specify sequence of steps to be performed in our workflow. - [**Polling Services**](/core/src/main/java/io/temporal/samples/polling): Recommended implementation of an activity that needs to periodically poll an external resource waiting its successful completion - [**Heartbeating Activity Batch**](/core/src/main/java/io/temporal/samples/batch/heartbeatingactivity): Batch job implementation using a heartbeating activity. - [**Iterator Batch**](/core/src/main/java/io/temporal/samples/batch/iterator): Batch job implementation using the workflow iterator pattern. - [**Sliding Window Batch**](/core/src/main/java/io/temporal/samples/batch/slidingwindow): A batch implementation that maintains a configured number of child workflows during processing. - [**Safe Message Passing**](/core/src/main/java/io/temporal/samples/safemessagepassing): Safely handling concurrent updates and signals messages. - [**Custom Annotation**](/core/src/main/java/io/temporal/samples/customannotation): Demonstrates how to create a custom annotation using an interceptor. - [**Async Packet Delivery**](/core/src/main/java/io/temporal/samples/packetdelivery): Demonstrates running multiple execution paths async within single execution. - [**Worker Versioning**](/core/src/main/java/io/temporal/samples/workerversioning): Demonstrates how to use worker versioning to manage workflow code changes. - [**Environment Configuration**](/core/src/main/java/io/temporal/samples/envconfig): Load client configuration from TOML files with programmatic overrides. #### API demonstrations - [**Async Untyped Child Workflow**](/core/src/main/java/io/temporal/samples/asyncuntypedchild): Demonstrates how to invoke an untyped child workflow async, that can complete after parent workflow is already completed. - [**Updatable Timer**](/core/src/main/java/io/temporal/samples/updatabletimer): Demonstrates the use of a helper class which relies on `Workflow.await` to implement a blocking sleep that can be updated at any moment. - [**Workflow Count Interceptor**](/core/src/main/java/io/temporal/samples/countinterceptor): Demonstrates how to create and register a simple Workflow Count Interceptor. - [**Workflow Retry On Signal Interceptor**](/core/src/main/java/io/temporal/samples/retryonsignalinterceptor): Demonstrates how to create and register an interceptor that retries an activity on a signal. - [**List Workflows**](/core/src/main/java/io/temporal/samples/listworkflows): Demonstrates the use of custom search attributes and ListWorkflowExecutionsRequest with custom queries. - [**Payload Converter - CloudEvents**](/core/src/main/java/io/temporal/samples/payloadconverter/cloudevents): Demonstrates the use of a custom payload converter for CloudEvents. - [**Payload Converter - Crypto**](/core/src/main/java/io/temporal/samples/payloadconverter/crypto): Demonstrates the use of a custom payload converter using jackson-json-crypto. - [**Async Child Workflow**](/core/src/main/java/io/temporal/samples/asyncchild): Demonstrates how to invoke a child workflow async, that can complete after parent workflow is already completed. - [**Terminate Workflow**](/core/src/main/java/io/temporal/samples/terminateworkflow): Demonstrates how to terminate a workflow using client API. - [**Get Workflow Results Async**](/core/src/main/java/io/temporal/samples/getresultsasync): Demonstrates how to start and get workflow results in async manner. - [**Per Activity Type Options**](/core/src/main/java/io/temporal/samples/peractivityoptions): Demonstrates how to set per Activity type options. - [**Configure WorkflowClient to use mTLS**](/core/src/main/java/io/temporal/samples/ssl): Demonstrates how to configure WorkflowClient when using mTLS. - [**Configure WorkflowClient to use API Key**](/core/src/main/java/io/temporal/samples/apikey): Demonstrates how to configure WorkflowClient when using API Keys. - [**Payload Codec**](/core/src/main/java/io/temporal/samples/encodefailures): Demonstrates how to use simple codec to encode/decode failure messages. - [**Exclude Workflow/ActivityTypes from Interceptors**](/core/src/main/java/io/temporal/samples/excludefrominterceptor): Demonstrates how to exclude certain workflow / activity types from interceptors. - [**Standalone Activities**](/core/src/main/java/io/temporal/samples/standaloneactivities): Demonstrates how to start, execute, list, and count Standalone Activities — Activities that run independently without a Workflow, using ActivityClient. #### SDK Metrics - [**Set up SDK metrics**](/core/src/main/java/io/temporal/samples/metrics): Demonstrates how to set up and scrape SDK metrics. #### Tracing Support - [**Set up OpenTracing and/or OpenTelemetry with Jaeger**](/core/src/main/java/io/temporal/samples/tracing): Demonstrates how to set up OpenTracing and/or OpenTelemetry and view traces using Jaeger. #### Encryption Support - [**Encrypted Payloads**](/core/src/main/java/io/temporal/samples/encryptedpayloads): Demonstrates how to use simple codec to encrypt and decrypt payloads. - [**AWS Encryption SDK**](/core/src/main/java/io/temporal/samples/keymanagementencryption/awsencryptionsdk): Demonstrates how to use the AWS Encryption SDK to encrypt and decrypt payloads with AWS KMS. #### Nexus Samples - [**Getting Started**](/core/src/main/java/io/temporal/samples/nexus): Demonstrates how to get started with Temporal and Nexus. - [**Mapping Multiple Arguments**](/core/src/main/java/io/temporal/samples/nexus): Demonstrates how map a Nexus operation to a Workflow that takes multiple arguments. - [**Cancellation**](/core/src/main/java/io/temporal/samples/nexuscancellation): Demonstrates how to cancel an async Nexus operation. - [**Context/Header Propagation**](/core/src/main/java/io/temporal/samples/nexuscontextpropagation): Demonstrates how to propagate context through Nexus operation headers. - [**Nexus Messaging**](/core/src/main/java/io/temporal/samples/nexusmessaging): Demonstrates how to send signal, update and query messages through Nexus. This contains two samples, one sending messages to an existing workflow and a second that creates a workflow through Nexus and sends messages to it. ### Running SpringBoot Samples These samples use SpringBoot 2 by default. To switch to using SpringBoot 3 look at the [gradle.properties](gradle.properties) file and follow simple instructions there. 1. Start SpringBoot from main repo dir: ./gradlew :springboot:bootRun To run the basic sample run ./gradlew :springboot-basic:bootRun 2. Navigate to [localhost:3030](http://localhost:3030) 3. Select which sample you want to run More info on each sample: - [**Hello**](/springboot/src/main/java/io/temporal/samples/springboot/hello): Invoke simple "Hello" workflow from a GET endpoint - [**SDK Metrics**](/springboot/src/main/java/io/temporal/samples/springboot/metrics): Learn how to set up SDK Metrics - [**Synchronous Update**](/springboot/src/main/java/io/temporal/samples/springboot/update): Learn how to use Synchronous Update feature with this purchase sample - [**Kafka Request / Reply**](/springboot/src/main/java/io/temporal/samples/springboot/kafka): Sample showing possible integration with event streaming platforms such as Kafka - [**Customize Options**](/springboot/src/main/java/io/temporal/samples/springboot/customize): Sample showing how to customize options such as WorkerOptions, WorkerFactoryOptions, etc (see options config [here](springboot/src/main/java/io/temporal/samples/springboot/customize/TemporalOptionsConfig.java)) - [**Apache Camel Route**](/springboot/src/main/java/io/temporal/samples/springboot/camel): Sample showing how to start Workflow execution from a Camel Route - [**Custom Actuator Endpoint**](/springboot/src/main/java/io/temporal/samples/springboot/actuator): Sample showing how to create a custom Actuator endpoint that shows registered Workflow and Activity impls per task queue. #### Temporal Cloud To run any of the SpringBoot samples in your Temporal Cloud namespace: 1. Edit the [application-tc.yaml](/springboot/src/main/resources/application-tc.yaml) to set your namespace and client certificates. 2. Start SpringBoot from main repo dir with the `tc` profile: ./gradlew bootRun --args='--spring.profiles.active=tc' 3. Follow the previous section from step 2 ### Running Spring AI Samples The Spring AI samples demonstrate the [Temporal Spring AI integration](https://github.com/temporalio/sdk-java/tree/master/temporal-spring-ai), which makes Spring AI agents durable on Temporal — model calls run as Temporal Activities recorded in Workflow history, and tools are dispatched per their type so they fit Workflow execution. Each sample is its own Spring Boot application with an interactive CLI. Run from the main repo dir: ./gradlew :springai:basic:bootRun ./gradlew :springai:mcp:bootRun ./gradlew :springai:multimodel:bootRun ./gradlew :springai:rag:bootRun All samples need an `OPENAI_API_KEY` environment variable; some need additional setup (see each sample's source for details). More info on each sample: - [**Basic**](/springai/basic): Chat workflow with three tool flavors — activity-backed (`WeatherActivity`), plain workflow tools (`StringTools`), and `@SideEffectTool` (`TimestampTools`) — plus a `PromptChatMemoryAdvisor` for conversation history. - [**MCP**](/springai/mcp): Connects to a Model Context Protocol server and exposes its tools to the AI through Temporal activities. Defaults to the filesystem MCP server. - [**Multi-Model**](/springai/multimodel): Two providers in one workflow (OpenAI and Anthropic), per-model `ActivityOptions` overrides via a Spring bean, plus a route that exercises Anthropic's extended-thinking mode through provider-specific `ChatOptions` pass-through. Requires `ANTHROPIC_API_KEY` in addition to `OPENAI_API_KEY`. - [**RAG**](/springai/rag): Vector store + embeddings for retrieval-augmented generation. Add documents, then ask questions; the workflow searches the vector store and grounds the answer in the retrieved context. ================================================ FILE: build.gradle ================================================ plugins { id "net.ltgt.errorprone" version "4.0.1" id 'com.diffplug.spotless' version '6.25.0' apply false id "org.springframework.boot" version "${springBootPluginVersion}" } subprojects { apply plugin: 'java' apply plugin: 'net.ltgt.errorprone' apply plugin: 'com.diffplug.spotless' compileJava { options.compilerArgs << "-Werror" } java { sourceCompatibility = JavaVersion.VERSION_17 targetCompatibility = JavaVersion.VERSION_17 } ext { otelVersion = '1.30.1' otelVersionAlpha = "${otelVersion}-alpha" javaSDKVersion = '1.35.0' camelVersion = '3.22.1' jarVersion = '1.0.0' } repositories { mavenLocal() maven { url "https://oss.sonatype.org/content/repositories/snapshots/" } mavenCentral() } dependencies { } apply plugin: 'com.diffplug.spotless' spotless { java { target 'src/*/java/**/*.java' targetExclude '**/.idea/**' googleJavaFormat('1.24.0') } } compileJava.dependsOn 'spotlessApply' test { useJUnitPlatform() } } ================================================ FILE: core/build.gradle ================================================ dependencies { // Temporal SDK implementation "io.temporal:temporal-sdk:$javaSDKVersion" implementation "io.temporal:temporal-opentracing:$javaSDKVersion" testImplementation("io.temporal:temporal-testing:$javaSDKVersion") // Environment configuration implementation "io.temporal:temporal-envconfig:$javaSDKVersion" // Needed for SDK related functionality implementation "io.grpc:grpc-util" implementation(platform("com.fasterxml.jackson:jackson-bom:2.17.2")) implementation "com.fasterxml.jackson.core:jackson-databind" implementation "com.fasterxml.jackson.core:jackson-core" implementation "io.micrometer:micrometer-registry-prometheus" implementation group: 'ch.qos.logback', name: 'logback-classic', version: '1.5.6' implementation group: 'com.jayway.jsonpath', name: 'json-path', version: '2.9.0' implementation(platform("io.opentelemetry:opentelemetry-bom:$otelVersion")) implementation "io.opentelemetry:opentelemetry-sdk" implementation "io.opentelemetry:opentelemetry-exporter-jaeger" implementation "io.opentelemetry:opentelemetry-extension-trace-propagators" implementation "io.opentelemetry:opentelemetry-opentracing-shim:$otelVersionAlpha" implementation "io.opentelemetry:opentelemetry-semconv:$otelVersionAlpha" implementation 'io.jaegertracing:jaeger-client:1.8.1' // Used in samples implementation group: 'commons-configuration', name: 'commons-configuration', version: '1.10' implementation group: 'io.cloudevents', name: 'cloudevents-core', version: '4.0.1' implementation group: 'io.cloudevents', name: 'cloudevents-api', version: '4.0.1' implementation group: 'io.cloudevents', name: 'cloudevents-json-jackson', version: '3.0.0' implementation group: 'net.thisptr', name: 'jackson-jq', version: '1.0.0-preview.20240207' implementation group: 'commons-cli', name: 'commons-cli', version: '1.9.0' // Used in AWS Encryption SDK sample implementation group: 'com.amazonaws', name: 'aws-encryption-sdk-java', version: '3.0.1' implementation("software.amazon.cryptography:aws-cryptographic-material-providers:1.0.2") implementation(platform("software.amazon.awssdk:bom:2.20.91")) implementation("software.amazon.awssdk:kms") implementation("software.amazon.awssdk:dynamodb") // we don't update it to 2.1.0 because 2.1.0 requires Java 11 implementation 'com.codingrodent:jackson-json-crypto:1.1.0' testImplementation "junit:junit:4.13.2" testImplementation "org.mockito:mockito-core:5.12.0" testImplementation(platform("org.junit:junit-bom:5.10.3")) testImplementation "org.junit.jupiter:junit-jupiter-api" testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine" testRuntimeOnly "org.junit.vintage:junit-vintage-engine" dependencies { errorproneJavac('com.google.errorprone:javac:9+181-r4173-1') errorprone('com.google.errorprone:error_prone_core:2.28.0') } } task execute(type: JavaExec) { mainClass = findProperty("mainClass") ?: "" classpath = sourceSets.main.runtimeClasspath if (findProperty("args")) { args findProperty("args").tokenize() } } ================================================ FILE: core/src/main/java/io/temporal/samples/apikey/ApiKeyWorker.java ================================================ package io.temporal.samples.apikey; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowClientOptions; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.serviceclient.WorkflowServiceStubsOptions; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import java.io.IOException; public class ApiKeyWorker { static final String TASK_QUEUE = "MyTaskQueue"; public static void main(String[] args) throws Exception { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } // For temporal cloud this would be ${cloud-region}.{cloud}.api.temporal.io:7233 // Example us-east-1.aws.api.temporal.io:7233 String targetEndpoint = System.getenv("TEMPORAL_ENDPOINT"); // Your registered namespace. String namespace = System.getenv("TEMPORAL_NAMESPACE"); // Your API Key String apiKey = System.getenv("TEMPORAL_API_KEY"); if (targetEndpoint == null || namespace == null || apiKey == null) { throw new IllegalArgumentException( "TEMPORAL_ENDPOINT, TEMPORAL_NAMESPACE, and TEMPORAL_API_KEY environment variables must be set"); } // Create API Key enabled client with environment config as base WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs( WorkflowServiceStubsOptions.newBuilder(profile.toWorkflowServiceStubsOptions()) .setTarget(targetEndpoint) .setEnableHttps(true) .addApiKey(() -> apiKey) .build()); // Now setup and start workflow worker WorkflowClient client = WorkflowClient.newInstance( service, WorkflowClientOptions.newBuilder(profile.toWorkflowClientOptions()) .setNamespace(namespace) .build()); // worker factory that can be used to create workers for specific task queues WorkerFactory factory = WorkerFactory.newInstance(client); /* * Define the workflow worker. Workflow workers listen to a defined task queue and process * workflows and activities. */ Worker worker = factory.newWorker(TASK_QUEUE); /* * Register our workflow implementation with the worker. * Workflow implementations must be known to the worker at runtime in * order to dispatch workflow tasks. */ worker.registerWorkflowImplementationTypes(MyWorkflowImpl.class); /* * Start all the workers registered for a specific task queue. * The started workers then start polling for workflows and activities. */ factory.start(); System.out.println("Worker started. Press Ctrl+C to exit."); // Keep the worker running Thread.currentThread().join(); } } ================================================ FILE: core/src/main/java/io/temporal/samples/apikey/MyWorkflow.java ================================================ package io.temporal.samples.apikey; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; @WorkflowInterface public interface MyWorkflow { @WorkflowMethod String execute(); } ================================================ FILE: core/src/main/java/io/temporal/samples/apikey/MyWorkflowImpl.java ================================================ package io.temporal.samples.apikey; public class MyWorkflowImpl implements MyWorkflow { @Override public String execute() { return "done"; } } ================================================ FILE: core/src/main/java/io/temporal/samples/apikey/README.md ================================================ # Workflow execution with API Key This example shows how to secure your Temporal application with API Key authentication. This is required to connect with Temporal Cloud or any production Temporal deployment that uses API Key authentication. ## Prerequisites 1. A Temporal Cloud account 2. A namespace in Temporal Cloud 3. An API Key for your namespace ## Getting your API Key 1. Log in to your Temporal Cloud account 2. Navigate to your namespace 3. Go to Namespace Settings > API Keys 4. Click "Create API Key" 5. Give your API Key a name and select the appropriate permissions 6. Copy the API Key value (you won't be able to see it again) ## Export env variables Before running the example you need to export the following env variables: ```bash # Your Temporal Cloud endpoint (e.g., us-east-1.aws.api.temporal.io:7233) export TEMPORAL_ENDPOINT="us-east-1.aws.api.temporal.io:7233" # Your Temporal Cloud namespace export TEMPORAL_NAMESPACE="your-namespace" # Your API Key from Temporal Cloud export TEMPORAL_API_KEY="your-api-key" ``` ## Running this sample This sample consists of two components that need to be run in separate terminals: 1. First, start the worker: ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.apikey.ApiKeyWorker ``` 2. Then, in a new terminal, run the starter: ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.apikey.Starter ``` ## Expected result When running the worker, you should see: ```text [main] INFO i.t.s.WorkflowServiceStubsImpl - Created WorkflowServiceStubs for channel: ManagedChannelOrphanWrapper{delegate=ManagedChannelImpl{logId=1, target=us-east-1.aws.api.temporal.io:7233}} [main] INFO io.temporal.internal.worker.Poller - start: Poller{name=Workflow Poller taskQueue="MyTaskQueue", namespace="your-namespace"} Worker started. Press Ctrl+C to exit. ``` When running the starter, you should see: ```text [main] INFO i.t.s.WorkflowServiceStubsImpl - Created WorkflowServiceStubs for channel: ManagedChannelOrphanWrapper{delegate=ManagedChannelImpl{logId=1, target=us-east-1.aws.api.temporal.io:7233}} [main] INFO io.temporal.internal.worker.Poller - start: Poller{name=Workflow Poller taskQueue="MyTaskQueue", namespace="your-namespace"} done ``` ## Troubleshooting If you encounter any issues: 1. Verify your environment variables are set correctly: ```bash echo $TEMPORAL_ENDPOINT echo $TEMPORAL_NAMESPACE echo $TEMPORAL_API_KEY ``` 2. Check that your API Key has the correct permissions for your namespace 3. Ensure your namespace is active and accessible 4. If you get connection errors, verify your endpoint is correct and accessible from your network 5. Make sure you're running the commands from the correct directory (where the `gradlew` script is located) ================================================ FILE: core/src/main/java/io/temporal/samples/apikey/Starter.java ================================================ package io.temporal.samples.apikey; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowClientOptions; import io.temporal.client.WorkflowOptions; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.serviceclient.WorkflowServiceStubsOptions; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import java.io.IOException; public class Starter { static final String TASK_QUEUE = "MyTaskQueue"; static final String WORKFLOW_ID = "HelloAPIKeyWorkflow"; public static void main(String[] args) throws Exception { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } // For temporal cloud this would be ${cloud-region}.{cloud}.api.temporal.io:7233 // Example us-east-1.aws.api.temporal.io:7233 String targetEndpoint = System.getenv("TEMPORAL_ENDPOINT"); // Your registered namespace. String namespace = System.getenv("TEMPORAL_NAMESPACE"); // Your API Key String apiKey = System.getenv("TEMPORAL_API_KEY"); if (targetEndpoint == null || namespace == null || apiKey == null) { throw new IllegalArgumentException( "TEMPORAL_ENDPOINT, TEMPORAL_NAMESPACE, and TEMPORAL_API_KEY environment variables must be set"); } // Create API Key enabled client with environment config as base WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs( WorkflowServiceStubsOptions.newBuilder(profile.toWorkflowServiceStubsOptions()) .setTarget(targetEndpoint) .setEnableHttps(true) .addApiKey(() -> apiKey) .build()); WorkflowClient client = WorkflowClient.newInstance( service, WorkflowClientOptions.newBuilder(profile.toWorkflowClientOptions()) .setNamespace(namespace) .build()); WorkerFactory factory = WorkerFactory.newInstance(client); Worker worker = factory.newWorker(TASK_QUEUE); worker.registerWorkflowImplementationTypes(MyWorkflowImpl.class); factory.start(); // Create the workflow client stub. It is used to start our workflow execution. MyWorkflow workflow = client.newWorkflowStub( MyWorkflow.class, WorkflowOptions.newBuilder() .setWorkflowId(WORKFLOW_ID) .setTaskQueue(TASK_QUEUE) .build()); String greeting = workflow.execute(); // Display workflow execution results System.out.println(greeting); System.exit(0); } } ================================================ FILE: core/src/main/java/io/temporal/samples/asyncchild/ChildWorkflow.java ================================================ package io.temporal.samples.asyncchild; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; @WorkflowInterface public interface ChildWorkflow { @WorkflowMethod String executeChild(); } ================================================ FILE: core/src/main/java/io/temporal/samples/asyncchild/ChildWorkflowImpl.java ================================================ package io.temporal.samples.asyncchild; import io.temporal.workflow.Workflow; import java.time.Duration; public class ChildWorkflowImpl implements ChildWorkflow { @Override public String executeChild() { Workflow.sleep(Duration.ofSeconds(3)); return "Child workflow done"; } } ================================================ FILE: core/src/main/java/io/temporal/samples/asyncchild/ParentWorkflow.java ================================================ package io.temporal.samples.asyncchild; import io.temporal.api.common.v1.WorkflowExecution; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; @WorkflowInterface public interface ParentWorkflow { @WorkflowMethod WorkflowExecution executeParent(); } ================================================ FILE: core/src/main/java/io/temporal/samples/asyncchild/ParentWorkflowImpl.java ================================================ package io.temporal.samples.asyncchild; import io.temporal.api.common.v1.WorkflowExecution; import io.temporal.api.enums.v1.ParentClosePolicy; import io.temporal.workflow.Async; import io.temporal.workflow.ChildWorkflowOptions; import io.temporal.workflow.Promise; import io.temporal.workflow.Workflow; public class ParentWorkflowImpl implements ParentWorkflow { @Override public WorkflowExecution executeParent() { // We set the parentClosePolicy to "Abandon" // This will allow child workflow to continue execution after parent completes ChildWorkflowOptions childWorkflowOptions = ChildWorkflowOptions.newBuilder() .setWorkflowId("childWorkflow") .setParentClosePolicy(ParentClosePolicy.PARENT_CLOSE_POLICY_ABANDON) .build(); // Get the child workflow stub ChildWorkflow child = Workflow.newChildWorkflowStub(ChildWorkflow.class, childWorkflowOptions); // Start the child workflow async Async.function(child::executeChild); // Get the child workflow execution promise Promise childExecution = Workflow.getWorkflowExecution(child); // Call .get on the promise. This will block until the child workflow starts execution (or start // fails) return childExecution.get(); } } ================================================ FILE: core/src/main/java/io/temporal/samples/asyncchild/README.md ================================================ # Async Child Workflow execution The sample demonstrates shows how to invoke a Child Workflow asynchronously. The Child Workflow is allowed to complete its execution even after the Parent Workflow completes. ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.asyncchild.Starter ``` ================================================ FILE: core/src/main/java/io/temporal/samples/asyncchild/Starter.java ================================================ package io.temporal.samples.asyncchild; import io.temporal.api.common.v1.WorkflowExecution; import io.temporal.api.workflow.v1.WorkflowExecutionInfo; import io.temporal.api.workflowservice.v1.DescribeWorkflowExecutionRequest; import io.temporal.api.workflowservice.v1.DescribeWorkflowExecutionResponse; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import java.io.IOException; import java.util.concurrent.TimeUnit; public class Starter { public static final String TASK_QUEUE = "asyncChildTaskQueue"; public static void main(String[] args) { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); WorkerFactory factory = WorkerFactory.newInstance(client); createWorker(factory); WorkflowOptions parentWorkflowOptions = WorkflowOptions.newBuilder() .setWorkflowId("parentWorkflow") .setTaskQueue(TASK_QUEUE) .build(); ParentWorkflow parentWorkflowStub = client.newWorkflowStub(ParentWorkflow.class, parentWorkflowOptions); // Start parent workflow and wait for it to complete WorkflowExecution childWorkflowExecution = parentWorkflowStub.executeParent(); // Get the child workflow execution status (after parent completed) System.out.println( "Child execution status: " + getStatusAsString(childWorkflowExecution, client, service)); // Wait for child workflow to complete sleep(4); // Check the status of the child workflow again System.out.println( "Child execution status: " + getStatusAsString(childWorkflowExecution, client, service)); System.exit(0); } private static void createWorker(WorkerFactory factory) { Worker worker = factory.newWorker(TASK_QUEUE); worker.registerWorkflowImplementationTypes(ParentWorkflowImpl.class, ChildWorkflowImpl.class); factory.start(); } private static String getStatusAsString( WorkflowExecution execution, WorkflowClient client, WorkflowServiceStubs service) { DescribeWorkflowExecutionRequest describeWorkflowExecutionRequest = DescribeWorkflowExecutionRequest.newBuilder() .setNamespace(client.getOptions().getNamespace()) .setExecution(execution) .build(); DescribeWorkflowExecutionResponse resp = service.blockingStub().describeWorkflowExecution(describeWorkflowExecutionRequest); WorkflowExecutionInfo workflowExecutionInfo = resp.getWorkflowExecutionInfo(); return workflowExecutionInfo.getStatus().toString(); } private static void sleep(int seconds) { try { Thread.sleep(TimeUnit.SECONDS.toMillis(seconds)); } catch (Exception e) { System.out.println("Exception: " + e.getMessage()); System.exit(0); } } } ================================================ FILE: core/src/main/java/io/temporal/samples/asyncuntypedchild/ChildWorkflow.java ================================================ package io.temporal.samples.asyncuntypedchild; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; /** * Define the child workflow Interface. It must contain one method annotated with @WorkflowMethod * * @see WorkflowInterface * @see WorkflowMethod */ @WorkflowInterface public interface ChildWorkflow { /** * Define the child workflow method. This method is executed when the workflow is started. The * workflow completes when the workflow method finishes execution. */ @WorkflowMethod String composeGreeting(String greeting, String name); } ================================================ FILE: core/src/main/java/io/temporal/samples/asyncuntypedchild/ChildWorkflowImpl.java ================================================ package io.temporal.samples.asyncuntypedchild; import io.temporal.workflow.Workflow; /** * Define the parent workflow implementation. It implements the getGreeting workflow method * *

Note that a workflow implementation must always be public for the Temporal library to be able * to create its instances. */ public class ChildWorkflowImpl implements ChildWorkflow { @Override public String composeGreeting(String greeting, String name) { // Sleep for 2 seconds to ensure the child completes after the parent. Workflow.sleep(2000); return greeting + " " + name + "!"; } } ================================================ FILE: core/src/main/java/io/temporal/samples/asyncuntypedchild/ParentWorkflow.java ================================================ package io.temporal.samples.asyncuntypedchild; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; /** * Define the parent workflow interface. It must contain one method annotated with @WorkflowMethod * * @see WorkflowInterface * @see WorkflowMethod */ @WorkflowInterface public interface ParentWorkflow { /** * Define the parent workflow method. This method is executed when the workflow is started. The * workflow completes when the workflow method finishes execution. */ @WorkflowMethod String getGreeting(String name); } ================================================ FILE: core/src/main/java/io/temporal/samples/asyncuntypedchild/ParentWorkflowImpl.java ================================================ package io.temporal.samples.asyncuntypedchild; import static io.temporal.samples.asyncuntypedchild.Starter.WORKFLOW_ID; import io.temporal.api.common.v1.WorkflowExecution; import io.temporal.api.enums.v1.ParentClosePolicy; import io.temporal.workflow.*; // Define the parent workflow implementation. It implements the getGreeting workflow method public class ParentWorkflowImpl implements ParentWorkflow { @Override public String getGreeting(String name) { /* * Define the child workflow stub. Since workflows are stateful, * a new stub must be created for each child workflow. */ ChildWorkflowStub child = Workflow.newUntypedChildWorkflowStub( ChildWorkflow.class.getSimpleName(), ChildWorkflowOptions.newBuilder() .setParentClosePolicy(ParentClosePolicy.PARENT_CLOSE_POLICY_ABANDON) .setWorkflowId("Child_of_" + WORKFLOW_ID) .build()); /* * Invoke the child workflows composeGreeting workflow method async. * This call is non-blocking and returns immediately returning a {@link io.temporal.workflow.Promise}, * you can invoke `get()` on the returned promise to wait for the child workflow result. */ child.executeAsync(String.class, "Hello", name); // Wait for the child workflow to start before returning the result Promise childExecution = child.getExecution(); WorkflowExecution childWorkflowExecution = childExecution.get(); // return the child workflowId return childWorkflowExecution.getWorkflowId(); } } ================================================ FILE: core/src/main/java/io/temporal/samples/asyncuntypedchild/README.md ================================================ # Async Child Workflow execution The sample demonstrates shows how to invoke an Untyped Child Workflow asynchronously. The Child Workflow continues running for some time after the Parent Workflow completes. ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.asyncuntypedchild.Starter ``` ================================================ FILE: core/src/main/java/io/temporal/samples/asyncuntypedchild/Starter.java ================================================ package io.temporal.samples.asyncuntypedchild; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import java.io.IOException; /** * Sample Temporal Workflow Definition that demonstrates the execution of a Child Workflow. Child * workflows allow you to group your Workflow logic into small logical and reusable units that solve * a particular problem. They can be typically reused by multiple other Workflows. */ public class Starter { static final String WORKFLOW_ID = "ParentWithAsyncUntypedChild"; static final String TASK_QUEUE = WORKFLOW_ID + "Queue"; /** * With the workflow, and child workflow defined, we can now start execution. The main method is * the workflow starter. */ public static void main(String[] args) { // Get a Workflow service stub. // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); /* * Get a Workflow service client which can be used to start, Signal, and Query Workflow Executions. */ WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); /* * Define the workflow factory. It is used to create workflow workers for a specific task queue. */ WorkerFactory factory = WorkerFactory.newInstance(client); /* * Define the workflow worker. Workflow workers listen to a defined task queue and process * workflows and activities. */ Worker worker = factory.newWorker(TASK_QUEUE); /* * Register the parent and child workflow implementation with the worker. * Since workflows are stateful in nature, * we need to register the workflow types. */ worker.registerWorkflowImplementationTypes(ParentWorkflowImpl.class, ChildWorkflowImpl.class); /* * Start all the workers registered for a specific task queue. * The started workers then start polling for workflows and activities. */ factory.start(); // Start a workflow execution. Usually this is done from another program. // Uses task queue from the GreetingWorkflow @WorkflowMethod annotation. // Create our parent workflow client stub. It is used to start the parent workflow execution. ParentWorkflow workflow = client.newWorkflowStub( ParentWorkflow.class, WorkflowOptions.newBuilder() .setWorkflowId(WORKFLOW_ID) .setTaskQueue(TASK_QUEUE) .build()); // Execute our parent workflow and wait for it to complete, it returns the child workflow id. String childWorkflowId = workflow.getGreeting("World"); System.out.println("Child WorkflowId=[" + childWorkflowId + "] started in abandon mode"); String childResult = client.newUntypedWorkflowStub(childWorkflowId).getResult(String.class); System.out.println("Result from child workflow = " + childResult); System.exit(0); } } ================================================ FILE: core/src/main/java/io/temporal/samples/autoheartbeat/AutoHeartbeatUtil.java ================================================ /* * Copyright (c) 2020 Temporal Technologies, Inc. All Rights Reserved * * Copyright 2012-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Modifications copyright (C) 2017 Uber Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not * use this file except in compliance with the License. A copy of the License is * located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package io.temporal.samples.autoheartbeat; import io.temporal.activity.ActivityExecutionContext; import java.time.Instant; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; public class AutoHeartbeatUtil { private final long period; private final long initialDelay; private final TimeUnit periodTimeUnit; private final ScheduledExecutorService timerService = Executors.newSingleThreadScheduledExecutor(); private final ActivityExecutionContext context; private final Object details; private String heartbeaterId; public AutoHeartbeatUtil( long period, long initialDelay, TimeUnit periodTimeUnit, ActivityExecutionContext context, Object details) { this.period = period; this.initialDelay = initialDelay; this.periodTimeUnit = periodTimeUnit; this.context = context; this.details = details; // Set to activity id better, for sample we just use type heartbeaterId = context.getInfo().getActivityType(); } public ScheduledFuture start() { System.out.println("Autoheartbeater[" + heartbeaterId + "] starting..."); return timerService.scheduleAtFixedRate( () -> { // try { System.out.println( "Autoheartbeater[" + heartbeaterId + "]" + "heartbeating at: " + printShortCurrentTime()); context.heartbeat(details); }, initialDelay, period, periodTimeUnit); } public void stop() { System.out.println("Autoheartbeater[" + heartbeaterId + "] being requested to stop."); // Try not to execute another heartbeat that could have been queued up // Note this can at times take a second or two so make sure to test this out on your workers // So can set best heartbeat timeout (sometimes might need larger value to accomodate) timerService.shutdownNow(); } private String printShortCurrentTime() { return DateTimeFormatter.ofPattern("HH:mm:ss") .withZone(ZoneId.systemDefault()) .format(Instant.now()); } } ================================================ FILE: core/src/main/java/io/temporal/samples/autoheartbeat/README.md ================================================ # Auto-heartbeating sample for activities that define HeartbeatTimeout This sample shows an implementation of an "auto-heartbeating" utility that can be applied via interceptor to all activities where you define HeartbeatTimeout. Use case where this can be helpful include situations where you have long-running activities where you want to heartbeat but its difficult to explicitly call heartbeat api in activity code directly. Another useful scenario for this is where you have activity that at times can complete in very short amount of time, but then at times can take for example minutes. In this case you have to set longer StartToClose timeout but you might not want first heartbeat to be sent right away but send it after the "shorter" duration of activity execution. Warning: make sure to test this sample for your use case. This includes load testing. This sample was not tested on large scale workloads. In addition note that it is recommended to heartbeat from activity code itself. Using this type of autoheartbeating utility does have disatvantage that activity code itself can continue running after a handled activity cancelation. Please be aware of these warnings when applying this sample. 1. Start the Sample: ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.autoheartbeat.Starter ``` ================================================ FILE: core/src/main/java/io/temporal/samples/autoheartbeat/Starter.java ================================================ /* * Copyright (c) 2020 Temporal Technologies, Inc. All Rights Reserved * * Copyright 2012-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Modifications copyright (C) 2017 Uber Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not * use this file except in compliance with the License. A copy of the License is * located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package io.temporal.samples.autoheartbeat; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.client.WorkflowStub; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.failure.CanceledFailure; import io.temporal.samples.autoheartbeat.activities.AutoActivitiesImpl; import io.temporal.samples.autoheartbeat.interceptor.AutoHeartbeatWorkerInterceptor; import io.temporal.samples.autoheartbeat.workflows.AutoWorkflow; import io.temporal.samples.autoheartbeat.workflows.AutoWorkflowImpl; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import io.temporal.worker.WorkerFactoryOptions; import java.io.IOException; public class Starter { static final String TASK_QUEUE = "AutoheartbeatTaskQueue"; static final String WORKFLOW_ID = "AutoHeartbeatWorkflow"; public static void main(String[] args) { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); // Configure our auto heartbeat workflow interceptor which will apply // AutoHeartbeaterUtil to each activity workflow schedules which has a heartbeat // timeout configured WorkerFactoryOptions wfo = WorkerFactoryOptions.newBuilder() .setWorkerInterceptors(new AutoHeartbeatWorkerInterceptor()) .build(); WorkerFactory factory = WorkerFactory.newInstance(client, wfo); Worker worker = factory.newWorker(TASK_QUEUE); worker.registerWorkflowImplementationTypes(AutoWorkflowImpl.class); worker.registerActivitiesImplementations(new AutoActivitiesImpl()); factory.start(); // first run completes execution with autoheartbeat utils firstRun(client); // second run cancels running (pending) activity via signal (specific scope cancel) secondRun(client); // third run cancels running execution which cancels activity as well thirdRun(client); // fourth run turns off autoheartbeat for activities and lets activity time out on heartbeat // timeout fourthRun(client); System.exit(0); } @SuppressWarnings("unused") private static void firstRun(WorkflowClient client) { System.out.println("**** First Run: run workflow to completion"); AutoWorkflow firstRun = client.newWorkflowStub( AutoWorkflow.class, WorkflowOptions.newBuilder() .setWorkflowId(WORKFLOW_ID) .setTaskQueue(TASK_QUEUE) .build()); try { String firstRunResult = firstRun.exec("Auto heartbeating is cool"); System.out.println("First run result: " + firstRunResult); } catch (Exception e) { System.out.println("First run - Workflow exec exception: " + e.getClass().getName()); } } @SuppressWarnings("unused") private static void secondRun(WorkflowClient client) { System.out.println("\n\n**** Second Run: cancel activities via signal"); AutoWorkflow secondRun = client.newWorkflowStub( AutoWorkflow.class, WorkflowOptions.newBuilder() .setWorkflowId(WORKFLOW_ID) .setTaskQueue(TASK_QUEUE) .build()); WorkflowClient.start(secondRun::exec, "Auto heartbeating is cool"); doSleeps(4); secondRun.cancelActivity(); try { String secondRunResult = WorkflowStub.fromTyped(secondRun).getResult(String.class); System.out.println("Second run result: " + secondRunResult); } catch (Exception e) { System.out.println("Second run - Workflow exec exception: " + e.getClass().getName()); } } @SuppressWarnings("unused") private static void thirdRun(WorkflowClient client) { System.out.println("\n\n**** Third Run: cancel workflow execution"); AutoWorkflow thirdRun = client.newWorkflowStub( AutoWorkflow.class, WorkflowOptions.newBuilder() .setWorkflowId(WORKFLOW_ID) .setTaskQueue(TASK_QUEUE) .build()); WorkflowClient.start(thirdRun::exec, "Auto heartbeating is cool"); doSleeps(10); try { WorkflowStub.fromTyped(thirdRun).cancel(); String thirdRunResult = WorkflowStub.fromTyped(thirdRun).getResult(String.class); System.out.println("Third run result: " + thirdRunResult); } catch (Exception e) { // we are expecting workflow cancelation if (e.getCause() instanceof CanceledFailure) { System.out.println("Third run - Workflow execution canceled."); } else { System.out.println("Third run - Workflow exec exception: " + e.getMessage()); } } } @SuppressWarnings("unused") private static void fourthRun(WorkflowClient client) { System.out.println("\n\n**** Fourth Run: cause heartbeat timeout"); // we disable autoheartbeat via env var System.setProperty("sample.disableAutoHeartbeat", "true"); AutoWorkflow fourth = client.newWorkflowStub( AutoWorkflow.class, WorkflowOptions.newBuilder() .setWorkflowId(WORKFLOW_ID) .setTaskQueue(TASK_QUEUE) .build()); try { String fourthRunResult = fourth.exec("Auto heartbeating is cool"); System.out.println("Fourth run result: " + fourthRunResult); } catch (Exception e) { System.out.println("Fourth run - Workflow exec exception: " + e.getClass().getName()); } } private static void doSleeps(int seconds) { try { Thread.sleep(seconds * 1000L); } catch (Exception e) { System.out.println(e.getMessage()); } } } ================================================ FILE: core/src/main/java/io/temporal/samples/autoheartbeat/activities/AutoActivities.java ================================================ /* * Copyright (c) 2020 Temporal Technologies, Inc. All Rights Reserved * * Copyright 2012-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Modifications copyright (C) 2017 Uber Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not * use this file except in compliance with the License. A copy of the License is * located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package io.temporal.samples.autoheartbeat.activities; import io.temporal.activity.ActivityInterface; @ActivityInterface public interface AutoActivities { String runActivityOne(String input); String runActivityTwo(String input); } ================================================ FILE: core/src/main/java/io/temporal/samples/autoheartbeat/activities/AutoActivitiesImpl.java ================================================ /* * Copyright (c) 2020 Temporal Technologies, Inc. All Rights Reserved * * Copyright 2012-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Modifications copyright (C) 2017 Uber Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not * use this file except in compliance with the License. A copy of the License is * located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package io.temporal.samples.autoheartbeat.activities; import java.util.concurrent.TimeUnit; public class AutoActivitiesImpl implements AutoActivities { @Override public String runActivityOne(String input) { return runActivity("runActivityOne - " + input, 10); } @Override public String runActivityTwo(String input) { return runActivity("runActivityTwo - " + input, 5); } @SuppressWarnings("FutureReturnValueIgnored") private String runActivity(String input, int seconds) { for (int i = 0; i < seconds; i++) { sleep(1); } return "Activity completed: " + input; } private void sleep(int seconds) { try { Thread.sleep(TimeUnit.SECONDS.toMillis(seconds)); } catch (InterruptedException ee) { // Empty } } } ================================================ FILE: core/src/main/java/io/temporal/samples/autoheartbeat/interceptor/AutoHeartbeatActivityInboundCallsInterceptor.java ================================================ /* * Copyright (c) 2020 Temporal Technologies, Inc. All Rights Reserved * * Copyright 2012-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Modifications copyright (C) 2017 Uber Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not * use this file except in compliance with the License. A copy of the License is * located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package io.temporal.samples.autoheartbeat.interceptor; import io.temporal.activity.Activity; import io.temporal.activity.ActivityExecutionContext; import io.temporal.client.ActivityCanceledException; import io.temporal.common.interceptors.ActivityInboundCallsInterceptor; import io.temporal.common.interceptors.ActivityInboundCallsInterceptorBase; import io.temporal.samples.autoheartbeat.AutoHeartbeatUtil; import java.time.Duration; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; public class AutoHeartbeatActivityInboundCallsInterceptor extends ActivityInboundCallsInterceptorBase { private ActivityExecutionContext activityExecutionContext; private Duration activityHeartbeatTimeout; private AutoHeartbeatUtil autoHeartbeater; private ScheduledFuture scheduledFuture; public AutoHeartbeatActivityInboundCallsInterceptor(ActivityInboundCallsInterceptor next) { super(next); } @Override public void init(ActivityExecutionContext context) { this.activityExecutionContext = context; activityHeartbeatTimeout = activityExecutionContext.getInfo().getHeartbeatTimeout(); super.init(context); } @Override @SuppressWarnings({"FutureReturnValueIgnored", "CatchAndPrintStackTrace"}) public ActivityOutput execute(ActivityInput input) { // If activity has heartbeat timeout defined we want to apply auto-heartbeter // Unless we explicitly disabled autoheartbeating via system property if (activityHeartbeatTimeout != null && activityHeartbeatTimeout.getSeconds() > 0 && !Boolean.parseBoolean(System.getProperty("sample.disableAutoHeartbeat"))) { System.out.println( "Auto heartbeating applied for activity: " + activityExecutionContext.getInfo().getActivityType()); autoHeartbeater = new AutoHeartbeatUtil(2, 0, TimeUnit.SECONDS, activityExecutionContext, input); scheduledFuture = autoHeartbeater.start(); } else { System.out.println( "Auto heartbeating not being applied for activity: " + activityExecutionContext.getInfo().getActivityType()); } if (scheduledFuture != null) { CompletableFuture activityExecFuture = CompletableFuture.supplyAsync(() -> super.execute(input)); CompletableFuture autoHeartbeatFuture = CompletableFuture.supplyAsync( () -> { try { return scheduledFuture.get(); } catch (Exception e) { throw new ActivityCanceledException(activityExecutionContext.getInfo()); } }); try { return (ActivityOutput) CompletableFuture.anyOf(autoHeartbeatFuture, activityExecFuture).get(); } catch (Exception e) { if (e instanceof ExecutionException) { ExecutionException ee = (ExecutionException) e; if (ee.getCause() instanceof ActivityCanceledException) { throw new ActivityCanceledException(activityExecutionContext.getInfo()); } } throw Activity.wrap(e); } finally { if (autoHeartbeater != null) { autoHeartbeater.stop(); } } } else { return super.execute(input); } } public interface AutoHeartbeaterCancellationCallback { void handle(Exception e); } } ================================================ FILE: core/src/main/java/io/temporal/samples/autoheartbeat/interceptor/AutoHeartbeatWorkerInterceptor.java ================================================ /* * Copyright (c) 2020 Temporal Technologies, Inc. All Rights Reserved * * Copyright 2012-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Modifications copyright (C) 2017 Uber Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not * use this file except in compliance with the License. A copy of the License is * located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package io.temporal.samples.autoheartbeat.interceptor; import io.temporal.common.interceptors.ActivityInboundCallsInterceptor; import io.temporal.common.interceptors.WorkerInterceptorBase; public class AutoHeartbeatWorkerInterceptor extends WorkerInterceptorBase { @Override public ActivityInboundCallsInterceptor interceptActivity(ActivityInboundCallsInterceptor next) { return new AutoHeartbeatActivityInboundCallsInterceptor(next); } } ================================================ FILE: core/src/main/java/io/temporal/samples/autoheartbeat/workflows/AutoWorkflow.java ================================================ /* * Copyright (c) 2020 Temporal Technologies, Inc. All Rights Reserved * * Copyright 2012-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Modifications copyright (C) 2017 Uber Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not * use this file except in compliance with the License. A copy of the License is * located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package io.temporal.samples.autoheartbeat.workflows; import io.temporal.workflow.SignalMethod; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; @WorkflowInterface public interface AutoWorkflow { @WorkflowMethod String exec(String input); @SignalMethod void cancelActivity(); } ================================================ FILE: core/src/main/java/io/temporal/samples/autoheartbeat/workflows/AutoWorkflowImpl.java ================================================ /* * Copyright (c) 2020 Temporal Technologies, Inc. All Rights Reserved * * Copyright 2012-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Modifications copyright (C) 2017 Uber Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not * use this file except in compliance with the License. A copy of the License is * located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package io.temporal.samples.autoheartbeat.workflows; import io.temporal.activity.ActivityCancellationType; import io.temporal.activity.ActivityOptions; import io.temporal.common.RetryOptions; import io.temporal.failure.ActivityFailure; import io.temporal.failure.CanceledFailure; import io.temporal.failure.TimeoutFailure; import io.temporal.samples.autoheartbeat.activities.AutoActivities; import io.temporal.workflow.CancellationScope; import io.temporal.workflow.Workflow; import java.time.Duration; public class AutoWorkflowImpl implements AutoWorkflow { private CancellationScope scope; @Override public String exec(String input) { AutoActivities activitiesOne = Workflow.newActivityStub( AutoActivities.class, ActivityOptions.newBuilder() .setStartToCloseTimeout(Duration.ofSeconds(22)) .setHeartbeatTimeout(Duration.ofSeconds(8)) .setCancellationType(ActivityCancellationType.WAIT_CANCELLATION_COMPLETED) // for sample purposes .setRetryOptions(RetryOptions.newBuilder().setMaximumAttempts(3).build()) .build()); AutoActivities activitiesTwo = Workflow.newActivityStub( AutoActivities.class, ActivityOptions.newBuilder() .setStartToCloseTimeout(Duration.ofSeconds(20)) .setHeartbeatTimeout(Duration.ofSeconds(7)) .setCancellationType(ActivityCancellationType.WAIT_CANCELLATION_COMPLETED) // for sample purposes .setRetryOptions(RetryOptions.newBuilder().setMaximumAttempts(3).build()) .build()); // Start our activity in CancellationScope so we can cancel it if needed scope = Workflow.newCancellationScope( () -> { activitiesOne.runActivityOne(input); activitiesTwo.runActivityTwo(input); }); try { scope.run(); } catch (ActivityFailure e) { if (e.getCause() instanceof CanceledFailure) { // We dont want workflow to fail in we canceled our scope, just log and return return "Workflow result after activity cancellation"; } else if (e.getCause() instanceof TimeoutFailure) { return "Workflow result after activity timeout of type: " + ((TimeoutFailure) e.getCause()).getTimeoutType().name(); } else { throw e; } } return "completed"; } @Override public void cancelActivity() { scope.cancel("Canceling scope from signal handler"); } } ================================================ FILE: core/src/main/java/io/temporal/samples/batch/heartbeatingactivity/HeartbeatingActivityBatchStarter.java ================================================ package io.temporal.samples.batch.heartbeatingactivity; import static io.temporal.samples.batch.heartbeatingactivity.HeartbeatingActivityBatchWorker.TASK_QUEUE; import io.temporal.api.common.v1.WorkflowExecution; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import java.io.IOException; /** Starts a single execution of HeartbeatingActivityBatchWorkflow. */ public class HeartbeatingActivityBatchStarter { public static void main(String[] args) { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient workflowClient = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); WorkflowOptions options = WorkflowOptions.newBuilder().setTaskQueue(TASK_QUEUE).build(); HeartbeatingActivityBatchWorkflow batchWorkflow = workflowClient.newWorkflowStub(HeartbeatingActivityBatchWorkflow.class, options); WorkflowExecution execution = WorkflowClient.start(batchWorkflow::processBatch); System.out.println( "Started batch workflow. WorkflowId=" + execution.getWorkflowId() + ", RunId=" + execution.getRunId()); System.exit(0); } } ================================================ FILE: core/src/main/java/io/temporal/samples/batch/heartbeatingactivity/HeartbeatingActivityBatchWorker.java ================================================ package io.temporal.samples.batch.heartbeatingactivity; import io.temporal.client.WorkflowClient; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import java.io.IOException; /** * A worker process that hosts implementations of HeartbeatingActivityBatchWorkflow and * RecordProcessorActivity. */ public final class HeartbeatingActivityBatchWorker { static final String TASK_QUEUE = "HeartbeatingActivityBatch"; public static void main(String[] args) { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); WorkerFactory factory = WorkerFactory.newInstance(client); Worker worker = factory.newWorker(TASK_QUEUE); worker.registerWorkflowImplementationTypes(HeartbeatingActivityBatchWorkflowImpl.class); worker.registerActivitiesImplementations( new RecordProcessorActivityImpl(new RecordLoaderImpl(), new RecordProcessorImpl())); factory.start(); System.out.println("Worker started for task queue: " + TASK_QUEUE); } } ================================================ FILE: core/src/main/java/io/temporal/samples/batch/heartbeatingactivity/HeartbeatingActivityBatchWorkflow.java ================================================ package io.temporal.samples.batch.heartbeatingactivity; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; @WorkflowInterface public interface HeartbeatingActivityBatchWorkflow { /** * Processes the batch of records. * * @return total number of processed records. */ @WorkflowMethod int processBatch(); } ================================================ FILE: core/src/main/java/io/temporal/samples/batch/heartbeatingactivity/HeartbeatingActivityBatchWorkflowImpl.java ================================================ package io.temporal.samples.batch.heartbeatingactivity; import io.temporal.activity.ActivityOptions; import io.temporal.workflow.Workflow; import java.time.Duration; /** * A sample implementation of processing a batch by an activity. * *

An activity can run as long as needed. It reports that it is still alive through heartbeat. If * the worker is restarted the activity is retried after the heartbeat timeout. Temporal allows * store data in heartbeat _details_. These details are available to the next activity attempt. The * progress of the record processing is stored in the details to avoid reprocessing records from the * beginning on failures. */ public final class HeartbeatingActivityBatchWorkflowImpl implements HeartbeatingActivityBatchWorkflow { /** * Activity that is used to process batch records. The start-to-close timeout is set to a high * value to support large batch sizes. Heartbeat timeout is required to quickly restart the * activity in case of failures. The heartbeat timeout is also needed to record heartbeat details * at the service. */ private final RecordProcessorActivity recordProcessor = Workflow.newActivityStub( RecordProcessorActivity.class, ActivityOptions.newBuilder() .setStartToCloseTimeout(Duration.ofHours(1)) .setHeartbeatTimeout(Duration.ofSeconds(10)) .build()); @Override public int processBatch() { // No special logic needed here as activity is retried automatically by the service. return recordProcessor.processRecords(); } } ================================================ FILE: core/src/main/java/io/temporal/samples/batch/heartbeatingactivity/README.md ================================================ A sample implementation of processing a batch by an Activity. An Activity can run as long as needed. It reports that it is still alive through Heartbeat. If the Worker is restarted, the Activity is retried after the Heartbeat Timeout. Temporal allows store data in Heartbeat _details_. These details are available to the next Activity attempt. The progress of the record processing is stored in the details to avoid reprocessing records from the beginning on failures. #### Running the Iterator Batch Sample The sample has two executables. Execute each command in a separate terminal window. The first command runs the Worker that hosts the Workflow and Activity Executions. Restart the worker while the batch is executing to see how activity timeout and retry work. ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.batch.heartbeatingactivity.HeartbeatingActivityBatchWorker ``` The second command start the Workflow Execution. Each time the command runs, it starts a new Workflow Execution. ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.batch.heartbeatingactivity.HeartbeatingActivityBatchStarter ``` ================================================ FILE: core/src/main/java/io/temporal/samples/batch/heartbeatingactivity/RecordLoader.java ================================================ package io.temporal.samples.batch.heartbeatingactivity; import java.util.Optional; /** * Helper class that is used to iterate over a list of records. * *

A specific implementation depends on a use case. For example, it can execute an SQL DB query * or read a comma delimited file. More complex use cases would need passing a different type of * offset parameter. */ public interface RecordLoader { /** * Returns the next record. * * @param offset offset of the next record. * @return Record at the offset. Empty optional if offset exceeds the dataset size. */ Optional getRecord(int offset); } ================================================ FILE: core/src/main/java/io/temporal/samples/batch/heartbeatingactivity/RecordLoaderImpl.java ================================================ package io.temporal.samples.batch.heartbeatingactivity; import java.util.Optional; /** Fake implementation of RecordLoader. */ public final class RecordLoaderImpl implements RecordLoader { static final int RECORD_COUNT = 1000; @Override public Optional getRecord(int offset) { if (offset >= RECORD_COUNT) { return Optional.empty(); } return Optional.of(new SingleRecord(offset)); } } ================================================ FILE: core/src/main/java/io/temporal/samples/batch/heartbeatingactivity/RecordProcessor.java ================================================ package io.temporal.samples.batch.heartbeatingactivity; /** A helper class that implements record processing. */ public interface RecordProcessor { /** * Processes a single record. * * @param record record to process */ void processRecord(SingleRecord record); } ================================================ FILE: core/src/main/java/io/temporal/samples/batch/heartbeatingactivity/RecordProcessorActivity.java ================================================ package io.temporal.samples.batch.heartbeatingactivity; import io.temporal.activity.ActivityInterface; @ActivityInterface public interface RecordProcessorActivity { /** Processes all records in the dataset */ int processRecords(); } ================================================ FILE: core/src/main/java/io/temporal/samples/batch/heartbeatingactivity/RecordProcessorActivityImpl.java ================================================ package io.temporal.samples.batch.heartbeatingactivity; import io.temporal.activity.Activity; import io.temporal.activity.ActivityExecutionContext; import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * RecordProcessorActivity implementation. * *

It relies on RecordLoader to iterate over set of records and process them one by one. The * heartbeat is used to remember offset. On activity retry the data from the last recorded heartbeat * is used to minimize the number of records that are reprocessed. Note that not every heartbeat * call is sent to the service. The frequency of the heartbeat service calls depends on the * heartbeat timeout the activity was scheduled with. If no heartbeat timeout is not set then no * heartbeat is ever sent to the service. * *

The biggest advantage of this approach is efficiency. It uses very few Temporal resources. * *

The biggest limitation of this approach is that it cannot deal with record processing * failures. The only options are either failing the whole batch or skip the record. While it is * possible to build additional logic to record failed records somewhere the experience is not * seamless. */ public class RecordProcessorActivityImpl implements RecordProcessorActivity { private static final Logger log = LoggerFactory.getLogger(RecordProcessorActivityImpl.class); private final RecordLoader recordLoader; private final RecordProcessor recordProcessor; public RecordProcessorActivityImpl(RecordLoader recordLoader, RecordProcessor recordProcessor) { this.recordLoader = recordLoader; this.recordProcessor = recordProcessor; } @Override public int processRecords() { // On activity retry load the last reported offset from the heartbeat details. ActivityExecutionContext context = Activity.getExecutionContext(); Optional heartbeatDetails = context.getHeartbeatDetails(Integer.class); int offset = heartbeatDetails.orElse(0); log.info("Activity processRecords started with offset=" + offset); // This sample implementation processes records one by one. // If needed it can be changed to use a pool of threads or asynchronous code to process multiple // such records in parallel. while (true) { Optional record = recordLoader.getRecord(offset); if (!record.isPresent()) { return offset; } recordProcessor.processRecord(record.get()); // Report that activity is still alive. The assumption is that each record takes less time // to process than the heartbeat timeout. // Leverage heartbeat details to record offset. context.heartbeat(offset); offset++; } } } ================================================ FILE: core/src/main/java/io/temporal/samples/batch/heartbeatingactivity/RecordProcessorImpl.java ================================================ package io.temporal.samples.batch.heartbeatingactivity; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** Fake record processor implementation. */ public final class RecordProcessorImpl implements RecordProcessor { private static final Logger log = LoggerFactory.getLogger(RecordProcessorImpl.class); @Override public void processRecord(SingleRecord record) { // Fake processing logic try { Thread.sleep(100); log.info("Processed " + record); } catch (InterruptedException ignored) { return; } } } ================================================ FILE: core/src/main/java/io/temporal/samples/batch/heartbeatingactivity/SingleRecord.java ================================================ package io.temporal.samples.batch.heartbeatingactivity; /** Record to process. A real application would add a use case specific data. */ public class SingleRecord { private int id; public SingleRecord(int id) { this.id = id; } /** JSON deserializer needs it */ public SingleRecord() {} public int getId() { return id; } @Override public String toString() { return "Record{" + "id=" + id + '}'; } } ================================================ FILE: core/src/main/java/io/temporal/samples/batch/iterator/IteratorBatchStarter.java ================================================ package io.temporal.samples.batch.iterator; import static io.temporal.samples.batch.iterator.IteratorBatchWorker.TASK_QUEUE; import io.temporal.api.common.v1.WorkflowExecution; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import java.io.IOException; /** Starts a single execution of IteratorBatchWorkflow. */ public class IteratorBatchStarter { public static void main(String[] args) { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient workflowClient = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); WorkflowOptions options = WorkflowOptions.newBuilder().setTaskQueue(TASK_QUEUE).build(); IteratorBatchWorkflow batchWorkflow = workflowClient.newWorkflowStub(IteratorBatchWorkflow.class, options); WorkflowExecution execution = WorkflowClient.start(batchWorkflow::processBatch, 5, 0); System.out.println( "Started batch workflow. WorkflowId=" + execution.getWorkflowId() + ", RunId=" + execution.getRunId()); System.exit(0); } } ================================================ FILE: core/src/main/java/io/temporal/samples/batch/iterator/IteratorBatchWorker.java ================================================ package io.temporal.samples.batch.iterator; import io.temporal.client.WorkflowClient; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import java.io.IOException; /** * A worker process that hosts implementations of IteratorBatchWorkflow and RecordProcessorWorkflow * as well as RecordLoader activity. */ public final class IteratorBatchWorker { static final String TASK_QUEUE = "IteratorBatch"; public static void main(String[] args) { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); WorkerFactory factory = WorkerFactory.newInstance(client); Worker worker = factory.newWorker(TASK_QUEUE); worker.registerWorkflowImplementationTypes( IteratorBatchWorkflowImpl.class, RecordProcessorWorkflowImpl.class); worker.registerActivitiesImplementations(new RecordLoaderImpl()); factory.start(); System.out.println("Worker started for task queue: " + TASK_QUEUE); } } ================================================ FILE: core/src/main/java/io/temporal/samples/batch/iterator/IteratorBatchWorkflow.java ================================================ package io.temporal.samples.batch.iterator; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; @WorkflowInterface public interface IteratorBatchWorkflow { /** * Processes the batch of records. * * @param offset the offset of the first record to process. 0 to start the batch processing. * @param pageSize the number of records to process in a single workflow run. * @return total number of processed records. */ @WorkflowMethod int processBatch(int pageSize, int offset); } ================================================ FILE: core/src/main/java/io/temporal/samples/batch/iterator/IteratorBatchWorkflowImpl.java ================================================ package io.temporal.samples.batch.iterator; import io.temporal.activity.ActivityOptions; import io.temporal.workflow.Async; import io.temporal.workflow.ChildWorkflowOptions; import io.temporal.workflow.Promise; import io.temporal.workflow.Workflow; import java.time.Duration; import java.util.ArrayList; import java.util.List; /** * Implements iterator workflow pattern. * *

A single workflow run processes a single page of records in parallel. Each record is processed * using its own RecordProcessorWorkflow child workflow. * *

After all child workflows complete the new run of the parent workflow is created using * continue as new. The new run processes the next page of records. This way practically unlimited * set of records can be processed. */ public final class IteratorBatchWorkflowImpl implements IteratorBatchWorkflow { private final RecordLoader recordLoader = Workflow.newActivityStub( RecordLoader.class, ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(5)).build()); /** Stub used to continue-as-new. */ private final IteratorBatchWorkflow nextRun = Workflow.newContinueAsNewStub(IteratorBatchWorkflow.class); @Override public int processBatch(int pageSize, int offset) { // Loads a page of records List records = recordLoader.getRecords(pageSize, offset); // Starts a child per record asynchrnously. List> results = new ArrayList<>(records.size()); for (SingleRecord record : records) { // Uses human friendly child id. String childId = Workflow.getInfo().getWorkflowId() + "/" + record.getId(); RecordProcessorWorkflow processor = Workflow.newChildWorkflowStub( RecordProcessorWorkflow.class, ChildWorkflowOptions.newBuilder().setWorkflowId(childId).build()); Promise result = Async.procedure(processor::processRecord, record); results.add(result); } // Waits for all children to complete. Promise.allOf(results).get(); // Skips error handling for the sample brevity. // So failed RecordProcessorWorkflows are ignored. // No more records in the dataset. Completes the workflow. if (records.isEmpty()) { return offset; } // Continues as new with the increased offset. return nextRun.processBatch(pageSize, offset + records.size()); } } ================================================ FILE: core/src/main/java/io/temporal/samples/batch/iterator/README.md ================================================ A sample implementation of the Workflow iterator pattern. A workflow starts a configured number of Child Workflows in parallel. Each child processes a single record. After all children complete, the parent calls continue-as-new and starts the children for the next page of records. This allows processing a set of records of any size. The advantage of this approach is simplicity. The main disadvantage is that it processes records in batches, with each batch waiting for the slowest child workflow. A variation of this pattern runs activities instead of child workflows. #### Running the Iterator Batch Sample The sample has two executables. Execute each command in a separate terminal window. The first command runs the Worker that hosts the Workflow and Activity Executions. ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.batch.iterator.IteratorBatchWorker ``` The second command start the Workflow Execution. Each time the command runs, it starts a new Workflow Execution. ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.batch.iterator.IteratorBatchStarter ``` ================================================ FILE: core/src/main/java/io/temporal/samples/batch/iterator/RecordLoader.java ================================================ package io.temporal.samples.batch.iterator; import io.temporal.activity.ActivityInterface; import java.util.List; /** * Activity that is used to iterate over a list of records. * *

A specific implementation depends on a use case. For example, it can execute an SQL DB query * or read a comma delimited file. More complex use cases would need passing a different type of * offset parameter. */ @ActivityInterface public interface RecordLoader { /** * Returns the next page of records. * * @param offset offset of the next page. * @param pageSize maximum number of records to return. * @return empty list if no more records to process. */ List getRecords(int pageSize, int offset); } ================================================ FILE: core/src/main/java/io/temporal/samples/batch/iterator/RecordLoaderImpl.java ================================================ package io.temporal.samples.batch.iterator; import java.util.ArrayList; import java.util.List; /** Fake implementation of RecordLoader. */ public final class RecordLoaderImpl implements RecordLoader { // The sample always returns 5 pages. // The real application would iterate over an existing dataset or file. public static final int PAGE_COUNT = 5; @Override public List getRecords(int pageSize, int offset) { List records = new ArrayList<>(pageSize); if (offset < pageSize * PAGE_COUNT) { for (int i = 0; i < pageSize; i++) { records.add(new SingleRecord(offset + i)); } } return records; } } ================================================ FILE: core/src/main/java/io/temporal/samples/batch/iterator/RecordProcessorWorkflow.java ================================================ package io.temporal.samples.batch.iterator; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; /** Workflow that implements processing of a single record. */ @WorkflowInterface public interface RecordProcessorWorkflow { /** Processes a single record */ @WorkflowMethod void processRecord(SingleRecord r); } ================================================ FILE: core/src/main/java/io/temporal/samples/batch/iterator/RecordProcessorWorkflowImpl.java ================================================ package io.temporal.samples.batch.iterator; import io.temporal.workflow.Workflow; import java.time.Duration; import java.util.Random; import org.slf4j.Logger; /** Fake RecordProcessorWorkflow implementation. */ public class RecordProcessorWorkflowImpl implements RecordProcessorWorkflow { public static final Logger log = Workflow.getLogger(RecordProcessorWorkflowImpl.class); private final Random random = Workflow.newRandom(); @Override public void processRecord(SingleRecord r) { // Simulate some processing Workflow.sleep(Duration.ofSeconds(random.nextInt(30))); log.info("Processed " + r); } } ================================================ FILE: core/src/main/java/io/temporal/samples/batch/iterator/SingleRecord.java ================================================ package io.temporal.samples.batch.iterator; /** Record to process. A real application would add a use case specific data. */ public class SingleRecord { private int id; public SingleRecord(int id) { this.id = id; } /** JSON deserializer needs it */ public SingleRecord() {} public int getId() { return id; } @Override public String toString() { return "SingleRecord{" + "id=" + id + '}'; } } ================================================ FILE: core/src/main/java/io/temporal/samples/batch/slidingwindow/BatchProgress.java ================================================ package io.temporal.samples.batch.slidingwindow; import java.util.Set; /** Used as a result of {@link SlidingWindowBatchWorkflow#getProgress()} query. */ public final class BatchProgress { private final int progress; private final Set currentRecords; public BatchProgress(int progress, Set currentRecords) { this.progress = progress; this.currentRecords = currentRecords; } /** Count of completed record processing child workflows. */ public int getProgress() { return progress; } /** Ids of records that are currently being processed by child workflows. */ public Set getCurrentRecords() { return currentRecords; } } ================================================ FILE: core/src/main/java/io/temporal/samples/batch/slidingwindow/BatchWorkflow.java ================================================ package io.temporal.samples.batch.slidingwindow; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; @WorkflowInterface public interface BatchWorkflow { /** * Processes a batch of records using multiple parallel sliding window workflows. * * @param pageSize the number of records to start processing in a single sliding window workflow * run. * @param slidingWindowSize the number of records to process in parallel by a single sliding * window workflow. Can be larger than the pageSize. * @param partitions defines the number of SlidingWindowBatchWorkflows to run in parallel. If * number of partitions is too low the update rate of a single SlidingWindowBatchWorkflows can * get too high. * @return total number of processed records. */ @WorkflowMethod int processBatch(int pageSize, int slidingWindowSize, int partitions); } ================================================ FILE: core/src/main/java/io/temporal/samples/batch/slidingwindow/BatchWorkflowImpl.java ================================================ package io.temporal.samples.batch.slidingwindow; import io.temporal.activity.ActivityOptions; import io.temporal.workflow.Async; import io.temporal.workflow.ChildWorkflowOptions; import io.temporal.workflow.Promise; import io.temporal.workflow.Workflow; import java.time.Duration; import java.util.ArrayList; import java.util.List; /** Implements BatchWorkflow by running multiple SlidingWindowBatchWorkflows in parallel. */ public class BatchWorkflowImpl implements BatchWorkflow { private final RecordLoader recordLoader = Workflow.newActivityStub( RecordLoader.class, ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(5)).build()); @Override public int processBatch(int pageSize, int slidingWindowSize, int partitions) { // The sample partitions the data set into continuous ranges. // A real application can choose any other way to divide the records into multiple collections. int totalCount = recordLoader.getRecordCount(); int partitionSize = totalCount / partitions + (totalCount % partitions > 0 ? 1 : 0); List> results = new ArrayList<>(partitions); for (int i = 0; i < partitions; i++) { // Makes child id more user-friendly String childId = Workflow.getInfo().getWorkflowId() + "/" + i; SlidingWindowBatchWorkflow partitionWorkflow = Workflow.newChildWorkflowStub( SlidingWindowBatchWorkflow.class, ChildWorkflowOptions.newBuilder().setWorkflowId(childId).build()); // Define partition boundaries. int offset = partitionSize * i; int maximumOffset = Math.min(offset + partitionSize, totalCount); ProcessBatchInput input = new ProcessBatchInput(); input.setPageSize(pageSize); input.setSlidingWindowSize(slidingWindowSize); input.setOffset(offset); input.setMaximumOffset(maximumOffset); Promise partitionResult = Async.function(partitionWorkflow::processBatch, input); results.add(partitionResult); } int result = 0; for (Promise partitionResult : results) { result += partitionResult.get(); } return result; } } ================================================ FILE: core/src/main/java/io/temporal/samples/batch/slidingwindow/ProcessBatchInput.java ================================================ package io.temporal.samples.batch.slidingwindow; import java.util.HashSet; import java.util.Set; /** Input of {@link SlidingWindowBatchWorkflow#processBatch(ProcessBatchInput)} */ public final class ProcessBatchInput { private int pageSize; private int slidingWindowSize; int offset; private int maximumOffset; private int progress; private Set currentRecords = new HashSet<>(); /** the number of records to load in a single RecordLoader.getRecords call. */ public void setPageSize(int pageSize) { this.pageSize = pageSize; } /** the number of parallel record processing child workflows to execute. */ public void setSlidingWindowSize(int slidingWindowSize) { this.slidingWindowSize = slidingWindowSize; } /** index of the first record to process. 0 to start the batch processing. */ public void setOffset(int offset) { this.offset = offset; } /** The maximum offset (exclusive) to process by this workflow. */ public void setMaximumOffset(int maximumOffset) { this.maximumOffset = maximumOffset; } /** Total number of records processed so far by this workflow. */ public void setProgress(int progress) { this.progress = progress; } /** * Ids of records that are being processed by child workflows. * *

This puts a limit on the sliding window size as workflow arguments cannot exceed 2MB in JSON * format. Another practical limit is the number of signals a workflow can handle per second. * Adjust the number of partitions to keep this rate at a reasonable value. */ public void setCurrentRecords(Set currentRecords) { this.currentRecords = currentRecords; } public int getPageSize() { return pageSize; } public int getSlidingWindowSize() { return slidingWindowSize; } public int getOffset() { return offset; } public int getMaximumOffset() { return maximumOffset; } public int getProgress() { return progress; } public Set getCurrentRecords() { return currentRecords; } } ================================================ FILE: core/src/main/java/io/temporal/samples/batch/slidingwindow/README.md ================================================ A sample implementation of a batch processing Workflow that maintains a sliding window of record processing Workflows. A Workflow starts a configured number of Child Workflows in parallel. Each child processes a single record. When a child completes a new child immediately started. A Parent Workflow calls continue-as-new after starting a preconfigured number of children. A child completion is reported through a Signal as a parent cannot directly wait for a child started by a previous run. Multiple instances of SlidingWindowBatchWorkflow run in parallel each processing a subset of records to support higher total rate of processing. #### Running the Sliding Window Batch Sample The sample has two executables. Execute each command in a separate terminal window. The first command runs the Worker that hosts the Workflow and Activity Executions. ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.batch.slidingwindow.SlidingWindowBatchWorker ``` Note that `Caused by: io.grpc.StatusRuntimeException: INVALID_ARGUMENT: UnhandledCommand` info messages in the output are expected and benign. They ensure that signals are not lost when there is a race condition between workflow calling continue-as-new and receiving a signal. If these messages appear too frequently consider increasing the number of partitions parameter passed to `BatchWorkflow.processBatch`. They will completely disappear when [Issue 1289](https://github.com/temporalio/temporal/issues/1289) is implemented. The second command start the BatchWorkflow Execution. Each time the command runs, it starts a new BatchWorkflow Execution. ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.batch.slidingwindow.SlidingWindowBatchStarter ``` ================================================ FILE: core/src/main/java/io/temporal/samples/batch/slidingwindow/RecordIterable.java ================================================ package io.temporal.samples.batch.slidingwindow; import io.temporal.activity.ActivityOptions; import io.temporal.workflow.Workflow; import java.time.Duration; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import org.jetbrains.annotations.NotNull; /** Iterable implementation that relies on RecordLoader activity. */ public class RecordIterable implements Iterable { /** * Iterator implementation that relies on RecordLoader activity. * *

This code assumes that RecordLoader.getRecords never returns a failure to the workflow. The * real production application might make a different design choice. */ private class RecordIterator implements Iterator { /** * The last page of records loaded through RecordLoader activity. The activity returns an empty * page to indicate the end of iteration. */ private List lastPage; /** The offset of the last loaded batch of records. */ private int offset; /** Index into the last loaded page of the next record to return. */ private int index; RecordIterator() { this.offset = initialOffset; if (initialOffset > maximumOffset) { this.lastPage = new ArrayList<>(); } else { int size = Math.min(pageSize, maximumOffset - offset); this.lastPage = recordLoader.getRecords(size, offset); } } @Override public boolean hasNext() { return !lastPage.isEmpty(); } @Override public SingleRecord next() { int size = lastPage.size(); if (size == 0) { throw new NoSuchElementException(); } SingleRecord result = lastPage.get(index++); if (size == index) { offset += index; index = 0; lastPage = recordLoader.getRecords(pageSize, offset); } return result; } } private final int initialOffset; private final int pageSize; private final int maximumOffset; private final RecordLoader recordLoader = Workflow.newActivityStub( RecordLoader.class, ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(5)).build()); /** * @param pageSize size of a single page to load. * @param initialOffset the initial offset to load records from. * @param maximumOffset the maximum offset (exclusive). */ public RecordIterable(int pageSize, int initialOffset, int maximumOffset) { this.pageSize = pageSize; this.initialOffset = initialOffset; this.maximumOffset = maximumOffset; } @NotNull @Override public Iterator iterator() { return new RecordIterator(); } } ================================================ FILE: core/src/main/java/io/temporal/samples/batch/slidingwindow/RecordLoader.java ================================================ package io.temporal.samples.batch.slidingwindow; import io.temporal.activity.ActivityInterface; import java.util.List; @ActivityInterface public interface RecordLoader { /** * Returns the next page of records. * * @param offset offset of the next page. * @param pageSize maximum number of records to return. * @return empty list if no more records to process. */ List getRecords(int pageSize, int offset); /** * Returns the total record count. * *

Used to divide record ranges among partitions. Some applications might choose a completely * different approach for partitioning the data set. */ int getRecordCount(); } ================================================ FILE: core/src/main/java/io/temporal/samples/batch/slidingwindow/RecordLoaderImpl.java ================================================ package io.temporal.samples.batch.slidingwindow; import java.util.ArrayList; import java.util.List; /** Fake loader implementation. The real application would iterate over a dataset or file. */ public final class RecordLoaderImpl implements RecordLoader { private static final int TOTAL_COUNT = 300; @Override public List getRecords(int pageSize, int offset) { List records = new ArrayList<>(pageSize); if (offset < TOTAL_COUNT) { for (int i = offset; i < Math.min(offset + pageSize, TOTAL_COUNT); i++) { records.add(new SingleRecord(i)); } } return records; } @Override public int getRecordCount() { return TOTAL_COUNT; } } ================================================ FILE: core/src/main/java/io/temporal/samples/batch/slidingwindow/RecordProcessorWorkflow.java ================================================ package io.temporal.samples.batch.slidingwindow; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; /** Workflow that implements processing of a single record. */ @WorkflowInterface public interface RecordProcessorWorkflow { /** * Processes a single record. Must report completion to a parent through {@link * SlidingWindowBatchWorkflow#reportCompletion(int)} */ @WorkflowMethod void processRecord(SingleRecord r); } ================================================ FILE: core/src/main/java/io/temporal/samples/batch/slidingwindow/RecordProcessorWorkflowImpl.java ================================================ package io.temporal.samples.batch.slidingwindow; import io.temporal.workflow.Workflow; import java.time.Duration; import java.util.Optional; import java.util.Random; import org.slf4j.Logger; /** Fake RecordProcessorWorkflow implementation. */ public final class RecordProcessorWorkflowImpl implements RecordProcessorWorkflow { public static final Logger log = Workflow.getLogger(RecordProcessorWorkflowImpl.class); private final Random random = Workflow.newRandom(); @Override public void processRecord(SingleRecord r) { processRecordImpl(r); // This workflow is always expected to have a parent. // But for unit testing it might be useful to skip the notification. Optional parentWorkflowId = Workflow.getInfo().getParentWorkflowId(); if (parentWorkflowId.isPresent()) { String parentId = parentWorkflowId.get(); SlidingWindowBatchWorkflow parent = Workflow.newExternalWorkflowStub(SlidingWindowBatchWorkflow.class, parentId); // Notify parent about record processing completion parent.reportCompletion(r.getId()); } } /** Application specific record processing logic goes here. */ private void processRecordImpl(SingleRecord r) { // Simulate some processing Workflow.sleep(Duration.ofSeconds(random.nextInt(10))); log.info("Processed " + r); } } ================================================ FILE: core/src/main/java/io/temporal/samples/batch/slidingwindow/SingleRecord.java ================================================ package io.temporal.samples.batch.slidingwindow; /** Record to process. */ public class SingleRecord { private int id; public SingleRecord(int id) { this.id = id; } /** Needed for JSON deserialization. */ public SingleRecord() {} public int getId() { return id; } @Override public String toString() { return "SingleRecord{" + "id=" + id + '}'; } } ================================================ FILE: core/src/main/java/io/temporal/samples/batch/slidingwindow/SlidingWindowBatchStarter.java ================================================ package io.temporal.samples.batch.slidingwindow; import static io.temporal.samples.batch.slidingwindow.SlidingWindowBatchWorker.TASK_QUEUE; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import java.io.IOException; public class SlidingWindowBatchStarter { @SuppressWarnings("CatchAndPrintStackTrace") public static void main(String[] args) { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient workflowClient = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); WorkflowOptions options = WorkflowOptions.newBuilder().setTaskQueue(TASK_QUEUE).build(); BatchWorkflow batchWorkflow = workflowClient.newWorkflowStub(BatchWorkflow.class, options); WorkflowClient.start(batchWorkflow::processBatch, 10, 25, 3); System.out.println("Started batch workflow with 3 partitions"); System.exit(0); } } ================================================ FILE: core/src/main/java/io/temporal/samples/batch/slidingwindow/SlidingWindowBatchWorker.java ================================================ package io.temporal.samples.batch.slidingwindow; import io.temporal.client.WorkflowClient; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import java.io.IOException; /** Hosts sliding window batch sample workflow and activity implementations. */ public final class SlidingWindowBatchWorker { static final String TASK_QUEUE = "SlidingWindow"; public static void main(String[] args) { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); WorkerFactory factory = WorkerFactory.newInstance(client); Worker worker = factory.newWorker(TASK_QUEUE); worker.registerWorkflowImplementationTypes( BatchWorkflowImpl.class, SlidingWindowBatchWorkflowImpl.class, RecordProcessorWorkflowImpl.class); worker.registerActivitiesImplementations(new RecordLoaderImpl()); factory.start(); System.out.println("Worker started for task queue: " + TASK_QUEUE); } } ================================================ FILE: core/src/main/java/io/temporal/samples/batch/slidingwindow/SlidingWindowBatchWorkflow.java ================================================ package io.temporal.samples.batch.slidingwindow; import io.temporal.workflow.QueryMethod; import io.temporal.workflow.SignalMethod; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; @WorkflowInterface public interface SlidingWindowBatchWorkflow { /** * Process the batch of records. * * @return total number of processed records. */ @WorkflowMethod int processBatch(ProcessBatchInput input); @SignalMethod void reportCompletion(int recordId); @QueryMethod BatchProgress getProgress(); } ================================================ FILE: core/src/main/java/io/temporal/samples/batch/slidingwindow/SlidingWindowBatchWorkflowImpl.java ================================================ package io.temporal.samples.batch.slidingwindow; import io.temporal.api.common.v1.WorkflowExecution; import io.temporal.api.enums.v1.ParentClosePolicy; import io.temporal.workflow.*; import java.util.*; /** * Implements batch processing by executing a specified number of workflows in parallel. A new * record processing workflow is started when a previously started one completes. The child * completion is reported through reportCompletion signal as it is not yet possible to passively * wait for a workflow that was started by a previous run. * *

Calls continue-as-new after starting 100 children. Note that the sliding window size can be * larger than 100. */ public final class SlidingWindowBatchWorkflowImpl implements SlidingWindowBatchWorkflow { /** Stub used to call continue-as-new. */ private final SlidingWindowBatchWorkflow nextRun = Workflow.newContinueAsNewStub(SlidingWindowBatchWorkflow.class); /** Contains ids of records that are being processed by child workflows. */ private Set currentRecords; /** * Used to accumulate records to remove for signals delivered before processBatch method started * execution */ private Set recordsToRemove = new HashSet<>(); /** Count of completed record processing child workflows. */ private int progress; /** * @return number of processed records */ @Override public int processBatch(ProcessBatchInput input) { WorkflowInfo info = Workflow.getInfo(); this.progress = input.getProgress(); this.currentRecords = input.getCurrentRecords(); // Remove records for signals delivered before the workflow run started. int countBefore = this.currentRecords.size(); this.currentRecords.removeAll(recordsToRemove); this.progress += countBefore - this.currentRecords.size(); int pageSize = input.getPageSize(); int offset = input.getOffset(); int maximumOffset = input.getMaximumOffset(); int slidingWindowSize = input.getSlidingWindowSize(); Iterable records = new RecordIterable(pageSize, offset, maximumOffset); List> childrenStartedByThisRun = new ArrayList<>(); Iterator recordIterator = records.iterator(); while (true) { // After starting slidingWindowSize children blocks until a completion signal is received. Workflow.await(() -> currentRecords.size() < slidingWindowSize); // Completes workflow, if no more records to process. if (!recordIterator.hasNext()) { // Awaits for all children to complete Workflow.await(() -> currentRecords.size() == 0); return offset + childrenStartedByThisRun.size(); } SingleRecord record = recordIterator.next(); // Uses ParentClosePolicy ABANDON to ensure that children survive continue-as-new of a parent. // Assigns user-friendly child workflow id. ChildWorkflowOptions childWorkflowOptions = ChildWorkflowOptions.newBuilder() .setParentClosePolicy(ParentClosePolicy.PARENT_CLOSE_POLICY_ABANDON) .setWorkflowId(info.getWorkflowId() + "/" + record.getId()) .build(); RecordProcessorWorkflow processor = Workflow.newChildWorkflowStub(RecordProcessorWorkflow.class, childWorkflowOptions); // Starts a child workflow asynchronously ignoring its result. // The assumption is that the parent workflow doesn't need to deal with child workflow // results and failures. Another assumption is that a child in any situation calls // the reportCompletion signal. Async.procedure(processor::processRecord, record); // Resolves when a child reported successful start. // Used to wait for a child start on continue-as-new. Promise childStartedPromise = Workflow.getWorkflowExecution(processor); childrenStartedByThisRun.add(childStartedPromise); currentRecords.add(record.getId()); // Continues-as-new after starting pageSize children if (childrenStartedByThisRun.size() == pageSize) { // Waits for all children to start. Without this wait, workflow completion through // continue-as-new might lead to a situation when they never start. // Assumes that they never fail to start as their automatically generated // IDs are not expected to collide. Promise.allOf(childrenStartedByThisRun).get(); // Continues as new to keep the history size bounded ProcessBatchInput newInput = new ProcessBatchInput(); newInput.setPageSize(pageSize); newInput.setSlidingWindowSize(slidingWindowSize); newInput.setOffset(offset + childrenStartedByThisRun.size()); newInput.setMaximumOffset(maximumOffset); newInput.setProgress(progress); newInput.setCurrentRecords(currentRecords); return nextRun.processBatch(newInput); } } } @Override public void reportCompletion(int recordId) { // Handle situation when signal handler is called before the workflow main method. if (currentRecords == null) { recordsToRemove.add(recordId); return; } // Dedupes signals as in some edge cases they can be duplicated. if (currentRecords.remove(recordId)) { progress++; } } @Override public BatchProgress getProgress() { return new BatchProgress(progress, currentRecords); } } ================================================ FILE: core/src/main/java/io/temporal/samples/bookingsaga/Booking.java ================================================ package io.temporal.samples.bookingsaga; public final class Booking { private String carReservationID; private String hotelReservationID; private String flightReservationID; /** Empty constructor to keep Jackson serializer happy. */ public Booking() {} public Booking(String carReservationID, String hotelReservationID, String flightReservationID) { this.carReservationID = carReservationID; this.hotelReservationID = hotelReservationID; this.flightReservationID = flightReservationID; } public String getCarReservationID() { return carReservationID; } public String getHotelReservationID() { return hotelReservationID; } public String getFlightReservationID() { return flightReservationID; } @Override public String toString() { return "Booking{" + "carReservationID='" + carReservationID + '\'' + ", hotelReservationID='" + hotelReservationID + '\'' + ", flightReservationID='" + flightReservationID + '\'' + '}'; } } ================================================ FILE: core/src/main/java/io/temporal/samples/bookingsaga/README.md ================================================ ## Saga example: trip booking Temporal implementation of the [Camunda BPMN trip booking example](https://github.com/berndruecker/trip-booking-saga-java) which demonstrates Temporal approach to SAGA. Run the following command to start the sample: ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.bookingsaga.TripBookingSaga ``` Note that the booking is expected to fail to demonstrate the compensation flow. Sample unit testing: [TripBookingWorkflowTest](https://github.com/temporalio/samples-java/blob/main/core/src/test/java/io/temporal/samples/bookingsaga/TripBookingWorkflowTest.java) ================================================ FILE: core/src/main/java/io/temporal/samples/bookingsaga/TripBookingActivities.java ================================================ package io.temporal.samples.bookingsaga; import io.temporal.activity.ActivityInterface; @ActivityInterface public interface TripBookingActivities { /** * Request a car rental reservation. * * @param requestId used for idempotency and compensation correlation. * @param name customer name * @return reservationID */ String reserveCar(String requestId, String name); /** * Request a flight reservation. * * @param requestId used for idempotency and compensation correlation. * @param name customer name * @return reservationID */ String bookFlight(String requestId, String name); /** * Request a hotel reservation. * * @param requestId used for idempotency and compensation correlation. * @param name customer name * @return reservationID */ String bookHotel(String requestId, String name); /** * Cancel a flight reservation. * * @param name customer name * @param requestId the same id is passed to bookFlight * @return cancellationConfirmationID */ String cancelFlight(String requestId, String name); /** * Cancel a hotel reservation. * * @param name customer name * @param requestId the same id is passed to bookHotel * @return cancellationConfirmationID */ String cancelHotel(String requestId, String name); /** * Cancel a car rental reservation. * * @param name customer name * @param requestId the same id is passed to reserveCar * @return cancellationConfirmationID */ String cancelCar(String requestId, String name); } ================================================ FILE: core/src/main/java/io/temporal/samples/bookingsaga/TripBookingActivitiesImpl.java ================================================ package io.temporal.samples.bookingsaga; import io.temporal.failure.ApplicationFailure; import java.util.UUID; public class TripBookingActivitiesImpl implements TripBookingActivities { @Override public String reserveCar(String requestId, String name) { System.out.println("reserving car for request '" + requestId + "` and name `" + name + "'"); return UUID.randomUUID().toString(); } @Override public String bookFlight(String requestId, String name) { System.out.println( "failing to book flight for request '" + requestId + "' and name '" + name + "'"); throw ApplicationFailure.newNonRetryableFailure( "Flight booking did not work", "bookingFailure"); } @Override public String bookHotel(String requestId, String name) { System.out.println("booking hotel for request '" + requestId + "` and name `" + name + "'"); return UUID.randomUUID().toString(); } @Override public String cancelFlight(String requestId, String name) { System.out.println("cancelling flight reservation '" + requestId + "' for '" + name + "'"); return UUID.randomUUID().toString(); } @Override public String cancelHotel(String requestId, String name) { System.out.println("cancelling hotel reservation '" + requestId + "' for '" + name + "'"); return UUID.randomUUID().toString(); } @Override public String cancelCar(String requestId, String name) { System.out.println("cancelling car reservation '" + requestId + "' for '" + name + "'"); return UUID.randomUUID().toString(); } } ================================================ FILE: core/src/main/java/io/temporal/samples/bookingsaga/TripBookingClient.java ================================================ package io.temporal.samples.bookingsaga; import com.google.common.base.Throwables; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import java.io.IOException; public class TripBookingClient { static final String TASK_QUEUE = "TripBooking"; public static void main(String[] args) { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } // gRPC stubs wrapper that talks to the temporal service. WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); // client that can be used to start and signal workflows WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); WorkflowOptions options = WorkflowOptions.newBuilder().setTaskQueue(TASK_QUEUE).setWorkflowId("Booking1").build(); TripBookingWorkflow trip = client.newWorkflowStub(TripBookingWorkflow.class, options); try { Booking booking = trip.bookTrip("trip1"); System.out.println("Booking: " + booking); } catch (Exception e) { System.out.println(Throwables.getStackTraceAsString(e)); } System.exit(0); } } ================================================ FILE: core/src/main/java/io/temporal/samples/bookingsaga/TripBookingWorker.java ================================================ package io.temporal.samples.bookingsaga; import io.temporal.client.WorkflowClient; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import java.io.IOException; public class TripBookingWorker { @SuppressWarnings("CatchAndPrintStackTrace") public static void main(String[] args) { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } // gRPC stubs wrapper that talks to the temporal service. WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); // client that can be used to start and signal workflows WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); // worker factory that can be used to create workers for specific task queues WorkerFactory factory = WorkerFactory.newInstance(client); // Worker that listens on a task queue and hosts both workflow and activity implementations. Worker worker = factory.newWorker(TripBookingClient.TASK_QUEUE); // Workflows are stateful. So you need a type to create instances. worker.registerWorkflowImplementationTypes(TripBookingWorkflowImpl.class); // Activities are stateless and thread safe. So a shared instance is used. TripBookingActivities tripBookingActivities = new TripBookingActivitiesImpl(); worker.registerActivitiesImplementations(tripBookingActivities); // Start all workers created by this factory. factory.start(); System.out.println("Worker started for task queue: " + TripBookingClient.TASK_QUEUE); } } ================================================ FILE: core/src/main/java/io/temporal/samples/bookingsaga/TripBookingWorkflow.java ================================================ package io.temporal.samples.bookingsaga; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; @WorkflowInterface public interface TripBookingWorkflow { @WorkflowMethod Booking bookTrip(String name); } ================================================ FILE: core/src/main/java/io/temporal/samples/bookingsaga/TripBookingWorkflowImpl.java ================================================ package io.temporal.samples.bookingsaga; import io.temporal.activity.ActivityOptions; import io.temporal.failure.ActivityFailure; import io.temporal.workflow.Saga; import io.temporal.workflow.Workflow; import java.time.Duration; public class TripBookingWorkflowImpl implements TripBookingWorkflow { private final ActivityOptions options = ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(10)).build(); private final TripBookingActivities activities = Workflow.newActivityStub(TripBookingActivities.class, options); @Override public Booking bookTrip(String name) { // Configure SAGA to run compensation activities in parallel Saga.Options sagaOptions = new Saga.Options.Builder().setParallelCompensation(true).build(); Saga saga = new Saga(sagaOptions); try { // addCompensation is added before the actual call to handle situations when the call failed // due to a timeout and its success is not clear. // The compensation code must handle situations when the actual function wasn't executed // gracefully. String carReservationRequestId = Workflow.randomUUID().toString(); saga.addCompensation(activities::cancelCar, carReservationRequestId, name); String carReservationID = activities.reserveCar(carReservationRequestId, name); String hotelReservationRequestID = Workflow.randomUUID().toString(); saga.addCompensation(activities::cancelHotel, hotelReservationRequestID, name); String hotelReservationId = activities.bookHotel(hotelReservationRequestID, name); String flightReservationRequestID = Workflow.randomUUID().toString(); saga.addCompensation(activities::cancelFlight, flightReservationRequestID, name); String flightReservationID = activities.bookFlight(flightReservationRequestID, name); return new Booking(carReservationID, hotelReservationId, flightReservationID); } catch (ActivityFailure e) { // Ensure that compensations are executed even if the workflow is canceled. Workflow.newDetachedCancellationScope(() -> saga.compensate()).run(); throw e; } } } ================================================ FILE: core/src/main/java/io/temporal/samples/bookingsyncsaga/Booking.java ================================================ package io.temporal.samples.bookingsyncsaga; public final class Booking { private final String carReservationID; private final String hotelReservationID; private final String flightReservationID; public Booking(String carReservationID, String hotelReservationID, String flightReservationID) { this.carReservationID = carReservationID; this.hotelReservationID = hotelReservationID; this.flightReservationID = flightReservationID; } public String getCarReservationID() { return carReservationID; } public String getHotelReservationID() { return hotelReservationID; } public String getFlightReservationID() { return flightReservationID; } @Override public String toString() { return "Booking{" + "carReservationID='" + carReservationID + '\'' + ", hotelReservationID='" + hotelReservationID + '\'' + ", flightReservationID='" + flightReservationID + '\'' + '}'; } } ================================================ FILE: core/src/main/java/io/temporal/samples/bookingsyncsaga/README.md ================================================ ## Saga example: synchronous trip booking The sample demonstrates low latency workflow with client synchronously waiting for result using an update. In case of failures the caller is unblocked and workflow continues executing compensations for as long as needed. Run the following command to start the worker: ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.bookingsyncsaga.TripBookingWorker ``` Run the following command to request a booking. Note that the booking is expected to fail to demonstrate the compensation flow. ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.bookingsyncsaga.TripBookingClient ``` ================================================ FILE: core/src/main/java/io/temporal/samples/bookingsyncsaga/TripBookingActivities.java ================================================ package io.temporal.samples.bookingsyncsaga; import io.temporal.activity.ActivityInterface; @ActivityInterface public interface TripBookingActivities { /** * Request a car rental reservation. * * @param requestId used for idempotency and compensation correlation. * @param name customer name * @return reservationID */ String reserveCar(String requestId, String name); /** * Request a flight reservation. * * @param requestId used for idempotency and compensation correlation. * @param name customer name * @return reservationID */ String bookFlight(String requestId, String name); /** * Request a hotel reservation. * * @param requestId used for idempotency and compensation correlation. * @param name customer name * @return reservationID */ String bookHotel(String requestId, String name); /** * Cancel a flight reservation. * * @param name customer name * @param requestId the same id is passed to bookFlight * @return cancellationConfirmationID */ String cancelFlight(String requestId, String name); /** * Cancel a hotel reservation. * * @param name customer name * @param requestId the same id is passed to bookHotel * @return cancellationConfirmationID */ String cancelHotel(String requestId, String name); /** * Cancel a car rental reservation. * * @param name customer name * @param requestId the same id is passed to reserveCar * @return cancellationConfirmationID */ String cancelCar(String requestId, String name); } ================================================ FILE: core/src/main/java/io/temporal/samples/bookingsyncsaga/TripBookingActivitiesImpl.java ================================================ package io.temporal.samples.bookingsyncsaga; import io.temporal.failure.ApplicationFailure; import java.util.UUID; public class TripBookingActivitiesImpl implements TripBookingActivities { @Override public String reserveCar(String requestId, String name) { System.out.println("reserving car for request '" + requestId + "` and name `" + name + "'"); return UUID.randomUUID().toString(); } @Override public String bookFlight(String requestId, String name) { System.out.println( "failing to book flight for request '" + requestId + "' and name '" + name + "'"); throw ApplicationFailure.newNonRetryableFailure( "Flight booking did not work", "bookingFailure"); } @Override public String bookHotel(String requestId, String name) { System.out.println("booking hotel for request '" + requestId + "` and name `" + name + "'"); return UUID.randomUUID().toString(); } @Override public String cancelFlight(String requestId, String name) { System.out.println("cancelling flight reservation '" + requestId + "' for '" + name + "'"); sleep(1000); return UUID.randomUUID().toString(); } @Override public String cancelHotel(String requestId, String name) { System.out.println("cancelling hotel reservation '" + requestId + "' for '" + name + "'"); sleep(1000); return UUID.randomUUID().toString(); } @Override public String cancelCar(String requestId, String name) { System.out.println("cancelling car reservation '" + requestId + "' for '" + name + "'"); sleep(1000); return UUID.randomUUID().toString(); } private static void sleep(long milliseconds) { try { Thread.sleep(milliseconds); } catch (InterruptedException e) { throw new RuntimeException(e); } } } ================================================ FILE: core/src/main/java/io/temporal/samples/bookingsyncsaga/TripBookingClient.java ================================================ package io.temporal.samples.bookingsyncsaga; import com.google.common.base.Throwables; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import java.io.IOException; public class TripBookingClient { static final String TASK_QUEUE = "TripBookingSync"; public static void main(String[] args) { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } // gRPC stubs wrapper that talks to the temporal service. WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); // client that can be used to start and signal workflows WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); WorkflowOptions options = WorkflowOptions.newBuilder().setTaskQueue(TASK_QUEUE).setWorkflowId("Booking1").build(); TripBookingWorkflow trip1 = client.newWorkflowStub(TripBookingWorkflow.class, options); // Start workflow asynchronously WorkflowClient.start(trip1::bookTrip, "trip1"); try { // Wait for workflow to complete or fail the booking using an update. Booking booking = trip1.waitForBooking(); System.out.println("Booking: " + booking); } catch (Exception e) { System.out.println(Throwables.getStackTraceAsString(e)); } System.exit(0); } } ================================================ FILE: core/src/main/java/io/temporal/samples/bookingsyncsaga/TripBookingWorker.java ================================================ package io.temporal.samples.bookingsyncsaga; import io.temporal.client.WorkflowClient; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import java.io.IOException; public class TripBookingWorker { @SuppressWarnings("CatchAndPrintStackTrace") public static void main(String[] args) { // gRPC stubs wrapper that talks to the local docker instance of temporal service. // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); // client that can be used to start and signal workflows WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); // worker factory that can be used to create workers for specific task queues WorkerFactory factory = WorkerFactory.newInstance(client); // Worker that listens on a task queue and hosts both workflow and activity implementations. Worker worker = factory.newWorker(TripBookingClient.TASK_QUEUE); // Workflows are stateful. So you need a type to create instances. worker.registerWorkflowImplementationTypes(TripBookingWorkflowImpl.class); // Activities are stateless and thread safe. So a shared instance is used. TripBookingActivities tripBookingActivities = new TripBookingActivitiesImpl(); worker.registerActivitiesImplementations(tripBookingActivities); // Start all workers created by this factory. factory.start(); System.out.println("Worker started for task queue: " + TripBookingClient.TASK_QUEUE); } } ================================================ FILE: core/src/main/java/io/temporal/samples/bookingsyncsaga/TripBookingWorkflow.java ================================================ package io.temporal.samples.bookingsyncsaga; import io.temporal.workflow.UpdateMethod; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; @WorkflowInterface public interface TripBookingWorkflow { @WorkflowMethod void bookTrip(String name); /** * Used to wait for booking completion or failure. After this method returns a failure workflow * keeps running executing compensations. * * @return booking information. */ @UpdateMethod Booking waitForBooking(); } ================================================ FILE: core/src/main/java/io/temporal/samples/bookingsyncsaga/TripBookingWorkflowImpl.java ================================================ package io.temporal.samples.bookingsyncsaga; import io.temporal.activity.ActivityOptions; import io.temporal.activity.LocalActivityOptions; import io.temporal.common.RetryOptions; import io.temporal.failure.ActivityFailure; import io.temporal.workflow.CompletablePromise; import io.temporal.workflow.Saga; import io.temporal.workflow.Workflow; import java.time.Duration; public class TripBookingWorkflowImpl implements TripBookingWorkflow { /** * Use local activities for the happy path. This allows to execute the whole sequence as a single * workflow task. Don't use local activities if you expect long retries. */ private final LocalActivityOptions options = LocalActivityOptions.newBuilder() .build() .newBuilder() .setStartToCloseTimeout(Duration.ofSeconds(1)) .setRetryOptions(RetryOptions.newBuilder().setMaximumAttempts(3).build()) .build(); private final TripBookingActivities activities = Workflow.newLocalActivityStub(TripBookingActivities.class, options); /** Use normal activities for compensations, as they potentially need long retries. */ private final ActivityOptions compensationOptions = ActivityOptions.newBuilder() .setStartToCloseTimeout(Duration.ofHours(1)) .setRetryOptions(RetryOptions.newBuilder().setMaximumAttempts(1).build()) .build(); private final TripBookingActivities compensationActivities = Workflow.newActivityStub(TripBookingActivities.class, compensationOptions); /** Used to pass result to the update function. */ private final CompletablePromise booking = Workflow.newPromise(); @Override public void bookTrip(String name) { Saga.Options sagaOptions = new Saga.Options.Builder().build(); Saga saga = new Saga(sagaOptions); try { // addCompensation is added before the actual call to handle situations when the call failed // due to // a timeout and its success is not clear. // The compensation code must handle situations when the actual function wasn't executed // gracefully. String carReservationRequestId = Workflow.randomUUID().toString(); saga.addCompensation(compensationActivities::cancelCar, carReservationRequestId, name); String carReservationID = activities.reserveCar(carReservationRequestId, name); String hotelReservationRequestID = Workflow.randomUUID().toString(); saga.addCompensation(compensationActivities::cancelHotel, hotelReservationRequestID, name); String hotelReservationId = activities.bookHotel(hotelReservationRequestID, name); String flightReservationRequestID = Workflow.randomUUID().toString(); saga.addCompensation(compensationActivities::cancelFlight, flightReservationRequestID, name); String flightReservationID = activities.bookFlight(flightReservationRequestID, name); // Unblock the update function booking.complete(new Booking(carReservationID, hotelReservationId, flightReservationID)); } catch (ActivityFailure e) { // Unblock the update function booking.completeExceptionally(e); // Ensure that compensations are executed even if the workflow is canceled. Workflow.newDetachedCancellationScope(() -> saga.compensate()).run(); throw e; } } @Override public Booking waitForBooking() { return booking.get(); } } ================================================ FILE: core/src/main/java/io/temporal/samples/common/QueryWorkflowExecution.java ================================================ package io.temporal.samples.common; import io.temporal.api.common.v1.WorkflowExecution; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowStub; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import java.io.IOException; import java.util.Optional; /** * Queries a workflow execution using the Temporal query API. Temporal redirects a query to any * currently running workflow worker for the workflow type of the requested workflow execution. * * @author fateev */ public class QueryWorkflowExecution { public static void main(String[] args) { if (args.length < 2 || args.length > 3) { System.err.println( "Usage: java " + QueryWorkflowExecution.class.getName() + " []"); System.exit(1); } String queryType = args[0]; String workflowId = args[1]; String runId = args.length == 3 ? args[2] : ""; // gRPC stubs wrapper that talks to the local docker instance of temporal service. // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); WorkflowExecution workflowExecution = WorkflowExecution.newBuilder().setWorkflowId(workflowId).setRunId(runId).build(); WorkflowStub workflow = client.newUntypedWorkflowStub(workflowExecution, Optional.empty()); String result = workflow.query(queryType, String.class); System.out.println("Query result for " + workflowExecution + ":"); System.out.println(result); } } ================================================ FILE: core/src/main/java/io/temporal/samples/countinterceptor/ClientCounter.java ================================================ package io.temporal.samples.countinterceptor; import java.util.AbstractMap; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; /** Simple counter class. */ public class ClientCounter { private static final String NUM_OF_GET_RESULT = "numOfGetResult"; private static final String NUM_OF_WORKFLOW_EXECUTIONS = "numOfWorkflowExec"; private static final String NUM_OF_SIGNALS = "numOfSignals"; private static final String NUM_OF_QUERIES = "numOfQueries"; private static final Map> perWorkflowIdMap = Collections.synchronizedMap(new HashMap<>()); public String getInfo() { StringBuilder stringBuilder = new StringBuilder(); for (String workflowRunId : perWorkflowIdMap.keySet()) { stringBuilder.append("\n** Workflow ID: " + workflowRunId); Map info = perWorkflowIdMap.get(workflowRunId); stringBuilder.append( "\n\tTotal Number of Workflow Exec: " + info.get(NUM_OF_WORKFLOW_EXECUTIONS)); stringBuilder.append("\n\tTotal Number of Signals: " + info.get(NUM_OF_SIGNALS)); stringBuilder.append("\n\tTotal Number of Queries: " + info.get(NUM_OF_QUERIES)); stringBuilder.append("\n\tTotal Number of GetResult: " + info.get(NUM_OF_GET_RESULT)); } return stringBuilder.toString(); } private void add(String workflowId, String type) { if (!perWorkflowIdMap.containsKey(workflowId)) { perWorkflowIdMap.put(workflowId, getDefaultInfoMap()); } if (perWorkflowIdMap.get(workflowId).get(type) == null) { perWorkflowIdMap.get(workflowId).put(type, 1); } else { int current = perWorkflowIdMap.get(workflowId).get(type).intValue(); int next = current + 1; perWorkflowIdMap.get(workflowId).put(type, next); } } public int getNumOfWorkflowExecutions(String workflowId) { return perWorkflowIdMap.get(workflowId).get(NUM_OF_WORKFLOW_EXECUTIONS); } public int getNumOfGetResults(String workflowId) { return perWorkflowIdMap.get(workflowId).get(NUM_OF_GET_RESULT); } public int getNumOfSignals(String workflowId) { return perWorkflowIdMap.get(workflowId).get(NUM_OF_SIGNALS); } public int getNumOfQueries(String workflowId) { return perWorkflowIdMap.get(workflowId).get(NUM_OF_QUERIES); } /** * Creates a default counter info map for a workflowid * * @return default counter info map */ private Map getDefaultInfoMap() { return Stream.of( new AbstractMap.SimpleImmutableEntry<>(NUM_OF_WORKFLOW_EXECUTIONS, 0), new AbstractMap.SimpleImmutableEntry<>(NUM_OF_SIGNALS, 0), new AbstractMap.SimpleImmutableEntry<>(NUM_OF_GET_RESULT, 0), new AbstractMap.SimpleImmutableEntry<>(NUM_OF_QUERIES, 0)) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); } public void addStartInvocation(String workflowId) { add(workflowId, NUM_OF_WORKFLOW_EXECUTIONS); } public void addSignalInvocation(String workflowId) { add(workflowId, NUM_OF_SIGNALS); } public void addGetResultInvocation(String workflowId) { add(workflowId, NUM_OF_GET_RESULT); } public void addQueryInvocation(String workflowId) { add(workflowId, NUM_OF_QUERIES); } } ================================================ FILE: core/src/main/java/io/temporal/samples/countinterceptor/InterceptorStarter.java ================================================ package io.temporal.samples.countinterceptor; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowClientOptions; import io.temporal.client.WorkflowOptions; import io.temporal.client.WorkflowStub; import io.temporal.common.interceptors.WorkflowClientInterceptor; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.samples.countinterceptor.activities.MyActivitiesImpl; import io.temporal.samples.countinterceptor.workflow.MyChildWorkflowImpl; import io.temporal.samples.countinterceptor.workflow.MyWorkflow; import io.temporal.samples.countinterceptor.workflow.MyWorkflowImpl; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import io.temporal.worker.WorkerFactoryOptions; import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class InterceptorStarter { public static SimpleCountWorkerInterceptor workerInterceptor = new SimpleCountWorkerInterceptor(); private static final String TEST_QUEUE = "test-queue"; private static final String WORKFLOW_ID = "TestInterceptorWorkflow"; private static final Logger logger = LoggerFactory.getLogger(SimpleCountWorkerInterceptor.class); public static void main(String[] args) { final ClientCounter clientCounter = new ClientCounter(); final WorkflowClientInterceptor clientInterceptor = new SimpleClientInterceptor(clientCounter); // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient client = WorkflowClient.newInstance( service, WorkflowClientOptions.newBuilder().setInterceptors(clientInterceptor).build()); WorkerFactoryOptions wfo = WorkerFactoryOptions.newBuilder() .setWorkerInterceptors(workerInterceptor) .validateAndBuildWithDefaults(); WorkerFactory factory = WorkerFactory.newInstance(client, wfo); Worker worker = factory.newWorker(TEST_QUEUE); worker.registerWorkflowImplementationTypes(MyWorkflowImpl.class, MyChildWorkflowImpl.class); worker.registerActivitiesImplementations(new MyActivitiesImpl()); factory.start(); WorkflowOptions workflowOptions = WorkflowOptions.newBuilder().setWorkflowId(WORKFLOW_ID).setTaskQueue(TEST_QUEUE).build(); MyWorkflow workflow = client.newWorkflowStub(MyWorkflow.class, workflowOptions); WorkflowClient.start(workflow::exec); workflow.signalNameAndTitle("John", "Customer"); String name = workflow.queryName(); String title = workflow.queryTitle(); // Send exit signal to workflow workflow.exit(); // Wait for workflow completion via WorkflowStub WorkflowStub untyped = WorkflowStub.fromTyped(workflow); String result = untyped.getResult(String.class); // Print workflow logger.info("Workflow Result: " + result); // Print the Query results logger.info("Query results: "); logger.info("Name: " + name); logger.info("Title: " + title); // Print the Worker Counter Info logger.info("Collected Worker Counter Info: "); logger.info(WorkerCounter.getInfo()); // Print the Client Counter Info logger.info("Collected Client Counter Info: "); logger.info(clientCounter.getInfo()); System.exit(0); } } ================================================ FILE: core/src/main/java/io/temporal/samples/countinterceptor/README.md ================================================ # Demo Workflow Interceptor The sample demonstrates: - the use of a simple Worker Workflow Interceptor that counts the number of Workflow Executions, Child Workflow Executions, and Activity Executions as well as the number of Signals and Queries. - the use of a simple Client Workflow Interceptor that counts the number of Workflow Executions as well as the number of Signals, Queries and GetResult invocations. Run the following command to start the sample: ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.countinterceptor.InterceptorStarter ``` ================================================ FILE: core/src/main/java/io/temporal/samples/countinterceptor/SimpleClientCallsInterceptor.java ================================================ package io.temporal.samples.countinterceptor; import io.temporal.common.interceptors.WorkflowClientCallsInterceptor; import io.temporal.common.interceptors.WorkflowClientCallsInterceptorBase; import java.util.concurrent.TimeoutException; public class SimpleClientCallsInterceptor extends WorkflowClientCallsInterceptorBase { private ClientCounter clientCounter; public SimpleClientCallsInterceptor( WorkflowClientCallsInterceptor next, ClientCounter clientCounter) { super(next); this.clientCounter = clientCounter; } @Override public WorkflowStartOutput start(WorkflowStartInput input) { clientCounter.addStartInvocation(input.getWorkflowId()); return super.start(input); } @Override public WorkflowSignalOutput signal(WorkflowSignalInput input) { clientCounter.addSignalInvocation(input.getWorkflowExecution().getWorkflowId()); return super.signal(input); } @Override public GetResultOutput getResult(GetResultInput input) throws TimeoutException { clientCounter.addGetResultInvocation(input.getWorkflowExecution().getWorkflowId()); return super.getResult(input); } @Override public QueryOutput query(QueryInput input) { clientCounter.addQueryInvocation(input.getWorkflowExecution().getWorkflowId()); return super.query(input); } } ================================================ FILE: core/src/main/java/io/temporal/samples/countinterceptor/SimpleClientInterceptor.java ================================================ package io.temporal.samples.countinterceptor; import io.temporal.common.interceptors.WorkflowClientCallsInterceptor; import io.temporal.common.interceptors.WorkflowClientInterceptorBase; public class SimpleClientInterceptor extends WorkflowClientInterceptorBase { private ClientCounter clientCounter; public SimpleClientInterceptor(ClientCounter clientCounter) { this.clientCounter = clientCounter; } @Override public WorkflowClientCallsInterceptor workflowClientCallsInterceptor( WorkflowClientCallsInterceptor next) { return new SimpleClientCallsInterceptor(next, clientCounter); } } ================================================ FILE: core/src/main/java/io/temporal/samples/countinterceptor/SimpleCountActivityInboundCallsInterceptor.java ================================================ package io.temporal.samples.countinterceptor; import io.temporal.activity.ActivityExecutionContext; import io.temporal.common.interceptors.ActivityInboundCallsInterceptor; import io.temporal.common.interceptors.ActivityInboundCallsInterceptorBase; public class SimpleCountActivityInboundCallsInterceptor extends ActivityInboundCallsInterceptorBase { private ActivityExecutionContext activityExecutionContext; public SimpleCountActivityInboundCallsInterceptor(ActivityInboundCallsInterceptor next) { super(next); } @Override public void init(ActivityExecutionContext context) { this.activityExecutionContext = context; super.init(context); } @Override public ActivityOutput execute(ActivityInput input) { WorkerCounter.add( this.activityExecutionContext.getInfo().getWorkflowId(), WorkerCounter.NUM_OF_ACTIVITY_EXECUTIONS); return super.execute(input); } } ================================================ FILE: core/src/main/java/io/temporal/samples/countinterceptor/SimpleCountWorkerInterceptor.java ================================================ package io.temporal.samples.countinterceptor; import io.temporal.common.interceptors.*; public class SimpleCountWorkerInterceptor extends WorkerInterceptorBase { @Override public WorkflowInboundCallsInterceptor interceptWorkflow(WorkflowInboundCallsInterceptor next) { return new SimpleCountWorkflowInboundCallsInterceptor(next); } @Override public ActivityInboundCallsInterceptor interceptActivity(ActivityInboundCallsInterceptor next) { return new SimpleCountActivityInboundCallsInterceptor(next); } } ================================================ FILE: core/src/main/java/io/temporal/samples/countinterceptor/SimpleCountWorkflowInboundCallsInterceptor.java ================================================ package io.temporal.samples.countinterceptor; import io.temporal.common.interceptors.WorkflowInboundCallsInterceptor; import io.temporal.common.interceptors.WorkflowInboundCallsInterceptorBase; import io.temporal.common.interceptors.WorkflowOutboundCallsInterceptor; import io.temporal.workflow.Workflow; import io.temporal.workflow.WorkflowInfo; public class SimpleCountWorkflowInboundCallsInterceptor extends WorkflowInboundCallsInterceptorBase { private WorkflowInfo workflowInfo; public SimpleCountWorkflowInboundCallsInterceptor(WorkflowInboundCallsInterceptor next) { super(next); } @Override public void init(WorkflowOutboundCallsInterceptor outboundCalls) { this.workflowInfo = Workflow.getInfo(); super.init(new SimpleCountWorkflowOutboundCallsInterceptor(outboundCalls)); } @Override public WorkflowOutput execute(WorkflowInput input) { WorkerCounter.add(this.workflowInfo.getWorkflowId(), WorkerCounter.NUM_OF_WORKFLOW_EXECUTIONS); return super.execute(input); } @Override public void handleSignal(SignalInput input) { WorkerCounter.add(this.workflowInfo.getWorkflowId(), WorkerCounter.NUM_OF_SIGNALS); super.handleSignal(input); } @Override public QueryOutput handleQuery(QueryInput input) { WorkerCounter.add(this.workflowInfo.getWorkflowId(), WorkerCounter.NUM_OF_QUERIES); return super.handleQuery(input); } } ================================================ FILE: core/src/main/java/io/temporal/samples/countinterceptor/SimpleCountWorkflowOutboundCallsInterceptor.java ================================================ package io.temporal.samples.countinterceptor; import io.temporal.common.interceptors.WorkflowOutboundCallsInterceptor; import io.temporal.common.interceptors.WorkflowOutboundCallsInterceptorBase; import io.temporal.workflow.Workflow; public class SimpleCountWorkflowOutboundCallsInterceptor extends WorkflowOutboundCallsInterceptorBase { public SimpleCountWorkflowOutboundCallsInterceptor(WorkflowOutboundCallsInterceptor next) { super(next); } @Override public ChildWorkflowOutput executeChildWorkflow(ChildWorkflowInput input) { WorkerCounter.add( Workflow.getInfo().getWorkflowId(), WorkerCounter.NUM_OF_CHILD_WORKFLOW_EXECUTIONS); return super.executeChildWorkflow(input); } } ================================================ FILE: core/src/main/java/io/temporal/samples/countinterceptor/WorkerCounter.java ================================================ package io.temporal.samples.countinterceptor; import java.util.AbstractMap; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; /** * Simple counter class. Static impl just for the sake of the sample. Note: in your applications you * should use CDI for example instead. */ public class WorkerCounter { private static Map> perWorkflowIdMap = Collections.synchronizedMap(new HashMap<>()); public static final String NUM_OF_WORKFLOW_EXECUTIONS = "numOfWorkflowExec"; public static final String NUM_OF_CHILD_WORKFLOW_EXECUTIONS = "numOfChildWorkflowExec"; public static final String NUM_OF_ACTIVITY_EXECUTIONS = "numOfActivityExec"; public static final String NUM_OF_SIGNALS = "numOfSignals"; public static final String NUM_OF_QUERIES = "numOfQueries"; public static void add(String workflowId, String type) { if (!perWorkflowIdMap.containsKey(workflowId)) { perWorkflowIdMap.put(workflowId, getDefaultInfoMap()); } if (perWorkflowIdMap.get(workflowId).get(type) == null) { perWorkflowIdMap.get(workflowId).put(type, 1); } else { int current = perWorkflowIdMap.get(workflowId).get(type).intValue(); int next = current + 1; perWorkflowIdMap.get(workflowId).put(type, next); } } public static int getNumOfWorkflowExecutions(String workflowId) { return perWorkflowIdMap.get(workflowId).get(NUM_OF_WORKFLOW_EXECUTIONS); } public static int getNumOfChildWorkflowExecutions(String workflowId) { return perWorkflowIdMap.get(workflowId).get(NUM_OF_CHILD_WORKFLOW_EXECUTIONS); } public static int getNumOfActivityExecutions(String workflowId) { return perWorkflowIdMap.get(workflowId).get(NUM_OF_ACTIVITY_EXECUTIONS); } public static int getNumOfSignals(String workflowId) { return perWorkflowIdMap.get(workflowId).get(NUM_OF_SIGNALS); } public static int getNumOfQueries(String workflowId) { return perWorkflowIdMap.get(workflowId).get(NUM_OF_QUERIES); } public static String getInfo() { StringBuilder stringBuilder = new StringBuilder(); for (String workflowRunId : perWorkflowIdMap.keySet()) { stringBuilder.append("\n** Workflow ID: " + workflowRunId); Map info = perWorkflowIdMap.get(workflowRunId); stringBuilder.append( "\n\tTotal Number of Workflow Exec: " + info.get(NUM_OF_WORKFLOW_EXECUTIONS)); stringBuilder.append( "\n\tTotal Number of Child Workflow Exec: " + info.get(NUM_OF_CHILD_WORKFLOW_EXECUTIONS)); stringBuilder.append( "\n\tTotal Number of Activity Exec: " + info.get(NUM_OF_ACTIVITY_EXECUTIONS)); stringBuilder.append("\n\tTotal Number of Signals: " + info.get(NUM_OF_SIGNALS)); stringBuilder.append("\n\tTotal Number of Queries: " + info.get(NUM_OF_QUERIES)); } return stringBuilder.toString(); } /** * Creates a default counter info map for a workflowid * * @return default counter info map */ private static Map getDefaultInfoMap() { return Stream.of( new AbstractMap.SimpleImmutableEntry<>(NUM_OF_WORKFLOW_EXECUTIONS, 0), new AbstractMap.SimpleImmutableEntry<>(NUM_OF_CHILD_WORKFLOW_EXECUTIONS, 0), new AbstractMap.SimpleImmutableEntry<>(NUM_OF_ACTIVITY_EXECUTIONS, 0), new AbstractMap.SimpleImmutableEntry<>(NUM_OF_SIGNALS, 0), new AbstractMap.SimpleImmutableEntry<>(NUM_OF_QUERIES, 0)) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); } } ================================================ FILE: core/src/main/java/io/temporal/samples/countinterceptor/activities/MyActivities.java ================================================ package io.temporal.samples.countinterceptor.activities; import io.temporal.activity.ActivityInterface; @ActivityInterface public interface MyActivities { String sayHello(String name, String title); String sayGoodBye(String name, String title); } ================================================ FILE: core/src/main/java/io/temporal/samples/countinterceptor/activities/MyActivitiesImpl.java ================================================ package io.temporal.samples.countinterceptor.activities; public class MyActivitiesImpl implements MyActivities { @Override public String sayHello(String name, String title) { return "Hello " + title + " " + name; } @Override public String sayGoodBye(String name, String title) { return "Goodbye " + title + " " + name; } } ================================================ FILE: core/src/main/java/io/temporal/samples/countinterceptor/workflow/MyChildWorkflow.java ================================================ package io.temporal.samples.countinterceptor.workflow; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; @WorkflowInterface public interface MyChildWorkflow { @WorkflowMethod String execChild(String name, String title); } ================================================ FILE: core/src/main/java/io/temporal/samples/countinterceptor/workflow/MyChildWorkflowImpl.java ================================================ package io.temporal.samples.countinterceptor.workflow; import io.temporal.activity.ActivityOptions; import io.temporal.samples.countinterceptor.activities.MyActivities; import io.temporal.workflow.Workflow; import java.time.Duration; public class MyChildWorkflowImpl implements MyChildWorkflow { @Override public String execChild(String name, String title) { MyActivities activities = Workflow.newActivityStub( MyActivities.class, ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(10)).build()); String result = activities.sayHello(name, title); result += activities.sayGoodBye(name, title); return result; } } ================================================ FILE: core/src/main/java/io/temporal/samples/countinterceptor/workflow/MyWorkflow.java ================================================ package io.temporal.samples.countinterceptor.workflow; import io.temporal.workflow.QueryMethod; import io.temporal.workflow.SignalMethod; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; @WorkflowInterface public interface MyWorkflow { @WorkflowMethod String exec(); @SignalMethod void signalNameAndTitle(String greeting, String title); @SignalMethod void exit(); @QueryMethod String queryName(); @QueryMethod String queryTitle(); } ================================================ FILE: core/src/main/java/io/temporal/samples/countinterceptor/workflow/MyWorkflowImpl.java ================================================ package io.temporal.samples.countinterceptor.workflow; import io.temporal.workflow.ChildWorkflowOptions; import io.temporal.workflow.Workflow; import java.time.Duration; public class MyWorkflowImpl implements MyWorkflow { private String name; private String title; private boolean exit = false; @Override public String exec() { // Wait for a greeting info Workflow.await(() -> name != null && title != null); // Execute child workflow ChildWorkflowOptions childWorkflowOptions = ChildWorkflowOptions.newBuilder().setWorkflowId("TestInterceptorChildWorkflow").build(); MyChildWorkflow child = Workflow.newChildWorkflowStub(MyChildWorkflow.class, childWorkflowOptions); String result = child.execChild(name, title); // Wait for exit signal Workflow.await(Duration.ofSeconds(5), () -> exit != false); return result; } @Override public void signalNameAndTitle(String name, String title) { this.name = name; this.title = title; } @Override public String queryName() { return name; } @Override public String queryTitle() { return title; } @Override public void exit() { this.exit = true; } } ================================================ FILE: core/src/main/java/io/temporal/samples/customannotation/BenignExceptionTypes.java ================================================ package io.temporal.samples.customannotation; import java.lang.annotation.*; /** * BenignExceptionTypes is an annotation that can be used to specify an exception type is benign and * not an issue worth logging. * *

For this annotation to work, {@link BenignExceptionTypesAnnotationInterceptor} must be passed * as a worker interceptor to the worker factory. */ @Documented @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface BenignExceptionTypes { /** Type of exceptions that should be considered benign and not logged as errors. */ Class[] value(); } ================================================ FILE: core/src/main/java/io/temporal/samples/customannotation/BenignExceptionTypesAnnotationInterceptor.java ================================================ /* * Copyright (c) 2020 Temporal Technologies, Inc. All Rights Reserved * * Copyright 2012-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Modifications copyright (C) 2017 Uber Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not * use this file except in compliance with the License. A copy of the License is * located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package io.temporal.samples.customannotation; import io.temporal.activity.ActivityExecutionContext; import io.temporal.common.interceptors.ActivityInboundCallsInterceptor; import io.temporal.common.interceptors.WorkerInterceptorBase; import io.temporal.common.metadata.POJOActivityImplMetadata; import io.temporal.common.metadata.POJOActivityMethodMetadata; import io.temporal.failure.ApplicationErrorCategory; import io.temporal.failure.ApplicationFailure; import io.temporal.failure.TemporalFailure; import java.lang.reflect.Method; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Checks if the activity method has the {@link BenignExceptionTypes} annotation. If it does, it * will throw an ApplicationFailure with {@link ApplicationErrorCategory#BENIGN}. */ public class BenignExceptionTypesAnnotationInterceptor extends WorkerInterceptorBase { @Override public ActivityInboundCallsInterceptor interceptActivity(ActivityInboundCallsInterceptor next) { return new ActivityInboundCallsInterceptorAnnotation(next); } public static class ActivityInboundCallsInterceptorAnnotation extends io.temporal.common.interceptors.ActivityInboundCallsInterceptorBase { private final ActivityInboundCallsInterceptor next; private Set> benignExceptionTypes = new HashSet<>(); public ActivityInboundCallsInterceptorAnnotation(ActivityInboundCallsInterceptor next) { super(next); this.next = next; } @Override public void init(ActivityExecutionContext context) { List activityMethods = POJOActivityImplMetadata.newInstance(context.getInstance().getClass()) .getActivityMethods(); POJOActivityMethodMetadata currentActivityMethod = activityMethods.stream() .filter(x -> x.getActivityTypeName().equals(context.getInfo().getActivityType())) .findFirst() .get(); // Get the implementation method from the interface method Method implementationMethod; try { implementationMethod = context .getInstance() .getClass() .getMethod( currentActivityMethod.getMethod().getName(), currentActivityMethod.getMethod().getParameterTypes()); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } // Get the @BenignExceptionTypes annotations from the implementation method BenignExceptionTypes an = implementationMethod.getAnnotation(BenignExceptionTypes.class); if (an != null && an.value() != null) { benignExceptionTypes = new HashSet<>(Arrays.asList(an.value())); } next.init(context); } @Override public ActivityOutput execute(ActivityInput input) { if (benignExceptionTypes.isEmpty()) { return next.execute(input); } try { return next.execute(input); } catch (TemporalFailure tf) { throw tf; } catch (Exception e) { if (benignExceptionTypes.contains(e.getClass())) { // If the exception is in the list of benign exceptions, throw an ApplicationFailure // with a BENIGN category throw ApplicationFailure.newBuilder() .setMessage(e.getMessage()) .setType(e.getClass().getName()) .setCause(e) .setCategory(ApplicationErrorCategory.BENIGN) .build(); } // If the exception is not in the list of benign exceptions, rethrow it throw e; } } } } ================================================ FILE: core/src/main/java/io/temporal/samples/customannotation/CustomAnnotation.java ================================================ /* * Copyright (c) 2020 Temporal Technologies, Inc. All Rights Reserved * * Copyright 2012-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Modifications copyright (C) 2017 Uber Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not * use this file except in compliance with the License. A copy of the License is * located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package io.temporal.samples.customannotation; import io.temporal.activity.ActivityInterface; import io.temporal.activity.ActivityMethod; import io.temporal.activity.ActivityOptions; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import io.temporal.worker.WorkerFactoryOptions; import io.temporal.workflow.Workflow; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; import java.io.IOException; import java.time.Duration; public class CustomAnnotation { // Define the task queue name static final String TASK_QUEUE = "CustomAnnotationTaskQueue"; // Define our workflow unique id static final String WORKFLOW_ID = "CustomAnnotationWorkflow"; /** * The Workflow Definition's Interface must contain one method annotated with @WorkflowMethod. * *

Workflow Definitions should not contain any heavyweight computations, non-deterministic * code, network calls, database operations, etc. Those things should be handled by the * Activities. * * @see WorkflowInterface * @see WorkflowMethod */ @WorkflowInterface public interface GreetingWorkflow { /** * This is the method that is executed when the Workflow Execution is started. The Workflow * Execution completes when this method finishes execution. */ @WorkflowMethod String getGreeting(String name); } /** * This is the Activity Definition's Interface. Activities are building blocks of any Temporal * Workflow and contain any business logic that could perform long running computation, network * calls, etc. * *

Annotating Activity Definition methods with @ActivityMethod is optional. * * @see ActivityInterface * @see ActivityMethod */ @ActivityInterface public interface GreetingActivities { /** Define your activity method which can be called during workflow execution */ String composeGreeting(String greeting, String name); } // Define the workflow implementation which implements our getGreeting workflow method. public static class GreetingWorkflowImpl implements GreetingWorkflow { /** * Define the GreetingActivities stub. Activity stubs are proxies for activity invocations that * are executed outside of the workflow thread on the activity worker, that can be on a * different host. Temporal is going to dispatch the activity results back to the workflow and * unblock the stub as soon as activity is completed on the activity worker. */ private final GreetingActivities activities = Workflow.newActivityStub( GreetingActivities.class, ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(10)).build()); @Override public String getGreeting(String name) { // This is a blocking call that returns only after activity is completed. return activities.composeGreeting("Hello", name); } } /** * Implementation of our workflow activity interface. It overwrites our defined composeGreeting * activity method. */ static class GreetingActivitiesImpl implements GreetingActivities { private int callCount; /** * Our activity implementation simulates a failure 3 times. Given our previously set * RetryOptions, our workflow is going to retry our activity execution. */ @Override @BenignExceptionTypes({IllegalStateException.class}) public synchronized String composeGreeting(String greeting, String name) { if (++callCount < 4) { System.out.println("composeGreeting activity is going to fail"); throw new IllegalStateException("not yet"); } // after 3 unsuccessful retries we finally can complete our activity execution System.out.println("composeGreeting activity is going to complete"); return greeting + " " + name + "!"; } } /** * With our Workflow and Activities defined, we can now start execution. The main method starts * the worker and then the workflow. */ public static void main(String[] args) { // Get a Workflow service stub. // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); /* * Get a Workflow service client which can be used to start, Signal, and Query Workflow Executions. */ WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); /* * Define the workflow factory. It is used to create workflow workers for a specific task queue. */ WorkerFactory factory = WorkerFactory.newInstance( client, WorkerFactoryOptions.newBuilder() .setWorkerInterceptors(new BenignExceptionTypesAnnotationInterceptor()) .build()); /* * Define the workflow worker. Workflow workers listen to a defined task queue and process * workflows and activities. */ Worker worker = factory.newWorker(TASK_QUEUE); /* * Register our workflow implementation with the worker. * Workflow implementations must be known to the worker at runtime in * order to dispatch workflow tasks. */ worker.registerWorkflowImplementationTypes(GreetingWorkflowImpl.class); /* * Register our Activity Types with the Worker. Since Activities are stateless and thread-safe, * the Activity Type is a shared instance. */ worker.registerActivitiesImplementations(new GreetingActivitiesImpl()); /* * Start all the workers registered for a specific task queue. * The started workers then start polling for workflows and activities. */ factory.start(); // Set our workflow options WorkflowOptions workflowOptions = WorkflowOptions.newBuilder().setWorkflowId(WORKFLOW_ID).setTaskQueue(TASK_QUEUE).build(); // Create the workflow client stub. It is used to start our workflow execution. GreetingWorkflow workflow = client.newWorkflowStub(GreetingWorkflow.class, workflowOptions); /* * Execute our workflow and wait for it to complete. The call to our getGreeting method is * synchronous. * * See {@link io.temporal.samples.hello.HelloSignal} for an example of starting workflow * without waiting synchronously for its result. */ String greeting = workflow.getGreeting("World"); // Display workflow execution results System.out.println(greeting); System.exit(0); } } ================================================ FILE: core/src/main/java/io/temporal/samples/customannotation/README.md ================================================ # Custom annotation The sample demonstrates how to create a custom annotation using an interceptor. In this case the annotation allows specifying an exception of a certain type is benign. This samples shows a custom annotation on an activity method, but the same approach can be used for workflow methods or Nexus operations. ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.customannotation.CustomAnnotation ``` ================================================ FILE: core/src/main/java/io/temporal/samples/customchangeversion/CustomChangeVersionActivities.java ================================================ package io.temporal.samples.customchangeversion; import io.temporal.activity.ActivityInterface; @ActivityInterface public interface CustomChangeVersionActivities { String customOne(String input); String customTwo(String input); String customThree(String input); } ================================================ FILE: core/src/main/java/io/temporal/samples/customchangeversion/CustomChangeVersionActivitiesImpl.java ================================================ package io.temporal.samples.customchangeversion; public class CustomChangeVersionActivitiesImpl implements CustomChangeVersionActivities { @Override public String customOne(String input) { return "\ncustomOne activity - " + input; } @Override public String customTwo(String input) { return "\ncustomTwo activity - " + input; } @Override public String customThree(String input) { return "\ncustomThree activity - " + input; } } ================================================ FILE: core/src/main/java/io/temporal/samples/customchangeversion/CustomChangeVersionStarter.java ================================================ package io.temporal.samples.customchangeversion; import io.grpc.StatusRuntimeException; import io.temporal.api.enums.v1.IndexedValueType; import io.temporal.api.operatorservice.v1.AddSearchAttributesRequest; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.client.WorkflowServiceException; import io.temporal.common.SearchAttributeKey; import io.temporal.common.SearchAttributes; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.OperatorServiceStubs; import io.temporal.serviceclient.OperatorServiceStubsOptions; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import java.io.IOException; import java.util.Collections; public class CustomChangeVersionStarter { private static SearchAttributeKey CUSTOM_CHANGE_VERSION = SearchAttributeKey.forKeyword("CustomChangeVersion"); private static final String taskQueue = "customChangeVersionTaskQueue"; private static final String workflowId = "CustomChangeVersionWorkflow"; public static void main(String[] args) { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); WorkerFactory workerFactory = WorkerFactory.newInstance(client); Worker worker = workerFactory.newWorker(taskQueue); // Register CustomChangeVersion search attribute thats used in this sample OperatorServiceStubs operatorService = OperatorServiceStubs.newServiceStubs( OperatorServiceStubsOptions.newBuilder() .setChannel(service.getRawChannel()) .validateAndBuildWithDefaults()); operatorService .blockingStub() .addSearchAttributes( AddSearchAttributesRequest.newBuilder() .setNamespace(client.getOptions().getNamespace()) .putAllSearchAttributes( Collections.singletonMap( "CustomChangeVersion", IndexedValueType.INDEXED_VALUE_TYPE_KEYWORD)) .build()); // Register workflow and activities worker.registerWorkflowImplementationTypes(CustomChangeVersionWorkflowImpl.class); worker.registerActivitiesImplementations(new CustomChangeVersionActivitiesImpl()); workerFactory.start(); CustomChangeVersionWorkflow workflow = client.newWorkflowStub( CustomChangeVersionWorkflow.class, WorkflowOptions.newBuilder() .setTaskQueue(taskQueue) .setWorkflowId(workflowId) .setTypedSearchAttributes( SearchAttributes.newBuilder().set(CUSTOM_CHANGE_VERSION, "").build()) .build()); try { String result = workflow.run("Hello"); System.out.println("Result: " + result); } catch (WorkflowServiceException e) { if (e.getCause() instanceof StatusRuntimeException) { StatusRuntimeException sre = (StatusRuntimeException) e.getCause(); System.out.println( "Error starting workflow execution: " + sre.getMessage() + " Status: " + sre.getStatus()); } else { System.out.println("Error starting workflow execution: " + e.getMessage()); } } System.exit(0); } } ================================================ FILE: core/src/main/java/io/temporal/samples/customchangeversion/CustomChangeVersionWorkflow.java ================================================ package io.temporal.samples.customchangeversion; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; @WorkflowInterface public interface CustomChangeVersionWorkflow { @WorkflowMethod String run(String input); } ================================================ FILE: core/src/main/java/io/temporal/samples/customchangeversion/CustomChangeVersionWorkflowImpl.java ================================================ package io.temporal.samples.customchangeversion; import io.temporal.activity.ActivityOptions; import io.temporal.common.SearchAttributeKey; import io.temporal.workflow.Workflow; import java.time.Duration; /** * CustomChangeVersionWorkflowImpl shows how to upsert a custom search attribute which can be used * when adding changes to our workflow using workflow versioning. Note that this is only temporary * solution until https://github.com/temporalio/sdk-java/issues/587 is implemented. Given that a * number of users are in need of this and are looking for a sample, we are adding this as sample * until this issue is fixed, at which point it will no longer be needed. */ public class CustomChangeVersionWorkflowImpl implements CustomChangeVersionWorkflow { static final SearchAttributeKey CUSTOM_CHANGE_VERSION = SearchAttributeKey.forKeyword("CustomChangeVersion"); private CustomChangeVersionActivities activities = Workflow.newActivityStub( CustomChangeVersionActivities.class, ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(2)).build()); @Override public String run(String input) { String result = activities.customOne(input); // We assume when this change is added we have some executions of this workflow type running // where customTwo activity was not called (we are adding it to exiting workflow) // Adding customTwo activity as a versioned change int version = Workflow.getVersion("add-v2-activity-change", Workflow.DEFAULT_VERSION, 1); if (version == 1) { // Upsert our custom change version search attribute // We set its value to follow TemporalChangeVersion structure of "-" Workflow.upsertTypedSearchAttributes( CUSTOM_CHANGE_VERSION.valueUnset(), CUSTOM_CHANGE_VERSION.valueSet("add-v2-activity-change-1")); // Adding call to v2 activity result += activities.customTwo(input); } // lets say then later on we also want to add a change to invoke another activity version = Workflow.getVersion("add-v3-activity-change", Workflow.DEFAULT_VERSION, 1); if (version == 1) { // Upsert our custom change version search attribute // We set its value to follow TemporalChangeVersion structure of "-" Workflow.upsertTypedSearchAttributes( CUSTOM_CHANGE_VERSION.valueUnset(), CUSTOM_CHANGE_VERSION.valueSet("add-v3-activity-change-1")); // Adding call to v2 activity result += activities.customThree(input); } return result; } } ================================================ FILE: core/src/main/java/io/temporal/samples/customchangeversion/README.md ================================================ ## Custom Change Version Search Attribute Sample This sample shows how to upsert custom search attribute when adding a version change to your workflow code. It is a current workaround until feature https://github.com/temporalio/sdk-java/issues/587 is implemented. Purpose of upserting a custom search attribute when addint new versions is to then be able to use visibility api to search for running/completed executions which are on a specific version. It is also useful to see if there are no running executions on specific change version in order to remove certain no longer used versioned change if/else block from your workflow code, so it no longer has to be maintained. To run this sample: ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.customchangeversion.CustomChangeVersionStarter ``` After running this sample you can go to your Web UI or use Temporal CLI to search for specific CustomChangeVersion, for example: ``` temporal workflow list -q "CustomChangeVersion='add-v3-activity-change-1'" ``` ================================================ FILE: core/src/main/java/io/temporal/samples/dsl/DslActivities.java ================================================ package io.temporal.samples.dsl; import io.temporal.activity.ActivityInterface; @ActivityInterface public interface DslActivities { String one(); String two(); String three(); String four(); } ================================================ FILE: core/src/main/java/io/temporal/samples/dsl/DslActivitiesImpl.java ================================================ package io.temporal.samples.dsl; import java.util.concurrent.TimeUnit; public class DslActivitiesImpl implements DslActivities { @Override public String one() { sleep(1); return "Activity one done..."; } @Override public String two() { sleep(1); return "Activity two done..."; } @Override public String three() { sleep(1); return "Activity three done..."; } @Override public String four() { sleep(1); return "Activity four done..."; } private void sleep(int seconds) { try { Thread.sleep(TimeUnit.SECONDS.toMillis(seconds)); } catch (InterruptedException ee) { // Empty } } } ================================================ FILE: core/src/main/java/io/temporal/samples/dsl/DslWorkflow.java ================================================ package io.temporal.samples.dsl; import io.temporal.samples.dsl.model.Flow; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; @WorkflowInterface public interface DslWorkflow { @WorkflowMethod String run(Flow flow, String input); } ================================================ FILE: core/src/main/java/io/temporal/samples/dsl/DslWorkflowImpl.java ================================================ package io.temporal.samples.dsl; import io.temporal.activity.ActivityOptions; import io.temporal.common.RetryOptions; import io.temporal.failure.ActivityFailure; import io.temporal.failure.ApplicationFailure; import io.temporal.samples.dsl.model.Flow; import io.temporal.samples.dsl.model.FlowAction; import io.temporal.workflow.ActivityStub; import io.temporal.workflow.Workflow; import java.time.Duration; import java.util.ArrayList; import java.util.List; public class DslWorkflowImpl implements DslWorkflow { @Override public String run(Flow flow, String input) { if (flow == null || flow.getActions().isEmpty()) { throw ApplicationFailure.newFailure( "Flow is null or does not have any actions", "illegal flow"); } try { return runActions(flow, input); } catch (ActivityFailure e) { throw ApplicationFailure.newFailure( "failing execution after compensation initiated", e.getCause().getClass().getName()); } } private String runActions(Flow flow, String input) { List results = new ArrayList<>(); for (FlowAction action : flow.getActions()) { // build activity options based on flow action input ActivityOptions.Builder activityOptionsBuilder = ActivityOptions.newBuilder(); activityOptionsBuilder.setStartToCloseTimeout( Duration.ofSeconds(action.getStartToCloseSec())); if (action.getRetries() > 0) { activityOptionsBuilder.setRetryOptions( RetryOptions.newBuilder().setMaximumAttempts(action.getRetries()).build()); } // create untyped activity stub and run activity based on flow action ActivityStub activityStub = Workflow.newUntypedActivityStub(activityOptionsBuilder.build()); results.add(activityStub.execute(action.getAction(), String.class, input)); } return String.join(",", results); } } ================================================ FILE: core/src/main/java/io/temporal/samples/dsl/README.md ================================================ # DSL Sample This sample shows how to use a DSL on top of Temporal. The sample defines a number of domain specific json samples which are used to define steps of actions to be performed by our workflow. As with all samples, use the following at your own risk. As a rule, DSLs provide limited and restrictive functionality. They are not suitable for full expressive development. In many cases, it's better to build customized DSLs to optimize simplicity and domain targeting for your particular use case. ## Run the sample 1Start the Starter ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.dsl.Starter ``` ================================================ FILE: core/src/main/java/io/temporal/samples/dsl/Starter.java ================================================ package io.temporal.samples.dsl; import com.fasterxml.jackson.databind.ObjectMapper; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.samples.dsl.model.Flow; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import java.io.IOException; public class Starter { public static void main(String[] args) { Flow flow = getFlowFromResource(); // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); WorkerFactory factory = WorkerFactory.newInstance(client); Worker worker = factory.newWorker("dsl-task-queue"); worker.registerWorkflowImplementationTypes(DslWorkflowImpl.class); worker.registerActivitiesImplementations(new DslActivitiesImpl()); factory.start(); DslWorkflow workflow = client.newWorkflowStub( DslWorkflow.class, WorkflowOptions.newBuilder() .setWorkflowId("dsl-workflow") .setTaskQueue("dsl-task-queue") .build()); String result = workflow.run(flow, "sample input"); System.out.println("Result: " + result); System.exit(0); } private static Flow getFlowFromResource() { ObjectMapper objectMapper = new ObjectMapper(); try { return objectMapper.readValue( Starter.class.getClassLoader().getResource("dsl/sampleflow.json"), Flow.class); } catch (Exception e) { e.printStackTrace(); return null; } } } ================================================ FILE: core/src/main/java/io/temporal/samples/dsl/model/Flow.java ================================================ package io.temporal.samples.dsl.model; import java.util.List; public class Flow { private String id; private String name; private String description; private List actions; public Flow() {} public Flow(String id, String name, String description, List actions) { this.id = id; this.name = name; this.description = description; this.actions = actions; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public List getActions() { return actions; } public void setActions(List actions) { this.actions = actions; } } ================================================ FILE: core/src/main/java/io/temporal/samples/dsl/model/FlowAction.java ================================================ package io.temporal.samples.dsl.model; public class FlowAction { private String action; private String compensateBy; private int retries; private int startToCloseSec; private int next; public FlowAction() {} public FlowAction( String action, String compensateBy, int retries, int startToCloseSec, int next) { this.action = action; this.compensateBy = compensateBy; this.retries = retries; this.startToCloseSec = startToCloseSec; this.next = next; } public String getAction() { return action; } public void setAction(String action) { this.action = action; } public String getCompensateBy() { return compensateBy; } public void setCompensateBy(String compensateBy) { this.compensateBy = compensateBy; } public int getRetries() { return retries; } public void setRetries(int retries) { this.retries = retries; } public int getStartToCloseSec() { return startToCloseSec; } public void setStartToCloseSec(int startToCloseSec) { this.startToCloseSec = startToCloseSec; } public int getNext() { return next; } public void setNext(int next) { this.next = next; } } ================================================ FILE: core/src/main/java/io/temporal/samples/earlyreturn/EarlyReturnClient.java ================================================ package io.temporal.samples.earlyreturn; import io.temporal.api.enums.v1.WorkflowIdConflictPolicy; import io.temporal.client.*; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import java.io.IOException; public class EarlyReturnClient { private static final String TASK_QUEUE = "EarlyReturnTaskQueue"; private static final String WORKFLOW_ID_PREFIX = "early-return-workflow-"; public static void main(String[] args) { WorkflowClient client = setupWorkflowClient(); runWorkflowWithUpdateWithStart(client); } // Set up the WorkflowClient public static WorkflowClient setupWorkflowClient() { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); return WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); } // Run workflow using 'updateWithStart' private static void runWorkflowWithUpdateWithStart(WorkflowClient client) { TransactionRequest txRequest = new TransactionRequest( "Bob", "Alice", 1000); // Change this amount to a negative number to have initTransaction fail WorkflowOptions options = buildWorkflowOptions(); TransactionWorkflow workflow = client.newWorkflowStub(TransactionWorkflow.class, options); System.out.println("Starting workflow with UpdateWithStart"); TxResult updateResult = null; try { updateResult = WorkflowClient.executeUpdateWithStart( workflow::returnInitResult, UpdateOptions.newBuilder().build(), new WithStartWorkflowOperation<>(workflow::processTransaction, txRequest)); System.out.println( "Workflow initialized with result: " + updateResult.getStatus() + " (transactionId: " + updateResult.getTransactionId() + ")"); TxResult result = WorkflowStub.fromTyped(workflow).getResult(TxResult.class); System.out.println( "Workflow completed with result: " + result.getStatus() + " (transactionId: " + result.getTransactionId() + ")"); } catch (Exception e) { System.err.println("Transaction initialization failed: " + e.getMessage()); } } // Build WorkflowOptions with task queue and unique ID private static WorkflowOptions buildWorkflowOptions() { return WorkflowOptions.newBuilder() .setTaskQueue(TASK_QUEUE) .setWorkflowIdConflictPolicy(WorkflowIdConflictPolicy.WORKFLOW_ID_CONFLICT_POLICY_FAIL) .setWorkflowId(WORKFLOW_ID_PREFIX + System.currentTimeMillis()) .build(); } } ================================================ FILE: core/src/main/java/io/temporal/samples/earlyreturn/EarlyReturnWorker.java ================================================ package io.temporal.samples.earlyreturn; import io.temporal.client.WorkflowClient; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; public class EarlyReturnWorker { private static final String TASK_QUEUE = "EarlyReturnTaskQueue"; public static void main(String[] args) { WorkflowClient client = EarlyReturnClient.setupWorkflowClient(); startWorker(client); } private static void startWorker(WorkflowClient client) { WorkerFactory factory = WorkerFactory.newInstance(client); Worker worker = factory.newWorker(TASK_QUEUE); worker.registerWorkflowImplementationTypes(TransactionWorkflowImpl.class); worker.registerActivitiesImplementations(new TransactionActivitiesImpl()); factory.start(); System.out.println("Worker started"); } } ================================================ FILE: core/src/main/java/io/temporal/samples/earlyreturn/README.md ================================================ ### Early-Return Sample This sample demonstrates an early-return from a workflow. By utilizing Update-with-Start, a client can start a new workflow and synchronously receive a response mid-workflow, while the workflow continues to run to completion. To run the sample, start the worker: ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.earlyreturn.EarlyReturnWorker ``` Then, start the client: ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.earlyreturn.EarlyReturnClient ``` * The client will start a workflow using Update-With-Start. * Update-With-Start will trigger an initialization step. * If the initialization step succeeds (default), intialization will return to the client with a transaction ID and the workflow will continue. The workflow will then complete and return the final result. * If the intitialization step fails (amount <= 0), the workflow will return to the client with an error message and the workflow will run an activity to cancel the transaction. To trigger a failed initialization, set the amount to <= 0 in the `EarlyReturnClient` class's `runWorkflowWithUpdateWithStart` method and re-run the client. ================================================ FILE: core/src/main/java/io/temporal/samples/earlyreturn/Transaction.java ================================================ package io.temporal.samples.earlyreturn; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; public final class Transaction { private final String id; private final String sourceAccount; private final String targetAccount; private final int amount; @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) public Transaction( @JsonProperty("id") String id, @JsonProperty("sourceAccount") String sourceAccount, @JsonProperty("targetAccount") String targetAccount, @JsonProperty("amount") int amount) { this.id = id; this.sourceAccount = sourceAccount; this.targetAccount = targetAccount; this.amount = amount; } @JsonProperty("id") public String getId() { return id; } @JsonProperty("sourceAccount") public String getSourceAccount() { return sourceAccount; } @JsonProperty("targetAccount") public String getTargetAccount() { return targetAccount; } @JsonProperty("amount") public int getAmount() { return amount; } @Override public String toString() { return String.format( "Transaction{id='%s', sourceAccount='%s', targetAccount='%s', amount=%d}", id, sourceAccount, targetAccount, amount); } } ================================================ FILE: core/src/main/java/io/temporal/samples/earlyreturn/TransactionActivities.java ================================================ package io.temporal.samples.earlyreturn; import io.temporal.activity.ActivityInterface; import io.temporal.activity.ActivityMethod; @ActivityInterface public interface TransactionActivities { @ActivityMethod Transaction mintTransactionId(TransactionRequest txRequest); @ActivityMethod Transaction initTransaction(Transaction tx); @ActivityMethod void cancelTransaction(Transaction tx); @ActivityMethod void completeTransaction(Transaction tx); } ================================================ FILE: core/src/main/java/io/temporal/samples/earlyreturn/TransactionActivitiesImpl.java ================================================ package io.temporal.samples.earlyreturn; import io.temporal.failure.ApplicationFailure; public class TransactionActivitiesImpl implements TransactionActivities { @Override public Transaction mintTransactionId(TransactionRequest request) { System.out.println("Minting transaction ID"); // Simulate transaction ID generation String txId = "TXID" + String.format("%010d", (long) (Math.random() * 1_000_000_0000L)); sleep(100); System.out.println("Transaction ID minted: " + txId); return new Transaction( txId, request.getSourceAccount(), request.getTargetAccount(), request.getAmount()); } @Override public Transaction initTransaction(Transaction tx) { System.out.println("Initializing transaction"); sleep(300); if (tx.getAmount() <= 0) { System.out.println("Invalid amount: " + tx.getAmount()); throw ApplicationFailure.newNonRetryableFailure( "Non-retryable Activity Failure: Invalid Amount", "InvalidAmount"); } sleep(500); return tx; } @Override public void cancelTransaction(Transaction tx) { System.out.println("Cancelling transaction"); sleep(300); System.out.println("Transaction cancelled"); } @Override public void completeTransaction(Transaction tx) { System.out.println( "Sending $" + tx.getAmount() + " from " + tx.getSourceAccount() + " to " + tx.getTargetAccount()); sleep(2000); System.out.println("Transaction completed successfully"); } private void sleep(long millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } ================================================ FILE: core/src/main/java/io/temporal/samples/earlyreturn/TransactionRequest.java ================================================ package io.temporal.samples.earlyreturn; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; public final class TransactionRequest { private final String sourceAccount; private final String targetAccount; private final int amount; @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) public TransactionRequest( @JsonProperty("sourceAccount") String sourceAccount, @JsonProperty("targetAccount") String targetAccount, @JsonProperty("amount") int amount) { this.sourceAccount = sourceAccount; this.targetAccount = targetAccount; this.amount = amount; } @JsonProperty("sourceAccount") public String getSourceAccount() { return sourceAccount; } @JsonProperty("targetAccount") public String getTargetAccount() { return targetAccount; } @JsonProperty("amount") public int getAmount() { return amount; } @Override public String toString() { return String.format( "TransactionRequest{sourceAccount='%s', targetAccount='%s', amount=%d}", sourceAccount, targetAccount, amount); } } ================================================ FILE: core/src/main/java/io/temporal/samples/earlyreturn/TransactionWorkflow.java ================================================ package io.temporal.samples.earlyreturn; import io.temporal.workflow.UpdateMethod; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; @WorkflowInterface public interface TransactionWorkflow { @WorkflowMethod TxResult processTransaction(TransactionRequest txRequest); @UpdateMethod(name = "early-return") TxResult returnInitResult(); } ================================================ FILE: core/src/main/java/io/temporal/samples/earlyreturn/TransactionWorkflowImpl.java ================================================ package io.temporal.samples.earlyreturn; import io.temporal.activity.ActivityOptions; import io.temporal.workflow.Workflow; import java.time.Duration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TransactionWorkflowImpl implements TransactionWorkflow { private static final Logger log = LoggerFactory.getLogger(TransactionWorkflowImpl.class); private final TransactionActivities activities = Workflow.newActivityStub( TransactionActivities.class, ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(30)).build()); private boolean initDone = false; private Transaction tx; private Exception initError = null; @Override public TxResult processTransaction(TransactionRequest txRequest) { this.tx = activities.mintTransactionId(txRequest); try { this.tx = activities.initTransaction(this.tx); } catch (Exception e) { initError = e; } finally { initDone = true; } if (initError != null) { // If initialization failed, cancel the transaction activities.cancelTransaction(this.tx); return new TxResult("", "Transaction cancelled."); } else { activities.completeTransaction(this.tx); return new TxResult(this.tx.getId(), "Transaction completed successfully."); } } @Override public TxResult returnInitResult() { Workflow.await(() -> initDone); if (initError != null) { log.info("Initialization failed."); throw Workflow.wrap(initError); } return new TxResult(tx.getId(), "Initialization successful"); } } ================================================ FILE: core/src/main/java/io/temporal/samples/earlyreturn/TxResult.java ================================================ package io.temporal.samples.earlyreturn; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; public class TxResult { private final String transactionId; private final String status; // Jackson-compatible constructor with @JsonCreator and @JsonProperty annotations @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) public TxResult( @JsonProperty("transactionId") String transactionId, @JsonProperty("status") String status) { this.transactionId = transactionId; this.status = status; } @JsonProperty("transactionId") public String getTransactionId() { return transactionId; } @JsonProperty("status") public String getStatus() { return status; } @Override public String toString() { return String.format("InitResult{transactionId='%s', status='%s'}", transactionId, status); } } ================================================ FILE: core/src/main/java/io/temporal/samples/encodefailures/CustomerAgeCheck.java ================================================ package io.temporal.samples.encodefailures; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; @WorkflowInterface public interface CustomerAgeCheck { @WorkflowMethod public String validateCustomer(MyCustomer customer); } ================================================ FILE: core/src/main/java/io/temporal/samples/encodefailures/CustomerAgeCheckImpl.java ================================================ package io.temporal.samples.encodefailures; import io.temporal.workflow.Workflow; public class CustomerAgeCheckImpl implements CustomerAgeCheck { @Override public String validateCustomer(MyCustomer customer) { // Note we have explicitly set InvalidCustomerException type to fail workflow execution // We wrap it using Workflow.wrap so can throw as unchecked if (customer.getAge() < 21) { throw Workflow.wrap( new InvalidCustomerException("customer " + customer.getName() + " is under age.")); } else { return "done..."; } } } ================================================ FILE: core/src/main/java/io/temporal/samples/encodefailures/InvalidCustomerException.java ================================================ package io.temporal.samples.encodefailures; public class InvalidCustomerException extends Exception { public InvalidCustomerException(String errorMessage) { super(errorMessage); } } ================================================ FILE: core/src/main/java/io/temporal/samples/encodefailures/MyCustomer.java ================================================ package io.temporal.samples.encodefailures; public class MyCustomer { private String name; private int age; private boolean approved; public MyCustomer() {} public MyCustomer(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public boolean isApproved() { return approved; } public void setApproved(boolean approved) { this.approved = approved; } } ================================================ FILE: core/src/main/java/io/temporal/samples/encodefailures/README.md ================================================ # Using Codec to encode / decode failure messages The sample demonstrates how to set up a simple codec for encoding/decoding failure messages In this sample we set encodeFailureAttributes = true to our CodecDataConverter meaning we want to encode / decode failure messages as well. All it does is add a "Customer: " prefix to the message. You can expand on this to add any type of encoding that you might want to use. Our workflow does simple customer age check validation and fails if their age is < 21. In the Starter then we print out that the failure message client received on execution failure was indeed encoded using our codec. ## Running 1. Start Temporal Server with "default" namespace enabled. For example using local Docker: ```bash git clone https://github.com/temporalio/docker-compose.git cd docker-compose docker-compose up ``` 2. Run the following command to start the sample: ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.encodefailures.Starter ``` ================================================ FILE: core/src/main/java/io/temporal/samples/encodefailures/SimplePrefixPayloadCodec.java ================================================ package io.temporal.samples.encodefailures; import com.google.protobuf.ByteString; import io.temporal.api.common.v1.Payload; import io.temporal.payload.codec.PayloadCodec; import io.temporal.payload.codec.PayloadCodecException; import java.util.List; import java.util.stream.Collectors; import org.jetbrains.annotations.NotNull; /** * Simple codec that adds dummy prefix to payload. For this sample it's also applied for failure * messages. */ public class SimplePrefixPayloadCodec implements PayloadCodec { public static final ByteString PREFIX = ByteString.copyFromUtf8("Customer: "); @NotNull @Override public List encode(@NotNull List payloads) { return payloads.stream().map(this::encode).collect(Collectors.toList()); } private Payload encode(Payload decodedPayload) { ByteString encodedData = PREFIX.concat(decodedPayload.getData()); return decodedPayload.toBuilder().setData(encodedData).build(); } @NotNull @Override public List decode(@NotNull List payloads) { return payloads.stream().map(this::decode).collect(Collectors.toList()); } private Payload decode(Payload encodedPayload) { ByteString encodedData = encodedPayload.getData(); if (!encodedData.startsWith(PREFIX)) throw new PayloadCodecException("Payload is not correctly encoded"); ByteString decodedData = encodedData.substring(PREFIX.size()); return encodedPayload.toBuilder().setData(decodedData).build(); } } ================================================ FILE: core/src/main/java/io/temporal/samples/encodefailures/Starter.java ================================================ package io.temporal.samples.encodefailures; import io.temporal.api.common.v1.Payload; import io.temporal.api.history.v1.HistoryEvent; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowClientOptions; import io.temporal.client.WorkflowFailedException; import io.temporal.client.WorkflowOptions; import io.temporal.common.converter.CodecDataConverter; import io.temporal.common.converter.DefaultDataConverter; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import io.temporal.worker.WorkflowImplementationOptions; import java.io.IOException; import java.util.Collections; public class Starter { private static final String TASK_QUEUE = "EncodeDecodeFailuresTaskQueue"; private static final String WORKFLOW_ID = "CustomerValidationWorkflow"; public static void main(String[] args) { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); // CodecDataConverter defines our data converter and codec // sets encodeFailureAttributes to true CodecDataConverter codecDataConverter = new CodecDataConverter( // For sample we just use default data converter DefaultDataConverter.newDefaultInstance(), // Simple prefix codec to encode/decode Collections.singletonList(new SimplePrefixPayloadCodec()), true); // Setting encodeFailureAttributes to true // WorkflowClient uses our CodecDataConverter WorkflowClient client = WorkflowClient.newInstance( service, WorkflowClientOptions.newBuilder().setDataConverter(codecDataConverter).build()); // Create worker and start Worker factory createWorker(client); // Start workflow execution and catch client error (workflow execution fails) CustomerAgeCheck workflow = client.newWorkflowStub( CustomerAgeCheck.class, WorkflowOptions.newBuilder() .setWorkflowId(WORKFLOW_ID) .setTaskQueue(TASK_QUEUE) .build()); try { // Start workflow execution to validate under-age customer workflow.validateCustomer(new MyCustomer("John", 17)); System.out.println("Workflow should have failed on customer validation"); } catch (WorkflowFailedException e) { // Get failure message from last event in history (WorkflowExecutionFailed event) and check // that // its encoded HistoryEvent wfExecFailedEvent = client.fetchHistory(WORKFLOW_ID).getLastEvent(); Payload payload = wfExecFailedEvent .getWorkflowExecutionFailedEventAttributes() .getFailure() .getEncodedAttributes(); if (isEncoded(payload)) { System.out.println("Workflow failure was encoded"); } else { System.out.println("Workflow failure was not encoded"); } } // Stop sample System.exit(0); } private static boolean isEncoded(Payload payload) { return payload.getData().startsWith(SimplePrefixPayloadCodec.PREFIX); } private static void createWorker(WorkflowClient client) { WorkerFactory factory = WorkerFactory.newInstance(client); Worker worker = factory.newWorker(TASK_QUEUE); worker.registerWorkflowImplementationTypes( WorkflowImplementationOptions.newBuilder() // note we set InvalidCustomerException to fail execution .setFailWorkflowExceptionTypes(InvalidCustomerException.class) .build(), CustomerAgeCheckImpl.class); factory.start(); } } ================================================ FILE: core/src/main/java/io/temporal/samples/encryptedpayloads/CryptCodec.java ================================================ package io.temporal.samples.encryptedpayloads; import com.google.protobuf.ByteString; import io.temporal.api.common.v1.Payload; import io.temporal.common.converter.DataConverterException; import io.temporal.common.converter.EncodingKeys; import io.temporal.payload.codec.PayloadCodec; import io.temporal.payload.codec.PayloadCodecException; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.security.SecureRandom; import java.util.List; import java.util.stream.Collectors; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.spec.GCMParameterSpec; import javax.crypto.spec.SecretKeySpec; import org.jetbrains.annotations.NotNull; class CryptCodec implements PayloadCodec { static final ByteString METADATA_ENCODING = ByteString.copyFrom("binary/encrypted", StandardCharsets.UTF_8); private static final String CIPHER = "AES/GCM/NoPadding"; static final String METADATA_ENCRYPTION_CIPHER_KEY = "encryption-cipher"; static final ByteString METADATA_ENCRYPTION_CIPHER = ByteString.copyFrom(CIPHER, StandardCharsets.UTF_8); static final String METADATA_ENCRYPTION_KEY_ID_KEY = "encryption-key-id"; private static final int GCM_NONCE_LENGTH_BYTE = 12; private static final int GCM_TAG_LENGTH_BIT = 128; private static final Charset UTF_8 = StandardCharsets.UTF_8; @NotNull @Override public List encode(@NotNull List payloads) { return payloads.stream().map(this::encodePayload).collect(Collectors.toList()); } @NotNull @Override public List decode(@NotNull List payloads) { return payloads.stream().map(this::decodePayload).collect(Collectors.toList()); } private Payload encodePayload(Payload payload) { String keyId = getKeyId(); SecretKey key = getKey(keyId); byte[] encryptedData; try { encryptedData = encrypt(payload.toByteArray(), key); } catch (Throwable e) { throw new DataConverterException(e); } return Payload.newBuilder() .putMetadata(EncodingKeys.METADATA_ENCODING_KEY, METADATA_ENCODING) .putMetadata(METADATA_ENCRYPTION_CIPHER_KEY, METADATA_ENCRYPTION_CIPHER) .putMetadata(METADATA_ENCRYPTION_KEY_ID_KEY, ByteString.copyFromUtf8(keyId)) .setData(ByteString.copyFrom(encryptedData)) .build(); } private Payload decodePayload(Payload payload) { if (METADATA_ENCODING.equals( payload.getMetadataOrDefault(EncodingKeys.METADATA_ENCODING_KEY, null))) { String keyId; try { keyId = payload.getMetadataOrThrow(METADATA_ENCRYPTION_KEY_ID_KEY).toString(UTF_8); } catch (Exception e) { throw new PayloadCodecException(e); } SecretKey key = getKey(keyId); byte[] plainData; Payload decryptedPayload; try { plainData = decrypt(payload.getData().toByteArray(), key); decryptedPayload = Payload.parseFrom(plainData); return decryptedPayload; } catch (Throwable e) { throw new PayloadCodecException(e); } } else { return payload; } } private String getKeyId() { // Currently there is no context available to vary which key is used. // Use a fixed key for all payloads. // This still supports key rotation as the key ID is recorded on payloads allowing // decryption to use a previous key. return "test-key-test-key-test-key-test!"; } private SecretKey getKey(String keyId) { // Key must be fetched from KMS or other secure storage. // Hard coded here only for example purposes. return new SecretKeySpec(keyId.getBytes(UTF_8), "AES"); } private static byte[] getNonce(int size) { byte[] nonce = new byte[size]; new SecureRandom().nextBytes(nonce); return nonce; } private byte[] encrypt(byte[] plainData, SecretKey key) throws Exception { byte[] nonce = getNonce(GCM_NONCE_LENGTH_BYTE); Cipher cipher = Cipher.getInstance(CIPHER); cipher.init(Cipher.ENCRYPT_MODE, key, new GCMParameterSpec(GCM_TAG_LENGTH_BIT, nonce)); byte[] encryptedData = cipher.doFinal(plainData); return ByteBuffer.allocate(nonce.length + encryptedData.length) .put(nonce) .put(encryptedData) .array(); } private byte[] decrypt(byte[] encryptedDataWithNonce, SecretKey key) throws Exception { ByteBuffer buffer = ByteBuffer.wrap(encryptedDataWithNonce); byte[] nonce = new byte[GCM_NONCE_LENGTH_BYTE]; buffer.get(nonce); byte[] encryptedData = new byte[buffer.remaining()]; buffer.get(encryptedData); Cipher cipher = Cipher.getInstance(CIPHER); cipher.init(Cipher.DECRYPT_MODE, key, new GCMParameterSpec(GCM_TAG_LENGTH_BIT, nonce)); return cipher.doFinal(encryptedData); } } ================================================ FILE: core/src/main/java/io/temporal/samples/encryptedpayloads/EncryptedPayloadsActivity.java ================================================ package io.temporal.samples.encryptedpayloads; import io.temporal.activity.ActivityInterface; import io.temporal.activity.ActivityMethod; import io.temporal.activity.ActivityOptions; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowClientOptions; import io.temporal.client.WorkflowOptions; import io.temporal.common.converter.CodecDataConverter; import io.temporal.common.converter.DefaultDataConverter; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import io.temporal.workflow.Workflow; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; import java.io.IOException; import java.time.Duration; import java.util.Collections; /** * Hello World Temporal workflow that executes a single activity. Requires a local instance the * Temporal service to be running. */ public class EncryptedPayloadsActivity { static final String TASK_QUEUE = "EncryptedPayloads"; /** Workflow interface has to have at least one method annotated with @WorkflowMethod. */ @WorkflowInterface public interface GreetingWorkflow { @WorkflowMethod String getGreeting(String name); } /** Activity interface is just a POJI. */ @ActivityInterface public interface GreetingActivities { @ActivityMethod String composeGreeting(String greeting, String name); } /** GreetingWorkflow implementation that calls GreetingsActivities#composeGreeting. */ public static class GreetingWorkflowImpl implements GreetingWorkflow { /** * Activity stub implements activity interface and proxies calls to it to Temporal activity * invocations. Because activities are reentrant, only a single stub can be used for multiple * activity invocations. */ private final GreetingActivities activities = Workflow.newActivityStub( GreetingActivities.class, ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(2)).build()); @Override public String getGreeting(String name) { // This is a blocking call that returns only after the activity has completed. return activities.composeGreeting("Hello", name); } } static class GreetingActivitiesImpl implements GreetingActivities { @Override public String composeGreeting(String greeting, String name) { return greeting + " " + name + "!"; } } public static void main(String[] args) { // gRPC stubs wrapper that talks to the local docker instance of temporal service. // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); // client that can be used to start and signal workflows WorkflowClient client = WorkflowClient.newInstance( service, WorkflowClientOptions.newBuilder() .setDataConverter( new CodecDataConverter( DefaultDataConverter.newDefaultInstance(), Collections.singletonList(new CryptCodec()))) .build()); // worker factory that can be used to create workers for specific task queues WorkerFactory factory = WorkerFactory.newInstance(client); // Worker that listens on a task queue and hosts both workflow and activity implementations. Worker worker = factory.newWorker(TASK_QUEUE); // Workflows are stateful. So you need a type to create instances. worker.registerWorkflowImplementationTypes(GreetingWorkflowImpl.class); // Activities are stateless and thread safe. So a shared instance is used. worker.registerActivitiesImplementations(new GreetingActivitiesImpl()); // Start listening to the workflow and activity task queues. factory.start(); // Start a workflow execution. Usually this is done from another program. // Uses task queue from the GreetingWorkflow @WorkflowMethod annotation. GreetingWorkflow workflow = client.newWorkflowStub( GreetingWorkflow.class, WorkflowOptions.newBuilder().setTaskQueue(TASK_QUEUE).build()); // Execute a workflow waiting for it to complete. See {@link // io.temporal.samples.hello.HelloSignal} // for an example of starting workflow without waiting synchronously for its result. String greeting = workflow.getGreeting("My Secret Friend"); System.out.println(greeting); System.exit(0); } } ================================================ FILE: core/src/main/java/io/temporal/samples/envconfig/LoadFromFile.java ================================================ package io.temporal.samples.envconfig; // @@@SNIPSTART java-env-config-profile import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowClientOptions; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.envconfig.LoadClientConfigProfileOptions; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.serviceclient.WorkflowServiceStubsOptions; import java.nio.file.Paths; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This sample demonstrates loading the default environment configuration profile from a TOML file. */ public class LoadFromFile { private static final Logger logger = LoggerFactory.getLogger(LoadFromFile.class); public static void main(String[] args) { try { // For this sample to be self-contained, we explicitly provide the path to // the config.toml file included in this directory. // By default though, the config.toml file will be loaded from // ~/.config/temporal/temporal.toml (or the equivalent standard config directory on your OS). String configFilePath = Paths.get(LoadFromFile.class.getResource("/config.toml").toURI()).toString(); logger.info("--- Loading 'default' profile from {} ---", configFilePath); // Load client profile from file. By default, this loads the "default" profile // and applies any environment variable overrides. ClientConfigProfile profile = ClientConfigProfile.load( LoadClientConfigProfileOptions.newBuilder() .setConfigFilePath(configFilePath) .build()); // Convert profile to client options (equivalent to Python's load_client_connect_config) WorkflowServiceStubsOptions serviceStubsOptions = profile.toWorkflowServiceStubsOptions(); WorkflowClientOptions clientOptions = profile.toWorkflowClientOptions(); logger.info("Loaded 'default' profile from {}", configFilePath); logger.info(" Address: {}", serviceStubsOptions.getTarget()); logger.info(" Namespace: {}", clientOptions.getNamespace()); if (serviceStubsOptions.getHeaders() != null && !serviceStubsOptions.getHeaders().keys().isEmpty()) { logger.info(" gRPC Metadata keys: {}", serviceStubsOptions.getHeaders().keys()); } logger.info("\nAttempting to connect to client..."); try { // Create the workflow client using the loaded configuration WorkflowClient client = WorkflowClient.newInstance( WorkflowServiceStubs.newServiceStubs(serviceStubsOptions), clientOptions); // Test the connection by getting system info var systemInfo = client .getWorkflowServiceStubs() .blockingStub() .getSystemInfo( io.temporal.api.workflowservice.v1.GetSystemInfoRequest.getDefaultInstance()); logger.info("✅ Client connected successfully!"); logger.info(" Server version: {}", systemInfo.getServerVersion()); } catch (Exception e) { logger.error("❌ Failed to connect: {}", e.getMessage()); } } catch (Exception e) { logger.error("Failed to load configuration: {}", e.getMessage(), e); System.exit(1); } } } // @@@SNIPEND ================================================ FILE: core/src/main/java/io/temporal/samples/envconfig/LoadProfile.java ================================================ package io.temporal.samples.envconfig; // @@@SNIPSTART java-env-config-profile-with-overrides import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowClientOptions; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.envconfig.LoadClientConfigProfileOptions; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.serviceclient.WorkflowServiceStubsOptions; import java.nio.file.Paths; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This sample demonstrates loading a specific profile from a TOML configuration file with * programmatic overrides. */ public class LoadProfile { private static final Logger logger = LoggerFactory.getLogger(LoadProfile.class); public static void main(String[] args) { String profileName = "staging"; try { // For this sample to be self-contained, we explicitly provide the path to // the config.toml file included in this directory. String configFilePath = Paths.get(LoadProfile.class.getResource("/config.toml").toURI()).toString(); logger.info("--- Loading '{}' profile from {} ---", profileName, configFilePath); // Load specific profile from file with environment variable overrides ClientConfigProfile profile = ClientConfigProfile.load( LoadClientConfigProfileOptions.newBuilder() .setConfigFilePath(configFilePath) .setConfigFileProfile(profileName) .build()); // Demonstrate programmatic override - fix the incorrect address from staging profile logger.info("\n--- Applying programmatic override ---"); ClientConfigProfile.Builder profileBuilder = profile.toBuilder(); profileBuilder.setAddress("localhost:7233"); // Override the incorrect address profile = profileBuilder.build(); logger.info(" Overridden address to: {}", profile.getAddress()); // Convert profile to client options (equivalent to Python's load_client_connect_config) WorkflowServiceStubsOptions serviceStubsOptions = profile.toWorkflowServiceStubsOptions(); WorkflowClientOptions clientOptions = profile.toWorkflowClientOptions(); logger.info("Loaded '{}' profile from {}", profileName, configFilePath); logger.info(" Address: {}", serviceStubsOptions.getTarget()); logger.info(" Namespace: {}", clientOptions.getNamespace()); if (serviceStubsOptions.getHeaders() != null && !serviceStubsOptions.getHeaders().keys().isEmpty()) { logger.info(" gRPC Metadata keys: {}", serviceStubsOptions.getHeaders().keys()); } logger.info("\nAttempting to connect to client..."); try { // Create the workflow client using the loaded configuration WorkflowClient client = WorkflowClient.newInstance( WorkflowServiceStubs.newServiceStubs(serviceStubsOptions), clientOptions); // Test the connection by getting system info var systemInfo = client .getWorkflowServiceStubs() .blockingStub() .getSystemInfo( io.temporal.api.workflowservice.v1.GetSystemInfoRequest.getDefaultInstance()); logger.info("✅ Client connected successfully!"); logger.info(" Server version: {}", systemInfo.getServerVersion()); } catch (Exception e) { logger.error("❌ Failed to connect: {}", e.getMessage()); } } catch (Exception e) { logger.error("Failed to load configuration: {}", e.getMessage(), e); System.exit(1); } } } // @@@SNIPEND ================================================ FILE: core/src/main/java/io/temporal/samples/envconfig/README.md ================================================ # Environment Configuration Sample This sample demonstrates how to configure a Temporal client using TOML configuration files. This allows you to manage connection settings across different environments without hardcoding them. The `config.toml` file defines three profiles: - `[profile.default]`: Local development configuration - `[profile.staging]`: Configuration with incorrect address to demonstrate overrides - `[profile.prod]`: Example production configuration (not runnable) **Load from file (default profile):** ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.envconfig.LoadFromFile ``` **Load specific profile with overrides:** ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.envconfig.LoadProfile ``` ================================================ FILE: core/src/main/java/io/temporal/samples/excludefrominterceptor/README.md ================================================ # Excluding certain Workflow and Activity Types from interceptors This sample shows how to exclude certain workflow types and Activity types from Workflow and Activity Interceptors. 1. Start the Sample: ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.excludefrominterceptor.RunMyWorkflows ``` Observe the event histories of MyWorkflowOne and MyWorkflowTwo in your Temporal Web UI. You should see that even tho both executions were served by same worker so both had the interceptors applied, MyWorkflowTwo was excluded from being applied by these interceptors. Also from the Activity interceptor logs (System.out prints during sample run) note that only ActivityOne activity is being intercepted and not ActivityTwo or the "ForInterceptor" activities. ================================================ FILE: core/src/main/java/io/temporal/samples/excludefrominterceptor/RunMyWorkflows.java ================================================ package io.temporal.samples.excludefrominterceptor; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.client.WorkflowStub; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.samples.excludefrominterceptor.activities.ForInterceptorActivitiesImpl; import io.temporal.samples.excludefrominterceptor.activities.MyActivitiesImpl; import io.temporal.samples.excludefrominterceptor.interceptor.MyWorkerInterceptor; import io.temporal.samples.excludefrominterceptor.workflows.*; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import io.temporal.worker.WorkerFactoryOptions; import java.io.IOException; import java.util.Arrays; import java.util.concurrent.CompletableFuture; public class RunMyWorkflows { public static void main(String[] args) { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); WorkerFactoryOptions wfo = WorkerFactoryOptions.newBuilder() // exclude MyWorkflowTwo from interceptor .setWorkerInterceptors( new MyWorkerInterceptor( // exclude MyWorkflowTwo from workflow interceptors Arrays.asList(MyWorkflowTwo.class.getSimpleName()), // exclude ActivityTwo and the "ForInterceptor" activities from activity // interceptor // note with SpringBoot starter you could use bean names here, we use strings to // not have // to reflect on the activity impl class in sample Arrays.asList( "ActivityTwo", "ForInterceptorActivityOne", "ForInterceptorActivityTwo"))) .validateAndBuildWithDefaults(); WorkerFactory factory = WorkerFactory.newInstance(client, wfo); Worker worker = factory.newWorker("exclude-from-interceptor-queue"); worker.registerWorkflowImplementationTypes(MyWorkflowOneImpl.class, MyWorkflowTwoImpl.class); worker.registerActivitiesImplementations( new MyActivitiesImpl(), new ForInterceptorActivitiesImpl()); factory.start(); MyWorkflow myWorkflow = client.newWorkflowStub( MyWorkflowOne.class, WorkflowOptions.newBuilder() .setWorkflowId("MyWorkflowOne") .setTaskQueue("exclude-from-interceptor-queue") .build()); MyWorkflowTwo myWorkflowTwo = client.newWorkflowStub( MyWorkflowTwo.class, WorkflowOptions.newBuilder() .setWorkflowId("MyWorkflowTwo") .setTaskQueue("exclude-from-interceptor-queue") .build()); WorkflowClient.start(myWorkflow::execute, "my workflow input"); WorkflowClient.start(myWorkflowTwo::execute, "my workflow two input"); // wait for both execs to complete try { CompletableFuture.allOf( WorkflowStub.fromTyped(myWorkflow).getResultAsync(String.class), WorkflowStub.fromTyped(myWorkflowTwo).getResultAsync(String.class)) .get(); } catch (Exception e) { System.out.println("Error: " + e.getMessage()); } System.exit(0); } } ================================================ FILE: core/src/main/java/io/temporal/samples/excludefrominterceptor/activities/ForInterceptorActivities.java ================================================ package io.temporal.samples.excludefrominterceptor.activities; import io.temporal.activity.ActivityInterface; @ActivityInterface public interface ForInterceptorActivities { void forInterceptorActivityOne(Object output); void forInterceptorActivityTwo(Object output); } ================================================ FILE: core/src/main/java/io/temporal/samples/excludefrominterceptor/activities/ForInterceptorActivitiesImpl.java ================================================ package io.temporal.samples.excludefrominterceptor.activities; public class ForInterceptorActivitiesImpl implements ForInterceptorActivities { @Override public void forInterceptorActivityOne(Object output) {} @Override public void forInterceptorActivityTwo(Object output) {} } ================================================ FILE: core/src/main/java/io/temporal/samples/excludefrominterceptor/activities/MyActivities.java ================================================ package io.temporal.samples.excludefrominterceptor.activities; import io.temporal.activity.ActivityInterface; @ActivityInterface public interface MyActivities { void activityOne(String input); void activityTwo(String input); } ================================================ FILE: core/src/main/java/io/temporal/samples/excludefrominterceptor/activities/MyActivitiesImpl.java ================================================ package io.temporal.samples.excludefrominterceptor.activities; public class MyActivitiesImpl implements MyActivities { @Override public void activityOne(String input) {} @Override public void activityTwo(String input) {} } ================================================ FILE: core/src/main/java/io/temporal/samples/excludefrominterceptor/interceptor/MyActivityInboundCallsInterceptor.java ================================================ package io.temporal.samples.excludefrominterceptor.interceptor; import io.temporal.activity.ActivityExecutionContext; import io.temporal.common.interceptors.ActivityInboundCallsInterceptor; import io.temporal.common.interceptors.ActivityInboundCallsInterceptorBase; import java.util.ArrayList; import java.util.List; public class MyActivityInboundCallsInterceptor extends ActivityInboundCallsInterceptorBase { private ActivityExecutionContext activityExecutionContext; private List excludeActivityTypes = new ArrayList<>(); public MyActivityInboundCallsInterceptor(ActivityInboundCallsInterceptor next) { super(next); } public MyActivityInboundCallsInterceptor( List excludeActivityTypes, ActivityInboundCallsInterceptor next) { super(next); this.excludeActivityTypes = excludeActivityTypes; } @Override public void init(ActivityExecutionContext context) { this.activityExecutionContext = context; super.init(context); } @Override public ActivityOutput execute(ActivityInput input) { if (!excludeActivityTypes.contains(activityExecutionContext.getInfo().getActivityType())) { // If activity retry attempt is > X then we want to log this (or push to metrics or similar) // for demo we just use >=1 just to log and dont have to explicitly fail our sample activities if (activityExecutionContext.getInfo().getAttempt() >= 1) { System.out.println( "Activity retry attempt noted - " + activityExecutionContext.getInfo().getWorkflowType() + " - " + activityExecutionContext.getInfo().getActivityType()); } } return super.execute(input); } } ================================================ FILE: core/src/main/java/io/temporal/samples/excludefrominterceptor/interceptor/MyWorkerInterceptor.java ================================================ package io.temporal.samples.excludefrominterceptor.interceptor; import io.temporal.common.interceptors.*; import java.util.ArrayList; import java.util.List; public class MyWorkerInterceptor extends WorkerInterceptorBase { private List excludeWorkflowTypes = new ArrayList<>(); private List excludeActivityTypes = new ArrayList<>(); public MyWorkerInterceptor() {} public MyWorkerInterceptor(List excludeWorkflowTypes) { this.excludeWorkflowTypes = excludeWorkflowTypes; } public MyWorkerInterceptor(List excludeWorkflowTypes, List excludeActivityTypes) { this.excludeWorkflowTypes = excludeWorkflowTypes; this.excludeActivityTypes = excludeActivityTypes; } @Override public WorkflowInboundCallsInterceptor interceptWorkflow(WorkflowInboundCallsInterceptor next) { return new MyWorkflowInboundCallsInterceptor(excludeWorkflowTypes, next); } @Override public ActivityInboundCallsInterceptor interceptActivity(ActivityInboundCallsInterceptor next) { return new MyActivityInboundCallsInterceptor(excludeActivityTypes, next); } } ================================================ FILE: core/src/main/java/io/temporal/samples/excludefrominterceptor/interceptor/MyWorkflowInboundCallsInterceptor.java ================================================ package io.temporal.samples.excludefrominterceptor.interceptor; import io.temporal.activity.ActivityOptions; import io.temporal.common.interceptors.WorkflowInboundCallsInterceptor; import io.temporal.common.interceptors.WorkflowInboundCallsInterceptorBase; import io.temporal.common.interceptors.WorkflowOutboundCallsInterceptor; import io.temporal.samples.excludefrominterceptor.activities.ForInterceptorActivities; import io.temporal.workflow.Workflow; import io.temporal.workflow.WorkflowInfo; import java.time.Duration; import java.util.ArrayList; import java.util.List; public class MyWorkflowInboundCallsInterceptor extends WorkflowInboundCallsInterceptorBase { private WorkflowInfo workflowInfo; private List excludeWorkflowTypes = new ArrayList<>(); private ForInterceptorActivities activities = Workflow.newActivityStub( ForInterceptorActivities.class, ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(2)).build()); public MyWorkflowInboundCallsInterceptor(WorkflowInboundCallsInterceptor next) { super(next); } public MyWorkflowInboundCallsInterceptor( List excludeWorkflowTypes, WorkflowInboundCallsInterceptor next) { super(next); this.excludeWorkflowTypes = excludeWorkflowTypes; } @Override public void init(WorkflowOutboundCallsInterceptor outboundCalls) { this.workflowInfo = Workflow.getInfo(); super.init(new MyWorkflowOutboundCallsInterceptor(excludeWorkflowTypes, outboundCalls)); } @Override public WorkflowOutput execute(WorkflowInput input) { WorkflowOutput output = super.execute(input); if (!excludeWorkflowTypes.contains(workflowInfo.getWorkflowType())) { // After workflow completes we want to execute activity to lets say persist its result to db // or similar activities.forInterceptorActivityOne(output.getResult()); } return output; } } ================================================ FILE: core/src/main/java/io/temporal/samples/excludefrominterceptor/interceptor/MyWorkflowOutboundCallsInterceptor.java ================================================ package io.temporal.samples.excludefrominterceptor.interceptor; import io.temporal.activity.ActivityOptions; import io.temporal.common.interceptors.WorkflowOutboundCallsInterceptor; import io.temporal.common.interceptors.WorkflowOutboundCallsInterceptorBase; import io.temporal.samples.excludefrominterceptor.activities.ForInterceptorActivities; import io.temporal.workflow.Workflow; import java.time.Duration; import java.util.ArrayList; import java.util.List; public class MyWorkflowOutboundCallsInterceptor extends WorkflowOutboundCallsInterceptorBase { private List excludeWorkflowTypes = new ArrayList<>(); private ForInterceptorActivities activities = Workflow.newActivityStub( ForInterceptorActivities.class, ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(2)).build()); public MyWorkflowOutboundCallsInterceptor(WorkflowOutboundCallsInterceptor next) { super(next); } public MyWorkflowOutboundCallsInterceptor( List excludeWorkflowTypes, WorkflowOutboundCallsInterceptor next) { super(next); this.excludeWorkflowTypes = excludeWorkflowTypes; } @Override public ActivityOutput executeActivity(ActivityInput input) { ActivityOutput output = super.executeActivity(input); if (!excludeWorkflowTypes.contains(Workflow.getInfo().getWorkflowType())) { // After activity completes we want to execute activity to lets say persist its result to db // or similar activities.forInterceptorActivityTwo(output.getResult().get()); } return output; } } ================================================ FILE: core/src/main/java/io/temporal/samples/excludefrominterceptor/workflows/MyWorkflow.java ================================================ package io.temporal.samples.excludefrominterceptor.workflows; import io.temporal.workflow.WorkflowMethod; public interface MyWorkflow { @WorkflowMethod String execute(String input); } ================================================ FILE: core/src/main/java/io/temporal/samples/excludefrominterceptor/workflows/MyWorkflowOne.java ================================================ package io.temporal.samples.excludefrominterceptor.workflows; import io.temporal.workflow.WorkflowInterface; @WorkflowInterface public interface MyWorkflowOne extends MyWorkflow {} ================================================ FILE: core/src/main/java/io/temporal/samples/excludefrominterceptor/workflows/MyWorkflowOneImpl.java ================================================ package io.temporal.samples.excludefrominterceptor.workflows; import io.temporal.activity.ActivityOptions; import io.temporal.samples.excludefrominterceptor.activities.MyActivities; import io.temporal.workflow.Workflow; import java.time.Duration; public class MyWorkflowOneImpl implements MyWorkflowOne { private MyActivities activities = Workflow.newActivityStub( MyActivities.class, ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(2)).build()); @Override public String execute(String input) { activities.activityOne(input); activities.activityTwo(input); return "done"; } } ================================================ FILE: core/src/main/java/io/temporal/samples/excludefrominterceptor/workflows/MyWorkflowTwo.java ================================================ package io.temporal.samples.excludefrominterceptor.workflows; import io.temporal.workflow.WorkflowInterface; @WorkflowInterface public interface MyWorkflowTwo extends MyWorkflow {} ================================================ FILE: core/src/main/java/io/temporal/samples/excludefrominterceptor/workflows/MyWorkflowTwoImpl.java ================================================ package io.temporal.samples.excludefrominterceptor.workflows; import io.temporal.activity.ActivityOptions; import io.temporal.samples.excludefrominterceptor.activities.MyActivities; import io.temporal.workflow.Workflow; import java.time.Duration; public class MyWorkflowTwoImpl implements MyWorkflowTwo { private MyActivities activities = Workflow.newActivityStub( MyActivities.class, ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(2)).build()); @Override public String execute(String input) { activities.activityOne(input); activities.activityTwo(input); return "done"; } } ================================================ FILE: core/src/main/java/io/temporal/samples/fileprocessing/FileProcessingStarter.java ================================================ package io.temporal.samples.fileprocessing; import static io.temporal.samples.fileprocessing.FileProcessingWorker.TASK_QUEUE; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import java.io.IOException; import java.net.URL; /** Starts a file processing sample workflow. */ public class FileProcessingStarter { public static void main(String[] args) throws Exception { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } // gRPC stubs wrapper that talks to the temporal service. WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); // client that can be used to start and signal workflows WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); FileProcessingWorkflow workflow = client.newWorkflowStub( FileProcessingWorkflow.class, WorkflowOptions.newBuilder().setTaskQueue(TASK_QUEUE).build()); System.out.println("Executing FileProcessingWorkflow"); URL source = new URL("http://www.google.com/"); URL destination = new URL("http://dummy"); // This is going to block until the workflow completes. // This is rarely used in production. Use the commented code below for async start version. workflow.processFile(source, destination); System.out.println("FileProcessingWorkflow completed"); // Use this code instead of the above blocking call to start workflow asynchronously. // WorkflowExecution workflowExecution = // WorkflowClient.start(workflow::processFile, source, destination); // System.out.println( // "Started periodic workflow with workflowId=\"" // + workflowExecution.getWorkflowId() // + "\" and runId=\"" // + workflowExecution.getRunId() // + "\""); // System.exit(0); } } ================================================ FILE: core/src/main/java/io/temporal/samples/fileprocessing/FileProcessingWorker.java ================================================ package io.temporal.samples.fileprocessing; import io.temporal.client.WorkflowClient; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import java.io.IOException; import java.lang.management.ManagementFactory; /** * This is the process that hosts all workflows and activities in this sample. Run multiple * instances of the worker in different windows. Then start a workflow by running the * FileProcessingStarter. Note that all activities always execute on the same worker. But each time * they might end up on a different worker as the first activity is dispatched to the common task * list. */ public class FileProcessingWorker { static final String TASK_QUEUE = "FileProcessing"; public static void main(String[] args) { String hostSpecifiTaskQueue = ManagementFactory.getRuntimeMXBean().getName(); // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } // gRPC stubs wrapper that talks to the temporal service. WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); // client that can be used to start and signal workflows WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); // worker factory that can be used to create workers for specific task queues WorkerFactory factory = WorkerFactory.newInstance(client); // Worker that listens on a task queue and hosts both workflow and activity implementations. final Worker workerForCommonTaskQueue = factory.newWorker(TASK_QUEUE); workerForCommonTaskQueue.registerWorkflowImplementationTypes(FileProcessingWorkflowImpl.class); StoreActivitiesImpl storeActivityImpl = new StoreActivitiesImpl(hostSpecifiTaskQueue); workerForCommonTaskQueue.registerActivitiesImplementations(storeActivityImpl); // Get worker to poll the host-specific task queue. final Worker workerForHostSpecificTaskQueue = factory.newWorker(hostSpecifiTaskQueue); workerForHostSpecificTaskQueue.registerActivitiesImplementations(storeActivityImpl); // Start all workers created by this factory. factory.start(); System.out.println("Worker started for task queue: " + TASK_QUEUE); System.out.println("Worker Started for activity task Queue: " + hostSpecifiTaskQueue); } } ================================================ FILE: core/src/main/java/io/temporal/samples/fileprocessing/FileProcessingWorkflow.java ================================================ package io.temporal.samples.fileprocessing; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; import java.net.URL; /** Contract for file processing workflow. */ @WorkflowInterface public interface FileProcessingWorkflow { @WorkflowMethod void processFile(URL source, URL destination); } ================================================ FILE: core/src/main/java/io/temporal/samples/fileprocessing/FileProcessingWorkflowImpl.java ================================================ package io.temporal.samples.fileprocessing; import io.temporal.activity.ActivityOptions; import io.temporal.common.RetryOptions; import io.temporal.workflow.Workflow; import java.net.URL; import java.time.Duration; import java.util.Optional; /** * This implementation of FileProcessingWorkflow downloads the file, zips it, and uploads it to a * destination. An important requirement for such a workflow is that while a first activity can run * on any host, the second and third must run on the same host as the first one. This is achieved * through use of a host specific task queue. The first activity returns the name of the host * specific task queue and all other activities are dispatched using the stub that is configured * with it. This assumes that FileProcessingWorker has a worker running on the same task queue. */ public class FileProcessingWorkflowImpl implements FileProcessingWorkflow { // Uses the default task queue shared by the pool of workers. private final StoreActivities defaultTaskQueueActivities; public FileProcessingWorkflowImpl() { // Create activity clients. ActivityOptions ao = ActivityOptions.newBuilder() .setStartToCloseTimeout(Duration.ofSeconds(20)) .setRetryOptions( RetryOptions.newBuilder() .setInitialInterval(Duration.ofSeconds(1)) .setMaximumAttempts(4) .setDoNotRetry(IllegalArgumentException.class.getName()) .build()) .build(); this.defaultTaskQueueActivities = Workflow.newActivityStub(StoreActivities.class, ao); } @Override public void processFile(URL source, URL destination) { RetryOptions retryOptions = RetryOptions.newBuilder().setInitialInterval(Duration.ofSeconds(1)).build(); // Retries the whole sequence on any failure, potentially on a different host. Workflow.retry(retryOptions, Optional.empty(), () -> processFileImpl(source, destination)); } private void processFileImpl(URL source, URL destination) { StoreActivities.TaskQueueFileNamePair downloaded = defaultTaskQueueActivities.download(source); // Now initialize stubs that are specific to the returned task queue. ActivityOptions hostActivityOptions = ActivityOptions.newBuilder() .setTaskQueue(downloaded.getHostTaskQueue()) // Set the amount a time an activity task can stay in the task queue before its picked // up by a Worker. It allows us to support cases where // the activity worker crashes or restarts before the activity starts execution. // This timeout should be specified only when host specific activity task queues are // used like in this sample. // Note that scheduleToStart timeout is not retryable and retry options will ignore it. // This timeout has to be handled by Workflow code. .setScheduleToStartTimeout(Duration.ofSeconds(10)) // Set the max time of a single activity execution attempt. // Activity is going to be executed by a Worker listening to the specified // host task queue. If the activity is started but then the activity worker crashes // for some reason, we want to make sure that it is retried after the specified timeout. // This timeout should be be as short as the longest possible execution of the Activity. .setStartToCloseTimeout(Duration.ofSeconds(2)) .setRetryOptions( RetryOptions.newBuilder() .setInitialInterval(Duration.ofSeconds(1)) .setMaximumAttempts(4) .setDoNotRetry(IllegalArgumentException.class.getName()) .build()) .build(); StoreActivities hostSpecificStore = Workflow.newActivityStub(StoreActivities.class, hostActivityOptions); // Call processFile activity to zip the file. // Call the activity to process the file using worker-specific task queue. String processed = hostSpecificStore.process(downloaded.getFileName()); // Call upload activity to upload the zipped file. hostSpecificStore.upload(processed, destination); } } ================================================ FILE: core/src/main/java/io/temporal/samples/fileprocessing/README.md ================================================ Demonstrates how to route tasks to specific Workers. This sample has a set of Activities that download a file, processes it, and uploads the result to a destination. Any Worker can execute the first Activity. However, the second and third Activities must be executed on the same host as the first one. #### Running the File Processing Sample The sample has two executables. Execute each command in a separate terminal window. The first command runs the Worker that hosts the Workflow and Activity Executions. To demonstrate that Activities execute together, we recommend running more than one instance of this Worker. ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.fileprocessing.FileProcessingWorker ``` The second command start the Workflow Execution. Each time the command runs, it starts a new Workflow Execution. ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.fileprocessing.FileProcessingStarter ``` ================================================ FILE: core/src/main/java/io/temporal/samples/fileprocessing/StoreActivities.java ================================================ package io.temporal.samples.fileprocessing; import io.temporal.activity.ActivityInterface; import java.net.URL; @ActivityInterface public interface StoreActivities { final class TaskQueueFileNamePair { private String hostTaskQueue; private String fileName; public TaskQueueFileNamePair(String hostTaskQueue, String fileName) { this.hostTaskQueue = hostTaskQueue; this.fileName = fileName; } /** Jackson needs it */ public TaskQueueFileNamePair() {} public String getHostTaskQueue() { return hostTaskQueue; } public String getFileName() { return fileName; } } /** * Upload file to remote location. * * @param localFileName file to upload * @param url remote location */ void upload(String localFileName, URL url); /** * Process file. * * @param inputFileName source file name @@return processed file name */ String process(String inputFileName); /** * Downloads file to local disk. * * @param url remote file location * @return local task queue and downloaded file name */ TaskQueueFileNamePair download(URL url); } ================================================ FILE: core/src/main/java/io/temporal/samples/fileprocessing/StoreActivitiesImpl.java ================================================ package io.temporal.samples.fileprocessing; import com.google.common.io.Files; import com.google.common.io.Resources; import io.temporal.activity.Activity; import java.io.File; import java.io.IOException; import java.net.URL; /** Store activities implementation. */ public class StoreActivitiesImpl implements StoreActivities { private final String hostSpecificTaskQueue; public StoreActivitiesImpl(String taskQueue) { this.hostSpecificTaskQueue = taskQueue; } @Override @SuppressWarnings("deprecation") public TaskQueueFileNamePair download(URL url) { try { byte[] binary = Resources.toByteArray(url); File destination = new File(Files.createTempDir(), "downloaded"); Files.write(binary, destination); System.out.println( "download activity: downloaded from " + url + " to " + destination.getAbsolutePath()); return new TaskQueueFileNamePair(hostSpecificTaskQueue, destination.getAbsolutePath()); } catch (IOException e) { throw Activity.wrap(e); } } @Override public String process(String sourceFile) { System.out.println("process activity: sourceFile= " + sourceFile); try { String processedName = processFileImpl(sourceFile); System.out.println("process activity: processed file: " + processedName); return processedName; } catch (IOException e) { throw Activity.wrap(e); } } @SuppressWarnings("deprecation") private String processFileImpl(String fileName) throws IOException { File inputFile = new File(fileName); File inputDir = inputFile.getParentFile(); File outputFile = new File(inputDir, "processed"); // We don't really process it, just copy to keep the sample simple. Files.copy(inputFile, outputFile); return outputFile.getAbsolutePath(); } @Override public void upload(String localFileName, URL url) { File file = new File(localFileName); if (!file.isFile()) { throw new IllegalArgumentException("Invalid file type: " + file); } // Faking upload to simplify sample implementation. System.out.println("upload activity: uploaded from " + localFileName + " to " + url); } } ================================================ FILE: core/src/main/java/io/temporal/samples/getresultsasync/MyWorkflow.java ================================================ package io.temporal.samples.getresultsasync; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; @WorkflowInterface public interface MyWorkflow { @WorkflowMethod String justSleep(int seconds); } ================================================ FILE: core/src/main/java/io/temporal/samples/getresultsasync/MyWorkflowImpl.java ================================================ package io.temporal.samples.getresultsasync; import io.temporal.workflow.Workflow; import java.time.Duration; public class MyWorkflowImpl implements MyWorkflow { @Override public String justSleep(int seconds) { Workflow.sleep(Duration.ofSeconds(seconds)); return "woke up after " + seconds + " seconds"; } } ================================================ FILE: core/src/main/java/io/temporal/samples/getresultsasync/README.md ================================================ # Get Workflow results async This sample shows the use of WorkflowStub.getResult and WorkflowStub.getResultAsync to show how the Temporal Client API can not only start Workflows async but also wait for their results async as well. ## Run the sample 1. Start the Worker: ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.getresultsasync.Worker ``` 2. Start the Starter ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.getresultsasync.Starter ``` ================================================ FILE: core/src/main/java/io/temporal/samples/getresultsasync/Starter.java ================================================ package io.temporal.samples.getresultsasync; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.client.WorkflowStub; import java.util.concurrent.TimeUnit; public class Starter { /** * Show the use and difference between getResult and getResultAsync for waiting on workflow * results. */ @SuppressWarnings("FutureReturnValueIgnored") public static void main(String[] args) { MyWorkflow workflowStub1 = Worker.client.newWorkflowStub( MyWorkflow.class, WorkflowOptions.newBuilder().setTaskQueue(Worker.TASK_QUEUE_NAME).build()); MyWorkflow workflowStub2 = Worker.client.newWorkflowStub( MyWorkflow.class, WorkflowOptions.newBuilder().setTaskQueue(Worker.TASK_QUEUE_NAME).build()); // Start workflow async (not blocking thread) WorkflowClient.start(workflowStub1::justSleep, 3); WorkflowStub untypedStub1 = WorkflowStub.fromTyped(workflowStub1); // Get the results, waiting for workflow to complete String result1 = untypedStub1.getResult(String.class); // blocking call, waiting to complete System.out.println("Result1: " + result1); // Start the workflow again (async) WorkflowClient.start(workflowStub2::justSleep, 5); WorkflowStub untypedStub2 = WorkflowStub.fromTyped(workflowStub2); // getResultAsync returns a CompletableFuture // It is not a blocking call like getResult(...) untypedStub2 .getResultAsync(String.class) .thenApply( result2 -> { System.out.println("Result2: " + result2); return result2; }); System.out.println("Waiting on result2..."); // Our workflow sleeps for 5 seconds (async) // Here we block the thread (Thread.sleep) for 7 (2 more than the workflow exec time) // To show that getResultsAsync completion happens during this time (async) sleep(7); System.out.println("Done waiting on result2..."); System.exit(0); } private static void sleep(int seconds) { try { Thread.sleep(TimeUnit.SECONDS.toMillis(seconds)); } catch (InterruptedException e) { System.out.println("Exception: " + e.getMessage()); System.exit(0); } } } ================================================ FILE: core/src/main/java/io/temporal/samples/getresultsasync/Worker.java ================================================ package io.temporal.samples.getresultsasync; import io.temporal.client.WorkflowClient; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.WorkerFactory; import java.io.IOException; public class Worker { public static final WorkflowServiceStubs service; public static final WorkflowClient client; public static final WorkerFactory factory; static { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); factory = WorkerFactory.newInstance(client); } public static final String TASK_QUEUE_NAME = "asyncstartqueue"; public static void main(String[] args) { io.temporal.worker.Worker worker = factory.newWorker(TASK_QUEUE_NAME); worker.registerWorkflowImplementationTypes(MyWorkflowImpl.class); factory.start(); } } ================================================ FILE: core/src/main/java/io/temporal/samples/hello/HelloAccumulator.java ================================================ package io.temporal.samples.hello; import io.temporal.activity.ActivityInterface; import io.temporal.activity.ActivityOptions; import io.temporal.api.workflow.v1.WorkflowExecutionInfo; import io.temporal.api.workflowservice.v1.DescribeWorkflowExecutionRequest; import io.temporal.api.workflowservice.v1.DescribeWorkflowExecutionResponse; import io.temporal.client.BatchRequest; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowFailedException; import io.temporal.client.WorkflowNotFoundException; import io.temporal.client.WorkflowOptions; import io.temporal.client.WorkflowStub; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import io.temporal.workflow.SignalMethod; import io.temporal.workflow.Workflow; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; import java.io.IOException; import java.io.Serializable; import java.time.Duration; import java.util.ArrayDeque; import java.util.Deque; import java.util.HashSet; import java.util.List; import java.util.Optional; import java.util.Random; import java.util.Set; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /* * Sample Temporal Workflow Definition that accumulates events. * This sample implements the Accumulator Pattern: collect many meaningful * things that need to be collected and worked on together, such as * all payments for an account, or all account updates by account. * * This sample models robots being created throughout the time period, * groups them by what color they are, and greets all the robots * of a color at the end. * * A new workflow is created per grouping. Workflows continue as new as needed. * A sample activity at the end is given, and you could add an activity to * process individual events in the processGreeting() method. */ public class HelloAccumulator { // set a time to wait for another signal to come in, e.g. // Duration.ofDays(30); static final Duration MAX_AWAIT_TIME = Duration.ofMinutes(1); static final String TASK_QUEUE = "HelloAccumulatorTaskQueue"; static final String WORKFLOW_ID_PREFIX = "HelloAccumulatorWorkflow"; public static class Greeting implements Serializable { String greetingText; String bucket; String greetingKey; public String getGreetingText() { return greetingText; } public void setGreetingText(String greetingText) { this.greetingText = greetingText; } public String getBucket() { return bucket; } public void setBucket(String bucket) { this.bucket = bucket; } public String getGreetingKey() { return greetingKey; } public void setGreetingKey(String greetingKey) { this.greetingKey = greetingKey; } public Greeting(String greetingText, String bucket, String greetingKey) { this.greetingText = greetingText; this.bucket = bucket; this.greetingKey = greetingKey; } public Greeting() {} @Override public String toString() { return "Greeting [greetingText=" + greetingText + ", bucket=" + bucket + ", greetingKey=" + greetingKey + "]"; } } /** * The Workflow Definition's Interface must contain one method annotated with @WorkflowMethod. * *

Workflow Definitions should not contain any heavyweight computations, non-deterministic * code, network calls, database operations, etc. Those things should be handled by the * Activities. * * @see io.temporal.workflow.WorkflowInterface * @see io.temporal.workflow.WorkflowMethod */ @WorkflowInterface public interface AccumulatorWorkflow { /** * This is the method that is executed when the Workflow Execution is started. The Workflow * Execution completes when this method finishes execution. */ @WorkflowMethod String accumulateGreetings( String bucketKey, Deque greetings, Set allGreetingsSet); // Define the workflow sendGreeting signal method. This method is executed when // the workflow receives a greeting signal. @SignalMethod void sendGreeting(Greeting greeting); // Define the workflow exit signal method. This method is executed when the // workflow receives an exit signal. @SignalMethod void exit(); } /** * This is the Activity Definition's Interface. Activities are building blocks of any Temporal * Workflow and contain any business logic that could perform long running computation, network * calls, etc. * *

Annotating Activity Definition methods with @ActivityMethod is optional. * * @see io.temporal.activity.ActivityInterface * @see io.temporal.activity.ActivityMethod */ @ActivityInterface public interface GreetingActivities { String composeGreeting(Deque greetings); } /** Simple activity implementation. */ static class GreetingActivitiesImpl implements GreetingActivities { // here is where we process all of the signals together @Override public String composeGreeting(Deque greetings) { List greetingList = greetings.stream().map(u -> u.greetingText).collect(Collectors.toList()); return "Hello (" + greetingList.size() + ") robots: " + greetingList + "!"; } } // Main workflow method public static class AccumulatorWorkflowImpl implements AccumulatorWorkflow { private final GreetingActivities activities = Workflow.newActivityStub( GreetingActivities.class, ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(2)).build()); private static final Logger logger = LoggerFactory.getLogger(AccumulatorWorkflowImpl.class); String bucketKey; ArrayDeque greetings; HashSet allGreetingsSet; boolean exitRequested = false; ArrayDeque unprocessedGreetings = new ArrayDeque(); @Override public String accumulateGreetings( String bucketKeyInput, Deque greetingsInput, Set allGreetingsSetInput) { bucketKey = bucketKeyInput; greetings = new ArrayDeque(); allGreetingsSet = new HashSet(); greetings.addAll(greetingsInput); allGreetingsSet.addAll(allGreetingsSetInput); // If you want to wait for a fixed amount of time instead of a time after a // message // as this does now, you might want to check out // ../../updatabletimer // Main Workflow Loop: // - wait for signals to come in // - every time a signal comes in, wait again for MAX_AWAIT_TIME // - if time runs out, and there are no messages, process them all and exit // - if exit signal is received, process any remaining signals and exit do { boolean timedout = !Workflow.await(MAX_AWAIT_TIME, () -> !unprocessedGreetings.isEmpty() || exitRequested); while (!unprocessedGreetings.isEmpty()) { processGreeting(unprocessedGreetings.removeFirst()); } if (exitRequested || timedout) { String greetEveryone = processGreetings(greetings); if (unprocessedGreetings.isEmpty()) { logger.info("Greeting queue is still empty"); return greetEveryone; } else { // you can get here if you send a signal after an exit, causing rollback just // after the // last processed activity logger.info("Greeting queue not empty, looping"); } } } while (!unprocessedGreetings.isEmpty() || !Workflow.getInfo().isContinueAsNewSuggested()); logger.info("starting continue as new processing"); // Create a workflow stub that will be used to continue this workflow as a new AccumulatorWorkflow continueAsNew = Workflow.newContinueAsNewStub(AccumulatorWorkflow.class); // Request that the new run will be invoked by the Temporal system: continueAsNew.accumulateGreetings(bucketKey, greetings, allGreetingsSet); // this could be improved in the future with the are_handlers_finished API. For // now if a signal comes in // after this, it will fail the workflow task and retry handling the new // signal(s) return "continued as new; results passed to next run"; } // Here is where we can process individual signals as they come in. // It's ok to call activities here. // This also validates an individual greeting: // - check for duplicates // - check for correct bucket public void processGreeting(Greeting greeting) { logger.info("processing greeting-" + greeting); if (greeting == null) { logger.warn("Greeting is null:" + greeting); return; } // this just ignores incorrect buckets - you can use workflowupdate to validate // and reject // bad bucket requests if needed if (!greeting.bucket.equals(bucketKey)) { logger.warn("wrong bucket, something is wrong with your signal processing: " + greeting); return; } if (!allGreetingsSet.add(greeting.greetingKey)) { logger.info("Duplicate signal event: " + greeting.greetingKey); return; } // add in any desired event processing activity here greetings.add(greeting); } private String processGreetings(Deque greetings) { logger.info("Composing greetings for: " + greetings); return activities.composeGreeting(greetings); } // Signal method // Keep it simple, these should be fast and not call activities @Override public void sendGreeting(Greeting greeting) { // signals can be the first workflow code that runs, make sure we have // an ArrayDeque to write to if (unprocessedGreetings == null) { unprocessedGreetings = new ArrayDeque(); } logger.info("received greeting-" + greeting); unprocessedGreetings.add(greeting); } @Override public void exit() { logger.info("exit signal received"); exitRequested = true; } } /** * With the Workflow and Activities defined, we can now start execution. The main method starts * the worker and then the workflow. */ public static void main(String[] args) throws Exception { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); client.getWorkflowServiceStubs().healthCheck(); /* * Define the workflow factory. It is used to create workflow workers for a * specific task queue. */ WorkerFactory factory = WorkerFactory.newInstance(client); /* * Define the workflow worker. Workflow workers listen to a defined task queue * and process * workflows and activities. */ Worker worker = factory.newWorker(TASK_QUEUE); /* * Register the workflow implementation with the worker. * Workflow implementations must be known to the worker at runtime in * order to dispatch workflow tasks. */ worker.registerWorkflowImplementationTypes(AccumulatorWorkflowImpl.class); /* * Register our Activity Types with the Worker. Since Activities are stateless * and thread-safe, * the Activity Type is a shared instance. */ worker.registerActivitiesImplementations(new GreetingActivitiesImpl()); /* * Start all the workers registered for a specific task queue. * The started workers then start polling for workflows and activities. */ factory.start(); System.out.println("Worker started for task queue: " + TASK_QUEUE); // setup which tests to run // by default it will run an accumulation with a few (20) signals // to a set of 4 buckets with Signal To Start boolean testContinueAsNew = false; boolean testSignalEdgeCases = true; // configure signal edge cases to test boolean testSignalAfterWorkflowExit = true; boolean testSignalAfterExitSignal = !testSignalAfterWorkflowExit; boolean testDuplicate = true; boolean testIgnoreBadBucket = true; // setup to send signals String bucket = "blue"; String workflowId = WORKFLOW_ID_PREFIX + "-" + bucket; ArrayDeque greetingList = new ArrayDeque(); HashSet allGreetingsSet = new HashSet(); String greetingKey = "key-"; String greetingText = "Robby Robot"; Greeting starterGreeting = new Greeting(greetingText, bucket, greetingKey); final String[] buckets = {"red", "blue", "green", "yellow"}; final String[] names = {"Genghis Khan", "Missy", "Bill", "Ted", "Rufus", "Abe"}; // Create the workflow options WorkflowOptions workflowOptions = WorkflowOptions.newBuilder().setTaskQueue(TASK_QUEUE).setWorkflowId(workflowId).build(); AccumulatorWorkflow workflow = client.newWorkflowStub(AccumulatorWorkflow.class, workflowOptions); // send many signals to start several workflows int max_signals = 20; if (testContinueAsNew) max_signals = 10000; for (int i = 0; i < max_signals; i++) { Random randomBucket = new Random(); int bucketIndex = randomBucket.nextInt(buckets.length); bucket = buckets[bucketIndex]; starterGreeting.setBucket(bucket); Thread.sleep(20); // simulate some delay workflowId = WORKFLOW_ID_PREFIX + "-" + bucket; Random randomName = new Random(); int nameIndex = randomName.nextInt(names.length); starterGreeting.setGreetingText(names[nameIndex] + " Robot"); workflowOptions = WorkflowOptions.newBuilder().setTaskQueue(TASK_QUEUE).setWorkflowId(workflowId).build(); // Create the workflow client stub. It is used to start the workflow execution. workflow = client.newWorkflowStub(AccumulatorWorkflow.class, workflowOptions); BatchRequest request = client.newSignalWithStartRequest(); starterGreeting.greetingKey = greetingKey + i; request.add(workflow::accumulateGreetings, bucket, greetingList, allGreetingsSet); request.add(workflow::sendGreeting, starterGreeting); client.signalWithStart(request); } // Demonstrate we still can connect to WF and get result using untyped: if (max_signals > 0) { WorkflowStub untyped = WorkflowStub.fromTyped(workflow); // wait for it to finish try { String greeting = untyped.getResult(String.class); printWorkflowStatus(client, workflowId); System.out.println("Greeting: " + greeting); } catch (WorkflowFailedException e) { System.out.println("Workflow failed: " + e.getCause().getMessage()); printWorkflowStatus(client, workflowId); } } if (!testSignalEdgeCases) { System.exit(0); // skip other demonstrations below } // set workflow parameters bucket = "purple"; greetingList = new ArrayDeque(); allGreetingsSet = new HashSet(); workflowId = WORKFLOW_ID_PREFIX + "-" + bucket; workflowOptions = WorkflowOptions.newBuilder().setTaskQueue(TASK_QUEUE).setWorkflowId(workflowId).build(); starterGreeting = new Greeting("Suzy Robot", bucket, "11235813"); // Create the workflow client stub. It is used to start the workflow execution. AccumulatorWorkflow workflowSync = client.newWorkflowStub(AccumulatorWorkflow.class, workflowOptions); // Start workflow asynchronously and call its getGreeting workflow method WorkflowClient.start(workflowSync::accumulateGreetings, bucket, greetingList, allGreetingsSet); // After start for accumulateGreetings returns, the workflow is guaranteed to be // started, so we can send a signal to it using the workflow stub. // This workflow keeps receiving signals until exit is called or the timer // finishes with no // signals // When the workflow is started the accumulateGreetings will block for the // previously defined conditions // Send the first workflow signal workflowSync.sendGreeting(starterGreeting); // Test sending an exit, waiting for workflow exit, then sending a signal. // This will trigger a WorkflowNotFoundException if using the same workflow // handle if (testSignalAfterWorkflowExit) { workflowSync.exit(); String greetingsAfterExit = workflowSync.accumulateGreetings(bucket, greetingList, allGreetingsSet); System.out.println(greetingsAfterExit); } // Test sending an exit, not waiting for workflow to exit, then sending a signal // this demonstrates Temporal history rollback // see https://community.temporal.io/t/continueasnew-signals/1008/7 if (testSignalAfterExitSignal) { workflowSync.exit(); } // Test sending more signals after workflow exit try { // send a second workflow signal Greeting janeGreeting = new Greeting("Jane Robot", bucket, "112358132134"); workflowSync.sendGreeting(janeGreeting); if (testIgnoreBadBucket) { // send a third signal with an incorrect bucket - this will be ignored // can use workflow update to validate and reject a request if needed workflowSync.sendGreeting(new Greeting("Sally Robot", "taupe", "112358132134")); } if (testDuplicate) { // intentionally send a duplicate signal workflowSync.sendGreeting(janeGreeting); } if (!testSignalAfterWorkflowExit) { // wait for results if we haven't waited for them yet String greetingsAfterExit = workflowSync.accumulateGreetings(bucket, greetingList, allGreetingsSet); System.out.println(greetingsAfterExit); } } catch (WorkflowNotFoundException e) { System.out.println("Workflow not found - this is intentional: " + e.getCause().getMessage()); printWorkflowStatus(client, workflowId); } try { /* * Here we create a new workflow stub using the same workflow id. * We do this to demonstrate that to send a signal to an already running * workflow you only need to know its workflow id. */ AccumulatorWorkflow workflowById = client.newWorkflowStub(AccumulatorWorkflow.class, workflowId); Greeting laterGreeting = new Greeting("XVX Robot", bucket, "1123581321"); // Send the second signal to our workflow workflowById.sendGreeting(laterGreeting); // Now let's send our exit signal to the workflow workflowById.exit(); /* * We now call our accumulateGreetings workflow method synchronously after our * workflow has started. * This reconnects our workflowById workflow stub to the existing workflow and * blocks until a result is available. Note that this behavior assumes that * WorkflowOptions * are not configured with WorkflowIdReusePolicy.AllowDuplicate. If they were, * this call would fail * with the WorkflowExecutionAlreadyStartedException exception. * You can use the policy to force workflows for a new time period, e.g. a * collection day, to have a new workflow ID. */ String greetings = workflowById.accumulateGreetings(bucket, greetingList, allGreetingsSet); // Print our results for greetings which were sent by signals System.out.println(greetings); } catch (WorkflowNotFoundException e) { System.out.println("Workflow not found - this is intentional: " + e.getCause().getMessage()); printWorkflowStatus(client, workflowId); } /* * Here we try to send the signals as start to demonstrate that after a workflow * exited * and signals failed to send * we can send signals to a new workflow */ if (testSignalAfterWorkflowExit) { greetingList = new ArrayDeque(); allGreetingsSet = new HashSet(); workflowId = WORKFLOW_ID_PREFIX + "-" + bucket; Greeting laterGreeting = new Greeting("Final Robot", bucket, "1123"); // Send the second signal to our workflow workflowOptions = WorkflowOptions.newBuilder().setTaskQueue(TASK_QUEUE).setWorkflowId(workflowId).build(); // Create the workflow client stub. It is used to start the workflow execution. workflow = client.newWorkflowStub(AccumulatorWorkflow.class, workflowOptions); BatchRequest request = client.newSignalWithStartRequest(); request.add(workflow::accumulateGreetings, bucket, greetingList, allGreetingsSet); request.add(workflow::sendGreeting, laterGreeting); client.signalWithStart(request); printWorkflowStatus(client, workflowId); String greetingsAfterExit = workflow.accumulateGreetings(bucket, greetingList, allGreetingsSet); // Print our results for greetings which were sent by signals System.out.println(greetingsAfterExit); printWorkflowStatus(client, workflowId); while (getWorkflowStatus(client, workflowId).equals("WORKFLOW_EXECUTION_STATUS_RUNNING")) { System.out.println("Workflow still running "); Thread.sleep(1000); } } System.exit(0); } private static void printWorkflowStatus(WorkflowClient client, String workflowId) { WorkflowStub existingUntyped = client.newUntypedWorkflowStub(workflowId, Optional.empty(), Optional.empty()); DescribeWorkflowExecutionRequest describeWorkflowExecutionRequest = DescribeWorkflowExecutionRequest.newBuilder() .setNamespace(client.getOptions().getNamespace()) .setExecution(existingUntyped.getExecution()) .build(); DescribeWorkflowExecutionResponse resp = client .getWorkflowServiceStubs() .blockingStub() .describeWorkflowExecution(describeWorkflowExecutionRequest); System.out.println( "**** PARENT: " + resp.getWorkflowExecutionInfo().getParentExecution().getWorkflowId()); WorkflowExecutionInfo workflowExecutionInfo = resp.getWorkflowExecutionInfo(); System.out.println("Workflow Status: " + workflowExecutionInfo.getStatus().toString()); } private static String getWorkflowStatus(WorkflowClient client, String workflowId) { WorkflowStub existingUntyped = client.newUntypedWorkflowStub(workflowId, Optional.empty(), Optional.empty()); DescribeWorkflowExecutionRequest describeWorkflowExecutionRequest = DescribeWorkflowExecutionRequest.newBuilder() .setNamespace(client.getOptions().getNamespace()) .setExecution(existingUntyped.getExecution()) .build(); DescribeWorkflowExecutionResponse resp = client .getWorkflowServiceStubs() .blockingStub() .describeWorkflowExecution(describeWorkflowExecutionRequest); System.out.println( "**** PARENT: " + resp.getWorkflowExecutionInfo().getParentExecution().getWorkflowId()); WorkflowExecutionInfo workflowExecutionInfo = resp.getWorkflowExecutionInfo(); return workflowExecutionInfo.getStatus().toString(); } } ================================================ FILE: core/src/main/java/io/temporal/samples/hello/HelloActivity.java ================================================ package io.temporal.samples.hello; import io.temporal.activity.ActivityInterface; import io.temporal.activity.ActivityMethod; import io.temporal.activity.ActivityOptions; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import io.temporal.workflow.Workflow; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; import java.io.IOException; import java.time.Duration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** Sample Temporal Workflow Definition that executes a single Activity. */ public class HelloActivity { // Define the task queue name static final String TASK_QUEUE = "HelloActivityTaskQueue"; // Define our workflow unique id static final String WORKFLOW_ID = "HelloActivityWorkflow"; /** * The Workflow Definition's Interface must contain one method annotated with @WorkflowMethod. * *

Workflow Definitions should not contain any heavyweight computations, non-deterministic * code, network calls, database operations, etc. Those things should be handled by the * Activities. * * @see io.temporal.workflow.WorkflowInterface * @see io.temporal.workflow.WorkflowMethod */ @WorkflowInterface public interface GreetingWorkflow { /** * This is the method that is executed when the Workflow Execution is started. The Workflow * Execution completes when this method finishes execution. */ @WorkflowMethod String getGreeting(String name); } /** * This is the Activity Definition's Interface. Activities are building blocks of any Temporal * Workflow and contain any business logic that could perform long running computation, network * calls, etc. * *

Annotating Activity Definition methods with @ActivityMethod is optional. * * @see io.temporal.activity.ActivityInterface * @see io.temporal.activity.ActivityMethod */ @ActivityInterface public interface GreetingActivities { // Define your activity method which can be called during workflow execution @ActivityMethod(name = "greet") String composeGreeting(String greeting, String name); } // Define the workflow implementation which implements our getGreeting workflow method. public static class GreetingWorkflowImpl implements GreetingWorkflow { /** * Define the GreetingActivities stub. Activity stubs are proxies for activity invocations that * are executed outside of the workflow thread on the activity worker, that can be on a * different host. Temporal is going to dispatch the activity results back to the workflow and * unblock the stub as soon as activity is completed on the activity worker. * *

In the {@link ActivityOptions} definition the "setStartToCloseTimeout" option sets the * overall timeout that our workflow is willing to wait for activity to complete. For this * example it is set to 2 seconds. */ private final GreetingActivities activities = Workflow.newActivityStub( GreetingActivities.class, ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(2)).build()); @Override public String getGreeting(String name) { // This is a blocking call that returns only after the activity has completed. return activities.composeGreeting("Hello", name); } } /** Simple activity implementation, that concatenates two strings. */ public static class GreetingActivitiesImpl implements GreetingActivities { private static final Logger log = LoggerFactory.getLogger(GreetingActivitiesImpl.class); @Override public String composeGreeting(String greeting, String name) { log.info("Composing greeting..."); return greeting + " " + name + "!"; } } /** * With our Workflow and Activities defined, we can now start execution. The main method starts * the worker and then the workflow. */ public static void main(String[] args) { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } // Get a Workflow service stub. WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); /* * Get a Workflow service client which can be used to start, Signal, and Query Workflow Executions. */ WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); /* * Define the workflow factory. It is used to create workflow workers for a specific task queue. */ WorkerFactory factory = WorkerFactory.newInstance(client); /* * Define the workflow worker. Workflow workers listen to a defined task queue and process * workflows and activities. */ Worker worker = factory.newWorker(TASK_QUEUE); /* * Register our workflow implementation with the worker. * Workflow implementations must be known to the worker at runtime in * order to dispatch workflow tasks. */ worker.registerWorkflowImplementationTypes(GreetingWorkflowImpl.class); /* * Register our Activity Types with the Worker. Since Activities are stateless and thread-safe, * the Activity Type is a shared instance. */ worker.registerActivitiesImplementations(new GreetingActivitiesImpl()); /* * Start all the workers registered for a specific task queue. * The started workers then start polling for workflows and activities. */ factory.start(); // Create the workflow client stub. It is used to start our workflow execution. GreetingWorkflow workflow = client.newWorkflowStub( GreetingWorkflow.class, WorkflowOptions.newBuilder() .setWorkflowId(WORKFLOW_ID) .setTaskQueue(TASK_QUEUE) .build()); /* * Execute our workflow and wait for it to complete. The call to our getGreeting method is * synchronous. * * See {@link io.temporal.samples.hello.HelloSignal} for an example of starting workflow * without waiting synchronously for its result. */ String greeting = workflow.getGreeting("World"); // Display workflow execution results System.out.println(greeting); System.exit(0); } } ================================================ FILE: core/src/main/java/io/temporal/samples/hello/HelloActivityExclusiveChoice.java ================================================ package io.temporal.samples.hello; import io.temporal.activity.ActivityInterface; import io.temporal.activity.ActivityOptions; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import io.temporal.workflow.Workflow; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; import java.io.IOException; import java.time.Duration; import java.util.HashMap; import java.util.Map; /** * Sample Temporal Workflow Definition demonstrating how to execute an Activity based on dynamic * input. */ public class HelloActivityExclusiveChoice { // Define the task queue name static final String TASK_QUEUE = "HelloActivityChoiceTaskQueue"; // Define our workflow unique id static final String WORKFLOW_ID = "HelloActivityChoiceWorkflow"; // Different fruits you can order enum Fruits { APPLE, BANANA, CHERRY, ORANGE } // Our example shopping list for different fruits public static class ShoppingList { private Map list = new HashMap<>(); public void addFruitOrder(Fruits fruit, int amount) { list.put(fruit, amount); } public Map getList() { return list; } } /** * Define the Workflow Interface. It must contain at least one method annotated * with @WorkflowMethod * * @see io.temporal.workflow.WorkflowInterface * @see io.temporal.workflow.WorkflowMethod */ @WorkflowInterface public interface PurchaseFruitsWorkflow { /** * Define the workflow method. This method is executed when the workflow is started. The * workflow completes when the workflow method finishes execution. */ @WorkflowMethod StringBuilder orderFruit(ShoppingList list); } /** * Define the Activity Interface. Workflow methods can call activities during execution. * Annotating activity methods with @ActivityMethod is optional * * @see io.temporal.activity.ActivityInterface * @see io.temporal.activity.ActivityMethod */ @ActivityInterface public interface OrderFruitsActivities { // Define your activity methods which can be called during workflow execution String orderApples(int amount); String orderBananas(int amount); String orderCherries(int amount); String orderOranges(int amount); } // Define the workflow implementation. It implements our orderFruit workflow method public static class PurchaseFruitsWorkflowImpl implements PurchaseFruitsWorkflow { /* * Define the OrderActivities stub. Activity stubs implements activity interfaces and proxy * calls to it to Temporal activity invocations. Since Temporal activities are reentrant, a * single activity stub can be used for multiple activity invocations. * *

In the {@link ActivityOptions} definition the "setStartToCloseTimeout" option sets the * maximum time of a single Activity execution attempt. For this example it is set to 2 seconds. */ private final OrderFruitsActivities activities = Workflow.newActivityStub( OrderFruitsActivities.class, ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(2)).build()); @Override public StringBuilder orderFruit(ShoppingList list) { StringBuilder shoppingResults = new StringBuilder(); // Go through each element of our shopping list list.getList() .forEach( (fruit, amount) -> { // You can use a basic switch to call an activity method based on the workflow input switch (fruit) { case APPLE: shoppingResults.append(activities.orderApples(amount)); break; case BANANA: shoppingResults.append(activities.orderBananas(amount)); break; case CHERRY: shoppingResults.append(activities.orderCherries(amount)); break; case ORANGE: shoppingResults.append(activities.orderOranges(amount)); break; default: shoppingResults.append("Unable to order fruit: ").append(fruit); break; } }); return shoppingResults; } } /** * Implementation of our workflow activity interface. It overwrites our defined activity methods. */ static class OrderFruitsActivitiesImpl implements OrderFruitsActivities { @Override public String orderApples(int amount) { return "Ordered " + amount + " Apples..."; } @Override public String orderBananas(int amount) { return "Ordered " + amount + " Bananas..."; } @Override public String orderCherries(int amount) { return "Ordered " + amount + " Cherries..."; } @Override public String orderOranges(int amount) { return "Ordered " + amount + " Oranges..."; } } /** * With our Workflow and Activities defined, we can now start execution. The main method is our * workflow starter. */ public static void main(String[] args) { /* * Define the workflow service. It is a gRPC stubs wrapper which talks to the docker instance of * our locally running Temporal service. */ // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); /* * Get a Workflow service client which can be used to start, Signal, and Query Workflow Executions. */ WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); /* * Define the workflow factory. It is used to create workflow workers for a specific task queue. */ WorkerFactory factory = WorkerFactory.newInstance(client); /* * Define the workflow worker. Workflow workers listen to a defined task queue and process * workflows and activities. */ Worker worker = factory.newWorker(TASK_QUEUE); /* * Register our workflow implementation with the worker. Since workflows are stateful in nature, * we need to register our workflow type. */ worker.registerWorkflowImplementationTypes(PurchaseFruitsWorkflowImpl.class); /* * Register our Activity Types with the Worker. Since Activities are stateless and thread-safe, * the Activity Type is a shared instance. */ worker.registerActivitiesImplementations(new OrderFruitsActivitiesImpl()); // Start all the workers registered for a specific task queue. factory.start(); // Create our workflow client stub. It is used to start our workflow execution. PurchaseFruitsWorkflow workflow = client.newWorkflowStub( PurchaseFruitsWorkflow.class, WorkflowOptions.newBuilder() .setWorkflowId(WORKFLOW_ID) .setTaskQueue(TASK_QUEUE) .build()); // Let's build our example shopping list ShoppingList shoppingList = new ShoppingList(); shoppingList.addFruitOrder(Fruits.APPLE, 8); shoppingList.addFruitOrder(Fruits.BANANA, 5); shoppingList.addFruitOrder(Fruits.CHERRY, 1); shoppingList.addFruitOrder(Fruits.ORANGE, 4); // Execute our workflow method StringBuilder orderResults = workflow.orderFruit(shoppingList); System.out.println("Order results: " + orderResults); System.exit(0); } } ================================================ FILE: core/src/main/java/io/temporal/samples/hello/HelloActivityRetry.java ================================================ package io.temporal.samples.hello; import io.temporal.activity.ActivityInterface; import io.temporal.activity.ActivityOptions; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.common.RetryOptions; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import io.temporal.workflow.Workflow; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; import java.io.IOException; import java.time.Duration; /** Sample Temporal workflow that demonstrates workflow activity retries. */ public class HelloActivityRetry { // Define the task queue name static final String TASK_QUEUE = "HelloActivityWithRetriesTaskQueue"; // Define our workflow unique id static final String WORKFLOW_ID = "HelloActivityWithRetriesWorkflow"; /** * The Workflow Definition's Interface must contain one method annotated with @WorkflowMethod. * *

Workflow Definitions should not contain any heavyweight computations, non-deterministic * code, network calls, database operations, etc. Those things should be handled by the * Activities. * * @see io.temporal.workflow.WorkflowInterface * @see io.temporal.workflow.WorkflowMethod */ @WorkflowInterface public interface GreetingWorkflow { /** * This is the method that is executed when the Workflow Execution is started. The Workflow * Execution completes when this method finishes execution. */ @WorkflowMethod String getGreeting(String name); } /** * This is the Activity Definition's Interface. Activities are building blocks of any Temporal * Workflow and contain any business logic that could perform long running computation, network * calls, etc. * *

Annotating Activity Definition methods with @ActivityMethod is optional. * * @see io.temporal.activity.ActivityInterface * @see io.temporal.activity.ActivityMethod */ @ActivityInterface public interface GreetingActivities { /** Define your activity method which can be called during workflow execution */ String composeGreeting(String greeting, String name); } // Define the workflow implementation which implements our getGreeting workflow method. public static class GreetingWorkflowImpl implements GreetingWorkflow { /** * Define the GreetingActivities stub. Activity stubs are proxies for activity invocations that * are executed outside of the workflow thread on the activity worker, that can be on a * different host. Temporal is going to dispatch the activity results back to the workflow and * unblock the stub as soon as activity is completed on the activity worker. * *

In the {@link ActivityOptions} definition the "setStartToCloseTimeout" option sets the * maximum time of a single Activity execution attempt. For this example it is set to 10 * seconds. * *

In the {@link ActivityOptions} definition the "setInitialInterval" option sets the * interval of the first retry. It is set to 1 second. The "setDoNotRetry" option is a list of * application failures for which retries should not be performed. * *

By default the maximum number of retry attempts is set to "unlimited" however you can * change it by adding the "setMaximumAttempts" option to the retry options. */ private final GreetingActivities activities = Workflow.newActivityStub( GreetingActivities.class, ActivityOptions.newBuilder() .setStartToCloseTimeout(Duration.ofSeconds(10)) .setRetryOptions( RetryOptions.newBuilder() .setInitialInterval(Duration.ofSeconds(1)) .setDoNotRetry(IllegalArgumentException.class.getName()) .build()) .build()); @Override public String getGreeting(String name) { // This is a blocking call that returns only after activity is completed. return activities.composeGreeting("Hello", name); } } /** * Implementation of our workflow activity interface. It overwrites our defined composeGreeting * activity method. */ static class GreetingActivitiesImpl implements GreetingActivities { private int callCount; private long lastInvocationTime; /** * Our activity implementation simulates a failure 3 times. Given our previously set * RetryOptions, our workflow is going to retry our activity execution. */ @Override public synchronized String composeGreeting(String greeting, String name) { if (lastInvocationTime != 0) { long timeSinceLastInvocation = System.currentTimeMillis() - lastInvocationTime; System.out.print(timeSinceLastInvocation + " milliseconds since last invocation. "); } lastInvocationTime = System.currentTimeMillis(); if (++callCount < 4) { System.out.println("composeGreeting activity is going to fail"); /* * We throw IllegalStateException here. It is not in the list of "do not retry" exceptions * set in our RetryOptions, so a workflow retry is going to be issued */ throw new IllegalStateException("not yet"); } // after 3 unsuccessful retries we finally can complete our activity execution System.out.println("composeGreeting activity is going to complete"); return greeting + " " + name + "!"; } } /** * With our Workflow and Activities defined, we can now start execution. The main method starts * the worker and then the workflow. */ public static void main(String[] args) { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); /* * Define the workflow factory. It is used to create workflow workers for a specific task queue. */ WorkerFactory factory = WorkerFactory.newInstance(client); /* * Define the workflow worker. Workflow workers listen to a defined task queue and process * workflows and activities. */ Worker worker = factory.newWorker(TASK_QUEUE); /* * Register our workflow implementation with the worker. * Workflow implementations must be known to the worker at runtime in * order to dispatch workflow tasks. */ worker.registerWorkflowImplementationTypes(GreetingWorkflowImpl.class); /* * Register our Activity Types with the Worker. Since Activities are stateless and thread-safe, * the Activity Type is a shared instance. */ worker.registerActivitiesImplementations(new GreetingActivitiesImpl()); /* * Start all the workers registered for a specific task queue. * The started workers then start polling for workflows and activities. */ factory.start(); // Set our workflow options WorkflowOptions workflowOptions = WorkflowOptions.newBuilder().setWorkflowId(WORKFLOW_ID).setTaskQueue(TASK_QUEUE).build(); // Create the workflow client stub. It is used to start our workflow execution. GreetingWorkflow workflow = client.newWorkflowStub(GreetingWorkflow.class, workflowOptions); /* * Execute our workflow and wait for it to complete. The call to our getGreeting method is * synchronous. * * See {@link io.temporal.samples.hello.HelloSignal} for an example of starting workflow * without waiting synchronously for its result. */ String greeting = workflow.getGreeting("World"); // Display workflow execution results System.out.println(greeting); System.exit(0); } } ================================================ FILE: core/src/main/java/io/temporal/samples/hello/HelloAsync.java ================================================ package io.temporal.samples.hello; import io.temporal.activity.ActivityInterface; import io.temporal.activity.ActivityOptions; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import io.temporal.workflow.Async; import io.temporal.workflow.Promise; import io.temporal.workflow.Workflow; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; import java.io.IOException; import java.time.Duration; /** Sample Temporal Workflow Definition that demonstrates an asynchronous Activity Execution. */ public class HelloAsync { // Define the task queue name static final String TASK_QUEUE = "HelloAsyncActivityTaskQueue"; // Define our workflow unique id static final String WORKFLOW_ID = "HelloAsyncActivityWorkflow"; /** * The Workflow Definition's Interface must contain one method annotated with @WorkflowMethod. * *

Workflow Definitions should not contain any heavyweight computations, non-deterministic * code, network calls, database operations, etc. Those things should be handled by the * Activities. * * @see io.temporal.workflow.WorkflowInterface * @see io.temporal.workflow.WorkflowMethod */ @WorkflowInterface public interface GreetingWorkflow { /** * This is the method that is executed when the Workflow Execution is started. The Workflow * Execution completes when this method finishes execution. */ @WorkflowMethod String getGreeting(String name); } /** * This is the Activity Definition's Interface. Activities are building blocks of any Temporal * Workflow and contain any business logic that could perform long running computation, network * calls, etc. * *

Annotating Activity Definition methods with @ActivityMethod is optional. * * @see io.temporal.activity.ActivityInterface * @see io.temporal.activity.ActivityMethod */ @ActivityInterface public interface GreetingActivities { // Define your activity method which can be called during workflow execution String composeGreeting(String greeting, String name); } // Define the workflow implementation which implements our getGreeting workflow method. public static class GreetingWorkflowImpl implements GreetingWorkflow { /* * Define the GreetingActivities stub. Activity stubs are proxies for activity invocations that * are executed outside of the workflow thread on the activity worker, that can be on a * different host. Temporal is going to dispatch the activity results back to the workflow and * unblock the stub as soon as activity is completed on the activity worker. * *

In the {@link ActivityOptions} definition the "setStartToCloseTimeout" option sets the * maximum time of a single Activity execution attempt. For this example it is set to 10 * seconds. */ private final GreetingActivities activities = Workflow.newActivityStub( GreetingActivities.class, ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(10)).build()); @Override public String getGreeting(String name) { /* * This is our workflow method. We invoke the composeGreeting method two times using * {@link io.temporal.workflow.Async#function(Func)}. * The results of each async activity method invocation returns us a * {@link io.temporal.workflow.Promise} which is similar to a Java {@link java.util.concurrent.Future} */ Promise hello = Async.function(activities::composeGreeting, "Hello", name); Promise bye = Async.function(activities::composeGreeting, "Bye", name); // After calling the two activity methods async, we block until we receive their results return hello.get() + "\n" + bye.get(); } } /** Simple activity implementation, that concatenates two strings. */ static class GreetingActivitiesImpl implements GreetingActivities { @Override public String composeGreeting(String greeting, String name) { return greeting + " " + name + "!"; } } /** * With our Workflow and Activities defined, we can now start execution. The main method starts * the worker and then the workflow. */ public static void main(String[] args) { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } // Get a Workflow service stub. WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); /* * Define the workflow factory. It is used to create workflow workers for a specific task queue. */ WorkerFactory factory = WorkerFactory.newInstance(client); /* * Define the workflow worker. Workflow workers listen to a defined task queue and process * workflows and activities. */ Worker worker = factory.newWorker(TASK_QUEUE); /* * Register our workflow implementation with the worker. * Workflow implementations must be known to the worker at runtime in * order to dispatch workflow tasks. */ worker.registerWorkflowImplementationTypes(GreetingWorkflowImpl.class); /* * Register our Activity Types with the Worker. Since Activities are stateless and thread-safe, * the Activity Type is a shared instance. */ worker.registerActivitiesImplementations(new GreetingActivitiesImpl()); /* * Start all the workers registered for a specific task queue. * The started workers then start polling for workflows and activities. */ factory.start(); // Create the workflow client stub. It is used to start our workflow execution. GreetingWorkflow workflow = client.newWorkflowStub( GreetingWorkflow.class, WorkflowOptions.newBuilder() .setWorkflowId(WORKFLOW_ID) .setTaskQueue(TASK_QUEUE) .build()); // Execute our workflow and wait for it to complete. String greeting = workflow.getGreeting("World"); // Display workflow execution results System.out.println(greeting); System.exit(0); } } ================================================ FILE: core/src/main/java/io/temporal/samples/hello/HelloAsyncActivityCompletion.java ================================================ package io.temporal.samples.hello; import io.temporal.activity.*; import io.temporal.client.ActivityCompletionClient; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import io.temporal.workflow.Workflow; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; import java.io.IOException; import java.time.Duration; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.ForkJoinPool; /** Sample Temporal Workflow Definition that demonstrates asynchronous Activity Execution */ public class HelloAsyncActivityCompletion { // Define the task queue name static final String TASK_QUEUE = "HelloAsyncActivityCompletionTaskQueue"; // Define the workflow unique id static final String WORKFLOW_ID = "HelloAsyncActivityCompletionWorkflow"; /** * The Workflow Definition's Interface must contain one method annotated with @WorkflowMethod. * *

Workflow Definitions should not contain any heavyweight computations, non-deterministic * code, network calls, database operations, etc. Those things should be handled by the * Activities. * * @see io.temporal.workflow.WorkflowInterface * @see io.temporal.workflow.WorkflowMethod */ @WorkflowInterface public interface GreetingWorkflow { /** * This is the method that is executed when the Workflow Execution is started. The Workflow * Execution completes when this method finishes execution. */ @WorkflowMethod String getGreeting(String name); } /** * This is the Activity Definition's Interface. Activities are building blocks of any Temporal * Workflow and contain any business logic that could perform long running computation, network * calls, etc. * *

Annotating Activity Definition methods with @ActivityMethod is optional. * * @see io.temporal.activity.ActivityInterface * @see io.temporal.activity.ActivityMethod */ @ActivityInterface public interface GreetingActivities { /** Define the activity method which can be called during workflow execution */ String composeGreeting(String greeting, String name); } // Define the workflow implementation which implements the getGreeting workflow method. public static class GreetingWorkflowImpl implements GreetingWorkflow { /* * Define the GreetingActivities stub. Activity stubs are proxies for activity invocations that * are executed outside of the workflow thread on the activity worker, that can be on a * different host. Temporal is going to dispatch the activity results back to the workflow and * unblock the stub as soon as activity is completed on the activity worker. * *

In the {@link ActivityOptions} definition the "setStartToCloseTimeout" option sets the * maximum time of a single Activity execution attempt. For this example it is set to 10 * seconds. */ private final GreetingActivities activities = Workflow.newActivityStub( GreetingActivities.class, ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(10)).build()); @Override public String getGreeting(String name) { // This is a blocking call that returns only after the activity has completed. return activities.composeGreeting("Hello", name); } } /** * Implementation of our workflow activity interface. It overwrites the defined composeGreeting * activity method. */ static class GreetingActivitiesImpl implements GreetingActivities { /* * ActivityCompletionClient is used to asynchronously complete activities. In this example we * will use this client alongside with {@link * io.temporal.activity.ActivityExecutionContext#doNotCompleteOnReturn()} which means our * activity method will not complete when it returns, however is expected to be completed * asynchronously using the client. */ private final ActivityCompletionClient completionClient; GreetingActivitiesImpl(ActivityCompletionClient completionClient) { this.completionClient = completionClient; } @Override public String composeGreeting(String greeting, String name) { // Get the activity execution context ActivityExecutionContext context = Activity.getExecutionContext(); // Set a correlation token that can be used to complete the activity asynchronously byte[] taskToken = context.getTaskToken(); /* * For the example we will use a {@link java.util.concurrent.ForkJoinPool} to execute our * activity. In real-life applications this could be any service. The composeGreetingAsync * method is the one that will actually complete workflow action execution. */ ForkJoinPool.commonPool().execute(() -> composeGreetingAsync(taskToken, greeting, name)); context.doNotCompleteOnReturn(); // Since we have set doNotCompleteOnReturn(), the workflow action method return value is // ignored. return "ignored"; } // Method that will complete action execution using the defined ActivityCompletionClient private void composeGreetingAsync(byte[] taskToken, String greeting, String name) { String result = greeting + " " + name + "!"; // Complete our workflow activity using ActivityCompletionClient completionClient.complete(taskToken, result); } } /** * With our Workflow and Activities defined, we can now start execution. The main method starts * the worker and then the workflow. */ public static void main(String[] args) throws ExecutionException, InterruptedException { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } // Get a Workflow service stub. WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); /* * Define the workflow factory. It is used to create workflow workers for a specific task queue. */ WorkerFactory factory = WorkerFactory.newInstance(client); /* * Define the workflow worker. Workflow workers listen to a defined task queue and process * workflows and activities. */ Worker worker = factory.newWorker(TASK_QUEUE); /* * Register our Workflow Types with the Worker. Workflow Types must be known to the Worker at * runtime in order for it to poll for Workflow Tasks. */ worker.registerWorkflowImplementationTypes(GreetingWorkflowImpl.class); /* * Register our Activity Types with the Worker. Since Activities are stateless and thread-safe, * the Activity Type is a shared instance. */ ActivityCompletionClient completionClient = client.newActivityCompletionClient(); worker.registerActivitiesImplementations(new GreetingActivitiesImpl(completionClient)); /* * Start all the Workers registered for a specific Task Queue. The Workers then start polling * for Workflow Tasks and Activity Tasks. */ factory.start(); // Create the workflow client stub. It is used to start our workflow execution. GreetingWorkflow workflow = client.newWorkflowStub( GreetingWorkflow.class, WorkflowOptions.newBuilder() .setWorkflowId(WORKFLOW_ID) .setTaskQueue(TASK_QUEUE) .build()); /* * Here we use {@link io.temporal.client.WorkflowClient} to execute our workflow asynchronously. * It gives us back a {@link java.util.concurrent.CompletableFuture}. We can then call its get * method to block and wait until a result is available. */ CompletableFuture greeting = WorkflowClient.execute(workflow::getGreeting, "World"); // Wait for workflow execution to complete and display its results. System.out.println(greeting.get()); System.exit(0); } } ================================================ FILE: core/src/main/java/io/temporal/samples/hello/HelloAsyncLambda.java ================================================ package io.temporal.samples.hello; import io.temporal.activity.ActivityInterface; import io.temporal.activity.ActivityOptions; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import io.temporal.workflow.Async; import io.temporal.workflow.Promise; import io.temporal.workflow.Workflow; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; import java.io.IOException; import java.time.Duration; /** Sample Temporal Workflow Definition that demonstrates an asynchronous Activity Executions. */ public class HelloAsyncLambda { // Define the task queue name static final String TASK_QUEUE = "HelloAsyncLambdaTaskQueue"; // Define our workflow unique id static final String WORKFLOW_ID = "HelloAsyncLambdaWorkflow"; /** * The Workflow Definition's Interface must contain one method annotated with @WorkflowMethod. * *

Workflow Definitions should not contain any heavyweight computations, non-deterministic * code, network calls, database operations, etc. Those things should be handled by the * Activities. * * @see io.temporal.workflow.WorkflowInterface * @see io.temporal.workflow.WorkflowMethod */ @WorkflowInterface public interface GreetingWorkflow { /** * This is the method that is executed when the Workflow Execution is started. The Workflow * Execution completes when this method finishes execution. */ @WorkflowMethod String getGreeting(String name); } /** * This is the Activity Definition's Interface. Activities are building blocks of any Temporal * Workflow and contain any business logic that could perform long running computation, network * calls, etc. * *

Annotating Activity Definition methods with @ActivityMethod is optional. * * @see io.temporal.activity.ActivityInterface * @see io.temporal.activity.ActivityMethod */ @ActivityInterface public interface GreetingActivities { String getGreeting(); String composeGreeting(String greeting, String name); } // Define the workflow implementation which implements our getGreeting workflow method. public static class GreetingWorkflowImpl implements GreetingWorkflow { /* * Define the GreetingActivities stub. Activity stubs are proxies for activity invocations that * are executed outside of the workflow thread on the activity worker, that can be on a * different host. Temporal is going to dispatch the activity results back to the workflow and * unblock the stub as soon as activity is completed on the activity worker. * *

In the {@link ActivityOptions} definition the "setStartToCloseTimeout" option sets the * maximum time of a single Activity execution attempt. For this example it is set to 10 * seconds. */ private final GreetingActivities activities = Workflow.newActivityStub( GreetingActivities.class, ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(10)).build()); @Override public String getGreeting(String name) { /* * Here we invoke our composeGreeting workflow activity two times asynchronously. For this we * use {@link io.temporal.workflow.Async} which has support for invoking lambdas. Behind the * scenes it allocates a thread to execute each activity method async. */ Promise result1 = Async.function( () -> { String greeting = activities.getGreeting(); return activities.composeGreeting(greeting, name); }); Promise result2 = Async.function( () -> { String greeting = activities.getGreeting(); return activities.composeGreeting(greeting, name); }); // blocking call to wait for our activities to return results return result1.get() + "\n" + result2.get(); } } /** * Implementation of our workflow activity interface. It overwrites our defined getGreeting and * composeGreeting methods. */ static class GreetingActivitiesImpl implements GreetingActivities { @Override public String getGreeting() { return "Hello"; } @Override public String composeGreeting(String greeting, String name) { return greeting + " " + name + "!"; } } /** * With our Workflow and Activities defined, we can now start execution. The main method starts * the worker and then the workflow. */ public static void main(String[] args) { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } // Get a Workflow service stub. WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); /* * Define the workflow factory. It is used to create workflow workers for a specific task queue. */ WorkerFactory factory = WorkerFactory.newInstance(client); /* * Define the workflow worker. Workflow workers listen to a defined task queue and process * workflows and activities. */ Worker worker = factory.newWorker(TASK_QUEUE); /* * Register our workflow implementation with the worker. * Workflow implementations must be known to the worker at runtime in * order to dispatch workflow tasks. */ worker.registerWorkflowImplementationTypes(GreetingWorkflowImpl.class); /* * Register our Activity Types with the Worker. Since Activities are stateless and thread-safe, * the Activity Type is a shared instance. */ worker.registerActivitiesImplementations(new GreetingActivitiesImpl()); /* * Start all the workers registered for a specific task queue. * The started workers then start polling for workflows and activities. */ factory.start(); // Define our workflow options WorkflowOptions workflowOptions = WorkflowOptions.newBuilder().setWorkflowId(WORKFLOW_ID).setTaskQueue(TASK_QUEUE).build(); // Create the workflow client stub. It is used to start our workflow execution. GreetingWorkflow workflow = client.newWorkflowStub(GreetingWorkflow.class, workflowOptions); /* * Execute our workflow and wait for it to complete. The call to our getGreeting method is * synchronous. */ String greeting = workflow.getGreeting("World"); // Display workflow execution results System.out.println(greeting); System.exit(0); } } ================================================ FILE: core/src/main/java/io/temporal/samples/hello/HelloAwait.java ================================================ package io.temporal.samples.hello; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.client.WorkflowStub; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.failure.ApplicationFailure; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import io.temporal.workflow.SignalMethod; import io.temporal.workflow.Workflow; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; import java.io.IOException; import java.time.Duration; /** * Sample Temporal workflow that demonstrates how to use workflow await methods to wait up to a * specified timeout for a condition updated from a signal handler. */ public class HelloAwait { // Define the task queue name static final String TASK_QUEUE = "HelloAwaitTaskQueue"; // Define the workflow unique id static final String WORKFLOW_ID = "HelloAwaitWorkflow"; /** * The Workflow Definition's Interface must contain one method annotated with @WorkflowMethod. * *

Workflow Definitions should not contain any heavyweight computations, non-deterministic * code, network calls, database operations, etc. Those things should be handled by the * Activities. * * @see WorkflowInterface * @see WorkflowMethod */ @WorkflowInterface public interface GreetingWorkflow { /** * This is the method that is executed when the Workflow Execution is started. The Workflow * Execution completes when this method finishes execution. */ @WorkflowMethod String getGreeting(); // Define the workflow waitForName signal method. This method is executed when the workflow // receives a "WaitForName" signal. @SignalMethod void waitForName(String name); } // Define the workflow implementation which implements the getGreetings workflow method. public static class GreetingWorkflowImpl implements GreetingWorkflow { private String name; @Override public String getGreeting() { boolean ok = Workflow.await(Duration.ofSeconds(10), () -> name != null); if (ok) { return "Hello " + name + "!"; } else { // To fail workflow use ApplicationFailure. Any other exception would cause workflow to // stall, not to fail. throw ApplicationFailure.newFailure( "WaitForName signal is not received within 10 seconds.", "signal-timeout"); } } @Override public void waitForName(String name) { this.name = name; } } /** * With the Workflow and Activities defined, we can now start execution. The main method starts * the worker and then the workflow. */ public static void main(String[] args) throws Exception { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } // Get a Workflow service stub. WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); /* * Define the workflow factory. It is used to create workflow workers for a specific task queue. */ WorkerFactory factory = WorkerFactory.newInstance(client); /* * Define the workflow worker. Workflow workers listen to a defined task queue and process * workflows and activities. */ Worker worker = factory.newWorker(TASK_QUEUE); /* * Register the workflow implementation with the worker. * Workflow implementations must be known to the worker at runtime in * order to dispatch workflow tasks. */ worker.registerWorkflowImplementationTypes(GreetingWorkflowImpl.class); /* * Start all the workers registered for a specific task queue. * The started workers then start polling for workflows and activities. */ factory.start(); // Create the workflow options WorkflowOptions workflowOptions = WorkflowOptions.newBuilder().setTaskQueue(TASK_QUEUE).setWorkflowId(WORKFLOW_ID).build(); // Create the workflow client stub. It is used to start the workflow execution. GreetingWorkflow workflow = client.newWorkflowStub(GreetingWorkflow.class, workflowOptions); // Start workflow asynchronously and call its getGreeting workflow method WorkflowClient.start(workflow::getGreeting); // After start for getGreeting returns, the workflow is guaranteed to be started. // Send WaitForName signal. workflow.waitForName("World"); /* * Here we create a new untyped workflow stub using the same workflow id. * The untyped stub is a convenient way to wait for a workflow result. */ WorkflowStub workflowById = client.newUntypedWorkflowStub(WORKFLOW_ID); String greeting = workflowById.getResult(String.class); System.out.println(greeting); System.exit(0); } } ================================================ FILE: core/src/main/java/io/temporal/samples/hello/HelloCancellationScope.java ================================================ package io.temporal.samples.hello; import io.temporal.activity.Activity; import io.temporal.activity.ActivityCancellationType; import io.temporal.activity.ActivityExecutionContext; import io.temporal.activity.ActivityInterface; import io.temporal.activity.ActivityOptions; import io.temporal.client.ActivityCompletionException; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.failure.ActivityFailure; import io.temporal.failure.CanceledFailure; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import io.temporal.worker.WorkerOptions; import io.temporal.workflow.Async; import io.temporal.workflow.CancellationScope; import io.temporal.workflow.Promise; import io.temporal.workflow.Workflow; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; import java.io.IOException; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.concurrent.TimeUnit; /** * Sample Temporal Workflow Definition that demonstrates parallel Activity Executions with a * Cancellation Scope. When one of the Activity Executions finish, we cancel the execution of the * other Activities and wait for their cancellation to complete. */ public class HelloCancellationScope { // Define the task queue name static final String TASK_QUEUE = "HelloCancellationScopeTaskQueue"; // Define our workflow unique id static final String WORKFLOW_ID = "HelloCancellationScopeWorkflow"; /** * The Workflow Definition's Interface must contain one method annotated with @WorkflowMethod. * *

Workflow Definitions should not contain any heavyweight computations, non-deterministic * code, network calls, database operations, etc. Those things should be handled by the * Activities. * * @see io.temporal.workflow.WorkflowInterface * @see io.temporal.workflow.WorkflowMethod */ @WorkflowInterface public interface GreetingWorkflow { /** * This is the method that is executed when the Workflow Execution is started. The Workflow * Execution completes when this method finishes execution. */ @WorkflowMethod String getGreeting(String name); } /** * This is the Activity Definition's Interface. Activities are building blocks of any Temporal * Workflow and contain any business logic that could perform long running computation, network * calls, etc. * *

Annotating Activity Definition methods with @ActivityMethod is optional. * * @see io.temporal.activity.ActivityInterface * @see io.temporal.activity.ActivityMethod */ @ActivityInterface public interface GreetingActivities { String composeGreeting(String greeting, String name); } // Define the workflow implementation which implements our getGreeting workflow method. public static class GreetingWorkflowImpl implements GreetingWorkflow { private static final int ACTIVITY_MAX_SLEEP_SECONDS = 30; private static final int ACTIVITY_MAX_CLEANUP_SECONDS = 5; private static final int ACTIVITY_START_TO_CLOSE_TIMEOUT = ACTIVITY_MAX_SLEEP_SECONDS + ACTIVITY_MAX_CLEANUP_SECONDS + 10; private static final String[] greetings = new String[] {"Hello", "Bye", "Hola", "Привет", "Oi", "Hallo"}; /** * Define the GreetingActivities stub. Activity stubs are proxies for activity invocations that * are executed outside of the workflow thread on the activity worker, that can be on a * different host. Temporal is going to dispatch the activity results back to the workflow and * unblock the stub as soon as activity is completed on the activity worker. * *

In the {@link ActivityOptions} definition the "setStartToCloseTimeout" option sets the * maximum time of a single Activity execution attempt. For this example it is set to 10 * seconds. * *

The "setCancellationType" option means that in case of activity cancellation the activity * should fail with {@link CanceledFailure}. We set * ActivityCancellationType.WAIT_CANCELLATION_COMPLETED which denotes that activity should be * first notified of the cancellation, and cancelled after it can perform some cleanup tasks for * example. Note that an activity must heartbeat to receive cancellation notifications. */ private final GreetingActivities activities = Workflow.newActivityStub( GreetingActivities.class, ActivityOptions.newBuilder() // if heartbeat timeout is not set, activity heartbeats will be throttled to one // every 30 seconds // which is too rare for the cancellations to be delivered in this example. .setHeartbeatTimeout(Duration.ofSeconds(5)) .setStartToCloseTimeout(Duration.ofSeconds(ACTIVITY_START_TO_CLOSE_TIMEOUT)) .setCancellationType(ActivityCancellationType.WAIT_CANCELLATION_COMPLETED) .build()); @Override public String getGreeting(String name) { List> results = new ArrayList<>(greetings.length); /* * Create our CancellationScope. Within this scope we call the workflow activity * composeGreeting method asynchronously for each of our defined greetings in different * languages. */ CancellationScope scope = Workflow.newCancellationScope( () -> { for (String greeting : greetings) { results.add(Async.function(activities::composeGreeting, greeting, name)); } }); /* * Execute all activities within the CancellationScope. Note that this execution is * non-blocking as the code inside our cancellation scope is also non-blocking. */ scope.run(); // We use "anyOf" here to wait for one of the activity invocations to return String result = Promise.anyOf(results).get(); // Trigger cancellation of all uncompleted activity invocations within the cancellation scope scope.cancel(); /* * Wait for all activities to perform cleanup if needed. * For the sake of the example we ignore cancellations and * get all the results so that we can print them in the end. * * Note that we cannot use "allOf" here as that fails on any Promise failures */ for (Promise activityResult : results) { try { activityResult.get(); } catch (ActivityFailure e) { if (!(e.getCause() instanceof CanceledFailure)) { throw e; } } } return result; } } /** * Implementation of our workflow activity interface. It overwrites our defined composeGreeting * method. */ static class GreetingActivitiesImpl implements GreetingActivities { @Override public String composeGreeting(String greeting, String name) { // Get the activity execution context ActivityExecutionContext context = Activity.getExecutionContext(); // simulate a random time this activity should execute for Random random = new Random(); int seconds = random.nextInt(GreetingWorkflowImpl.ACTIVITY_MAX_SLEEP_SECONDS - 5) + 5; System.out.println("Activity for " + greeting + " going to take " + seconds + " seconds"); for (int i = 0; i < seconds; i++) { sleep(1); try { // Perform the heartbeat. Used to notify the workflow that activity execution is alive context.heartbeat(i); } catch (ActivityCompletionException e) { /* * Activity heartbeat can throw an exception for multiple reasons, including: * 1) activity cancellation * 2) activity not existing (due to a timeout for example) from the service point of view * 3) activity worker shutdown request * * In our case our activity fails because one of the other performed activities * has completed execution and our workflow method has issued the "cancel" request * to cancel all other activities in the cancellation scope. * * The following code simulates our activity after cancellation "cleanup" */ seconds = random.nextInt(GreetingWorkflowImpl.ACTIVITY_MAX_CLEANUP_SECONDS); System.out.println( "Activity for " + greeting + " was cancelled. Cleanup is expected to take " + seconds + " seconds."); sleep(seconds); System.out.println("Activity for " + greeting + " finished cancellation"); throw e; } } // return results of activity invocation System.out.println("Activity for " + greeting + " completed"); return greeting + " " + name + "!"; } private void sleep(int seconds) { try { Thread.sleep(TimeUnit.SECONDS.toMillis(seconds)); } catch (InterruptedException ee) { // Empty } } } /** * With our Workflow and Activities defined, we can now start execution. The main method starts * the worker and then the workflow. */ public static void main(String[] args) { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } // Get a Workflow service stub. WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); /* * Define the workflow factory. It is used to create workflow workers for a specific task queue. */ WorkerFactory factory = WorkerFactory.newInstance(client); /* * Define the workflow worker. Workflow workers listen to a defined task queue and process * workflows and activities. * * In the {@link ActivityOptions} definition the * "setMaxConcurrentActivityExecutionSize" option sets the max number of parallel activity executions allowed * The "setMaxConcurrentActivityTaskPollers" option sets the number of simultaneous poll requests on activity task queue */ Worker worker = factory.newWorker( TASK_QUEUE, WorkerOptions.newBuilder() .setMaxConcurrentActivityExecutionSize(100) .setMaxConcurrentActivityTaskPollers(1) .build()); /* * Register our workflow implementation with the worker. * Workflow implementations must be known to the worker at runtime in * order to dispatch workflow tasks. */ worker.registerWorkflowImplementationTypes(GreetingWorkflowImpl.class); /* * Register our Activity Types with the Worker. Since Activities are stateless and thread-safe, * the Activity Type is a shared instance. */ worker.registerActivitiesImplementations(new GreetingActivitiesImpl()); /* * Start all the workers registered for a specific task queue. * The started workers then start polling for workflows and activities. */ factory.start(); // Create the workflow client stub. It is used to start our workflow execution. GreetingWorkflow workflow = client.newWorkflowStub( GreetingWorkflow.class, WorkflowOptions.newBuilder() .setWorkflowId(WORKFLOW_ID) .setTaskQueue(TASK_QUEUE) .build()); /* * Execute our workflow and wait for it to complete. The call to our getGreeting method is * synchronous. */ String greeting = workflow.getGreeting("World"); // Display workflow execution results System.out.println(greeting); System.exit(0); } } ================================================ FILE: core/src/main/java/io/temporal/samples/hello/HelloCancellationScopeWithTimer.java ================================================ package io.temporal.samples.hello; import io.temporal.activity.*; import io.temporal.client.ActivityCompletionException; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.failure.ActivityFailure; import io.temporal.failure.CanceledFailure; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import io.temporal.workflow.*; import java.io.IOException; import java.time.Duration; import java.util.concurrent.TimeUnit; public class HelloCancellationScopeWithTimer { // Define the task queue name static final String TASK_QUEUE = "HelloCancellationScopeTimerTaskQueue"; // Define our workflow unique id static final String WORKFLOW_ID = "HelloCancellationScopeTimerWorkflow"; /** * The Workflow Definition's Interface must contain one method annotated with @WorkflowMethod. * *

Workflow Definitions should not contain any heavyweight computations, non-deterministic * code, network calls, database operations, etc. Those things should be handled by the * Activities. * * @see io.temporal.workflow.WorkflowInterface * @see io.temporal.workflow.WorkflowMethod */ @WorkflowInterface public interface CancellationWithTimerWorkflow { /** * This is the method that is executed when the Workflow Execution is started. The Workflow * Execution completes when this method finishes execution. */ @WorkflowMethod String execute(String input); } /** * This is the Activity Definition's Interface. Activities are building blocks of any Temporal * Workflow and contain any business logic that could perform long running computation, network * calls, etc. * *

Annotating Activity Definition methods with @ActivityMethod is optional. * * @see io.temporal.activity.ActivityInterface * @see io.temporal.activity.ActivityMethod */ @ActivityInterface public interface UpdateInfoActivities { String updateInfo(String input); } // Define the workflow implementation which implements our getGreeting workflow method. public static class CancellationWithTimerWorkflowImpl implements CancellationWithTimerWorkflow { private final UpdateInfoActivities activities = Workflow.newActivityStub( UpdateInfoActivities.class, ActivityOptions.newBuilder() // If heartbeat timeout is not set, activity heartbeats will be throttled to one // every 30 seconds, it also will not have a heartbeat timeout. .setHeartbeatTimeout(Duration.ofSeconds(2)) .setStartToCloseTimeout(Duration.ofSeconds(10)) .setCancellationType(ActivityCancellationType.WAIT_CANCELLATION_COMPLETED) .build()); private String result; @Override public String execute(String input) { // Create cancellation scope for our activity execution CancellationScope cancellationScope = Workflow.newCancellationScope( () -> { try { result = activities.updateInfo(input); } catch (ActivityFailure cause) { throw cause; } }); // Create a timer, if this timer fires we want to cancel our activity and complete the // workflow execution // Giving client default result. Note for sample the tier is set to less than the // activity StartToClose timeout in order to simulate it getting cancelled Workflow.newTimer(Duration.ofSeconds(3)) .thenApply( result -> { // Cancel our activity, note activity has to heartbeat to receive cancellation System.out.println("Cancelling scope as timer fired"); cancellationScope.cancel(); return null; }); // Start our cancellation scope try { cancellationScope.run(); } catch (ActivityFailure e) { // Activity cancellation is going thrigger activity failure // The cause of activity failure would be CanceledFailure if (e.getCause() instanceof CanceledFailure) { result = "Activity canceled due to timer firing."; } else { result = "Activity failed due to: " + e.getMessage(); } } return result; } } /** * Implementation of our workflow activity interface. It overwrites our defined composeGreeting * method. */ static class UpdateInfoActivitiesImpl implements UpdateInfoActivities { @Override public String updateInfo(String input) { // Get the activity execution context ActivityExecutionContext context = Activity.getExecutionContext(); // Our "dummy" activity just sleeps for a second up to 10 times and heartbeats for (int i = 0; i < 10; i++) { sleep(1); try { context.heartbeat(i); } catch (ActivityCompletionException e) { // Here we can do some cleanup if needed before we re-throw activity completion exception throw e; } } return "dummy activity result"; } private void sleep(int seconds) { try { Thread.sleep(TimeUnit.SECONDS.toMillis(seconds)); } catch (InterruptedException ee) { // Empty } } } /** * With our Workflow and Activities defined, we can now start execution. The main method starts * the worker and then the workflow. */ public static void main(String[] args) { // Get a Workflow service stub. // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); /* * Get a Workflow service client which can be used to start, Signal, and Query Workflow Executions. */ WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); /* * Define the workflow factory. It is used to create workflow workers for a specific task queue. */ WorkerFactory factory = WorkerFactory.newInstance(client); /* * Define the workflow worker. Workflow workers listen to a defined task queue and process * workflows and activities. */ Worker worker = factory.newWorker(TASK_QUEUE); /* * Register our workflow implementation with the worker. * Workflow implementations must be known to the worker at runtime in * order to dispatch workflow tasks. */ worker.registerWorkflowImplementationTypes(CancellationWithTimerWorkflowImpl.class); /* * Register our Activity Types with the Worker. Since Activities are stateless and thread-safe, * the Activity Type is a shared instance. */ worker.registerActivitiesImplementations(new UpdateInfoActivitiesImpl()); /* * Start all the workers registered for a specific task queue. * The started workers then start polling for workflows and activities. */ factory.start(); // Create the workflow client stub. It is used to start our workflow execution. CancellationWithTimerWorkflow workflow = client.newWorkflowStub( CancellationWithTimerWorkflow.class, WorkflowOptions.newBuilder() .setWorkflowId(WORKFLOW_ID) .setTaskQueue(TASK_QUEUE) .build()); /* * Execute our workflow and wait for it to complete. The call to our getGreeting method is * synchronous. */ String result = workflow.execute("Some test input"); // Display workflow execution results System.out.println(result); System.exit(0); } } ================================================ FILE: core/src/main/java/io/temporal/samples/hello/HelloChild.java ================================================ package io.temporal.samples.hello; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import io.temporal.workflow.Async; import io.temporal.workflow.Promise; import io.temporal.workflow.Workflow; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; import java.io.IOException; /** * Sample Temporal Workflow Definition that demonstrates the execution of a Child Workflow. Child * workflows allow you to group your Workflow logic into small logical and reusable units that solve * a particular problem. They can be typically reused by multiple other Workflows. */ public class HelloChild { // Define the task queue name static final String TASK_QUEUE = "HelloChildTaskQueue"; // Define the workflow unique id static final String WORKFLOW_ID = "HelloChildWorkflow"; /** * Define the parent workflow interface. It must contain one method annotated with @WorkflowMethod * * @see io.temporal.workflow.WorkflowInterface * @see io.temporal.workflow.WorkflowMethod */ @WorkflowInterface public interface GreetingWorkflow { /** * Define the parent workflow method. This method is executed when the workflow is started. The * workflow completes when the workflow method finishes execution. */ @WorkflowMethod String getGreeting(String name); } /** * Define the child workflow Interface. It must contain one method annotated with @WorkflowMethod * * @see io.temporal.workflow.WorkflowInterface * @see io.temporal.workflow.WorkflowMethod */ @WorkflowInterface public interface GreetingChild { /** * Define the child workflow method. This method is executed when the workflow is started. The * workflow completes when the workflow method finishes execution. */ @WorkflowMethod String composeGreeting(String greeting, String name); } // Define the parent workflow implementation. It implements the getGreeting workflow method public static class GreetingWorkflowImpl implements GreetingWorkflow { @Override public String getGreeting(String name) { /* * Define the child workflow stub. Since workflows are stateful, * a new stub must be created for each child workflow. */ GreetingChild child = Workflow.newChildWorkflowStub(GreetingChild.class); // This is a non blocking call that returns immediately. // Use child.composeGreeting("Hello", name) to call synchronously. /* * Invoke the child workflows composeGreeting workflow method. * This call is non-blocking and returns immediately returning a {@link io.temporal.workflow.Promise} * * You can use child.composeGreeting("Hello", name) instead to call the child workflow method synchronously. */ Promise greeting = Async.function(child::composeGreeting, "Hello", name); // Wait for the child workflow to complete and return its results return greeting.get(); } } /** * Define the parent workflow implementation. It implements the getGreeting workflow method * *

Note that a workflow implementation must always be public for the Temporal library to be * able to create its instances. */ public static class GreetingChildImpl implements GreetingChild { @Override public String composeGreeting(String greeting, String name) { return greeting + " " + name + "!"; } } /** * With the workflow, and child workflow defined, we can now start execution. The main method is * the workflow starter. */ public static void main(String[] args) { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } // Get a Workflow service stub. WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); /* * Define the worker factory. It is used to create workers for a specific task queue. */ WorkerFactory factory = WorkerFactory.newInstance(client); /* * Define the worker. Workers listen to a defined task queue and process workflows and * activities. */ Worker worker = factory.newWorker(TASK_QUEUE); /* * Register the parent and child workflow implementation with the worker. * Since workflows are stateful in nature, * we need to register the workflow types. */ worker.registerWorkflowImplementationTypes(GreetingWorkflowImpl.class, GreetingChildImpl.class); /* * Start all the workers registered for a specific task queue. * The started workers then start polling for workflows and activities. */ factory.start(); // Start a workflow execution. Usually this is done from another program. // Uses task queue from the GreetingWorkflow @WorkflowMethod annotation. // Create our parent workflow client stub. It is used to start the parent workflow execution. GreetingWorkflow workflow = client.newWorkflowStub( GreetingWorkflow.class, WorkflowOptions.newBuilder() .setWorkflowId(WORKFLOW_ID) .setTaskQueue(TASK_QUEUE) .build()); // Execute our parent workflow and wait for it to complete. String greeting = workflow.getGreeting("World"); // Display the parent workflow execution results System.out.println(greeting); System.exit(0); } } ================================================ FILE: core/src/main/java/io/temporal/samples/hello/HelloCron.java ================================================ package io.temporal.samples.hello; import io.temporal.activity.Activity; import io.temporal.activity.ActivityInterface; import io.temporal.activity.ActivityOptions; import io.temporal.api.common.v1.WorkflowExecution; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowExecutionAlreadyStarted; import io.temporal.client.WorkflowOptions; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import io.temporal.workflow.Workflow; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; import java.io.IOException; import java.time.Duration; /** * Sample Temporal workflow that demonstrates periodic workflow execution using a cron. Note that * the periodic execution is based on a fixed delay (provided by the cron definition). To learn * about periodic execution with a dynamic delay checkout the {@link HelloPeriodic} example. */ public class HelloCron { // Define the task queue name static final String TASK_QUEUE = "HelloCronTaskQueue"; // Define the workflow unique id static final String WORKFLOW_ID = "HelloCronWorkflow"; /** * The Workflow Definition's Interface must contain one method annotated with @WorkflowMethod. * *

Workflow Definitions should not contain any heavyweight computations, non-deterministic * code, network calls, database operations, etc. Those things should be handled by the * Activities. * * @see io.temporal.workflow.WorkflowInterface * @see io.temporal.workflow.WorkflowMethod */ @WorkflowInterface public interface GreetingWorkflow { /** * This is the method that is executed when the Workflow Execution is started. The Workflow * Execution completes when this method finishes execution. */ @WorkflowMethod void greet(String name); } /** * This is the Activity Definition's Interface. Activities are building blocks of any Temporal * Workflow and contain any business logic that could perform long running computation, network * calls, etc. * *

Annotating Activity Definition methods with @ActivityMethod is optional. * * @see io.temporal.activity.ActivityInterface * @see io.temporal.activity.ActivityMethod */ @ActivityInterface public interface GreetingActivities { // Define your activity method which can be called during workflow execution void greet(String greeting); } // Define the workflow implementation which implements the greet workflow method. public static class GreetingWorkflowImpl implements GreetingWorkflow { /** * Define the GreetingActivities stub. Activity stubs are proxies for activity invocations that * are executed outside of the workflow thread on the activity worker, that can be on a * different host. Temporal is going to dispatch the activity results back to the workflow and * unblock the stub as soon as activity is completed on the activity worker. * *

In the {@link ActivityOptions} definition the "setStartToCloseTimeout" option sets the * maximum time of a single Activity execution attempt. For this example it is set to 10 * seconds. */ private final GreetingActivities activities = Workflow.newActivityStub( GreetingActivities.class, ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(10)).build()); @Override public void greet(String name) { activities.greet("Hello " + name + "!"); } } /** * Implementation of the workflow activity interface. It overwrites the defined greet activity * method. */ static class GreetingActivitiesImpl implements GreetingActivities { @Override public void greet(String greeting) { System.out.println( "From " + Activity.getExecutionContext().getInfo().getWorkflowId() + ": " + greeting); } } /** * With the Workflow and Activities defined, we can now start execution. The main method starts * the worker and then the workflow. */ public static void main(String[] args) { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } // Get a Workflow service stub. WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); /* * Define the workflow factory. It is used to create workflow workers for a specific task queue. */ WorkerFactory factory = WorkerFactory.newInstance(client); /* * Define the workflow worker. Workflow workers listen to a defined task queue and process * workflows and activities. */ Worker worker = factory.newWorker(TASK_QUEUE); /* * Register the workflow implementation with the worker. * Workflow implementations must be known to the worker at runtime in * order to dispatch workflow tasks. */ worker.registerWorkflowImplementationTypes(GreetingWorkflowImpl.class); /* * Register the workflow activity implementation with the worker. Since workflow activities are * stateless and thread-safe, we need to register a shared instance. */ worker.registerActivitiesImplementations(new GreetingActivitiesImpl()); /* * Start all the workers registered for a specific task queue. * The started workers then start polling for workflows and activities. */ factory.start(); /* * Define our workflow options. Note that the cron definition is not part of the * core workflow definition. Workflow options allow you to execute the same * workflow in different ways (for example with or without a cron, etc). * * Here we use setCronSchedule to define a cron for our workflow execution. * The cron format is parsed by the https://github.com/robfig/cron" library. * In addition to the standard "* * * * *" format Temporal also supports the "@every" as well as * other cron definition extensions. For example you could define "@every 2s" to define a cron definition * which executes our workflow every two seconds. * * The defined cron expression "* * * * *" means that our workflow should execute every minute. * * We also use setWorkflowExecutionTimeout to define the workflow execution total time (set to three minutes). * After this time, our workflow execution ends (and our cron will stop executing as well). * * The setWorkflowRunTimeout defines the amount of time after which a single workflow instance is terminated. * * So given all our settings in the WorkflowOptions we define the following: * "Execute our workflow once every minute for three minutes. * Once a workflow instance is started, terminate it after one minute (if its still running)" * */ WorkflowOptions workflowOptions = WorkflowOptions.newBuilder() .setWorkflowId(WORKFLOW_ID) .setTaskQueue(TASK_QUEUE) .setCronSchedule("* * * * *") .setWorkflowExecutionTimeout(Duration.ofMinutes(3)) .setWorkflowRunTimeout(Duration.ofMinutes(1)) .build(); // Create the workflow client stub. It is used to start our workflow execution. GreetingWorkflow workflow = client.newWorkflowStub(GreetingWorkflow.class, workflowOptions); try { // start workflow execution WorkflowExecution execution = WorkflowClient.start(workflow::greet, "World"); System.out.println("Started " + execution); } catch (WorkflowExecutionAlreadyStarted e) { // Thrown when a workflow with the same WORKFLOW_ID is currently running System.out.println("Already running as " + e.getExecution()); } catch (Throwable e) { e.printStackTrace(); System.exit(1); } } } ================================================ FILE: core/src/main/java/io/temporal/samples/hello/HelloDelayedStart.java ================================================ package io.temporal.samples.hello; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.common.WorkflowExecutionHistory; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import io.temporal.workflow.Workflow; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; import java.io.IOException; import java.time.Duration; /** Sample Temporal Workflow Definition that shows how to use delayed start. */ public class HelloDelayedStart { // Define the task queue name static final String TASK_QUEUE = "HelloDelayedStartTaskQueue"; // Define our workflow unique id static final String WORKFLOW_ID = "HelloDelayedStartWorkflow"; /** * The Workflow Definition's Interface must contain one method annotated with @WorkflowMethod. * *

Workflow Definitions should not contain any heavyweight computations, non-deterministic * code, network calls, database operations, etc. Those things should be handled by the * Activities. * * @see io.temporal.workflow.WorkflowInterface * @see io.temporal.workflow.WorkflowMethod */ @WorkflowInterface public interface DelayedStartWorkflow { /** * This is the method that is executed when the Workflow Execution is started. The Workflow * Execution completes when this method finishes execution. */ @WorkflowMethod void start(); } // Define the workflow implementation which implements our start workflow method. public static class DelayedStartWorkflowImpl implements DelayedStartWorkflow { @Override public void start() { // this workflow just sleeps for a second Workflow.sleep(Duration.ofSeconds(1)); } } public static void main(String[] args) { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } // Get a Workflow service stub. WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); /* * Define the workflow factory. It is used to create workflow workers for a specific task queue. */ WorkerFactory factory = WorkerFactory.newInstance(client); /* * Define the workflow worker. Workflow workers listen to a defined task queue and process * workflows and activities. */ Worker worker = factory.newWorker(TASK_QUEUE); /* * Register our workflow implementation with the worker. * Workflow implementations must be known to the worker at runtime in * order to dispatch workflow tasks. */ worker.registerWorkflowImplementationTypes(DelayedStartWorkflowImpl.class); /* * Start all the workers registered for a specific task queue. * The started workers then start polling for workflows and activities. */ factory.start(); DelayedStartWorkflow workflow = client.newWorkflowStub( DelayedStartWorkflow.class, WorkflowOptions.newBuilder() .setWorkflowId(WORKFLOW_ID) .setTaskQueue(TASK_QUEUE) // set delayed start in 2 seconds .setStartDelay(Duration.ofSeconds(2)) .build()); workflow.start(); // Delayed executions are still created right away by the service but // they have a firstWorkflowTaskBackoff set to the delay duration // meaning the first workflow task is dispatched by service // 2 second after exec is started in our sample WorkflowExecutionHistory history = client.fetchHistory(WORKFLOW_ID); com.google.protobuf.Duration backoff = history .getHistory() .getEvents(0) .getWorkflowExecutionStartedEventAttributes() .getFirstWorkflowTaskBackoff(); System.out.println("First workflow task backoff: " + backoff.getSeconds()); System.exit(0); } } ================================================ FILE: core/src/main/java/io/temporal/samples/hello/HelloDetachedCancellationScope.java ================================================ package io.temporal.samples.hello; import io.temporal.activity.Activity; import io.temporal.activity.ActivityCancellationType; import io.temporal.activity.ActivityInterface; import io.temporal.activity.ActivityOptions; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowFailedException; import io.temporal.client.WorkflowOptions; import io.temporal.client.WorkflowStub; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.failure.ActivityFailure; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import io.temporal.workflow.*; import java.io.IOException; import java.time.Duration; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** * This sample Temporal Workflow Definition demonstrates how to run "cleanup" code when a Workflow * Execution has been explicitly cancelled. */ public class HelloDetachedCancellationScope { // Define the task queue name static final String TASK_QUEUE = "HelloDetachedCancellationTaskQueue"; // Define our workflow unique id static final String WORKFLOW_ID = "HelloDetachedCancellationWorkflow"; /** * The Workflow Definition's Interface must contain one method annotated with @WorkflowMethod. * *

Workflow Definitions should not contain any heavyweight computations, non-deterministic * code, network calls, database operations, etc. Those things should be handled by the * Activities. * * @see io.temporal.workflow.WorkflowInterface * @see io.temporal.workflow.WorkflowMethod */ @WorkflowInterface public interface GreetingWorkflow { /** * This is the method that is executed when the Workflow Execution is started. The Workflow * Execution completes when this method finishes execution. */ @WorkflowMethod String getGreeting(String name); /** Query method to get the greeting */ @QueryMethod String queryGreeting(); } /** * This is the Activity Definition's Interface. Activities are building blocks of any Temporal * Workflow and contain any business logic that could perform long running computation, network * calls, etc. * *

Annotating Activity Definition methods with @ActivityMethod is optional. * * @see io.temporal.activity.ActivityInterface * @see io.temporal.activity.ActivityMethod */ @ActivityInterface public interface GreetingActivities { String sayHello(String name); String sayGoodBye(String name); } /** This is the Greeting Activity Definition. */ static class GreetingActivitiesImpl implements GreetingActivities { @Override public String sayHello(String name) { // This simulates a long-running Activity Execution so we can cancel the Workflow Execution // before it completes. for (int i = 0; i < Integer.MAX_VALUE; i++) { try { Thread.sleep(200); } catch (InterruptedException e) { // Wrap and re-throw the exception. throw Activity.wrap(e); } Activity.getExecutionContext().heartbeat(i); } return "unreachable"; } @Override public String sayGoodBye(String name) { return "Goodbye " + name + "!"; } } /** This is the Workflow Definition which implements our getGreeting method. */ public static class GreetingWorkflowImpl implements GreetingWorkflow { private String greeting; private final GreetingActivities activities = Workflow.newActivityStub( GreetingActivities.class, ActivityOptions.newBuilder() .setStartToCloseTimeout(Duration.ofSeconds(10)) .setCancellationType(ActivityCancellationType.WAIT_CANCELLATION_COMPLETED) .setHeartbeatTimeout(Duration.ofSeconds(2)) .build()); @Override public String getGreeting(String name) { try { this.greeting = activities.sayHello(name); return greeting; } catch (ActivityFailure af) { // Create a CancellationScope that is not linked to a parent scope // This can be used in the "cleanup" code after the Workflow Execution has been cancelled. CancellationScope detached = Workflow.newDetachedCancellationScope(() -> greeting = activities.sayGoodBye(name)); detached.run(); throw af; } } @Override public String queryGreeting() { return greeting; } } public static void main(String[] args) throws InterruptedException { // Get a Workflow service stub. // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); /* * Get a Workflow service client which can be used to start, Signal, and Query Workflow * Executions. */ WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); /* * Define the workflow factory. It is used to create workflow workers for a specific task queue. */ WorkerFactory factory = WorkerFactory.newInstance(client); /* * Define the workflow worker. Workflow workers listen to a defined task queue and process * workflows and activities. */ Worker worker = factory.newWorker(TASK_QUEUE); /* * Register our Workflow Types with the Worker. Workflow Types must be known to the Worker at * runtime. */ worker.registerWorkflowImplementationTypes(GreetingWorkflowImpl.class); /* * Register our Activity Types with the Worker. Since Activities are stateless and thread-safe, * the Activity Type is a shared instance. */ worker.registerActivitiesImplementations(new GreetingActivitiesImpl()); /* * Start all the Workers that are in this process. The Workers will then start polling for * Workflow Tasks and Activity Tasks. */ factory.start(); // Create the Workflow client stub in order to start our Workflow Execution. GreetingWorkflow workflow = client.newWorkflowStub( GreetingWorkflow.class, WorkflowOptions.newBuilder() .setWorkflowId(WORKFLOW_ID) .setTaskQueue(TASK_QUEUE) .build()); WorkflowClient.start(workflow::getGreeting, "John"); WorkflowStub workflowStub = WorkflowStub.fromTyped(workflow); Thread.sleep(1000); // Cancel the Workflow Execution // Note that this can be done from a different client. workflowStub.cancel(); String result; try { // Wait for Workflow Execution results // Because we cancelled the Workflow Execution we should get WorkflowFailedException result = workflowStub.getResult(6, TimeUnit.SECONDS, String.class, String.class); } catch (TimeoutException | WorkflowFailedException e) { // Query the Workflow Execution to get the result which was set by the detached cancellation // scope run result = workflowStub.query("queryGreeting", String.class); } System.out.println(result); System.exit(0); } } ================================================ FILE: core/src/main/java/io/temporal/samples/hello/HelloDynamic.java ================================================ package io.temporal.samples.hello; import io.temporal.activity.Activity; import io.temporal.activity.ActivityOptions; import io.temporal.activity.DynamicActivity; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.client.WorkflowStub; import io.temporal.common.converter.EncodedValues; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import io.temporal.workflow.ActivityStub; import io.temporal.workflow.DynamicSignalHandler; import io.temporal.workflow.DynamicWorkflow; import io.temporal.workflow.Workflow; import java.io.IOException; import java.time.Duration; public class HelloDynamic { // Define the task queue name public static final String TASK_QUEUE = "HelloDynamicTaskQueue"; // Define our workflow unique id public static final String WORKFLOW_ID = "HelloDynamicWorkflow"; // Dynamic Workflow Implementation public static class DynamicGreetingWorkflowImpl implements DynamicWorkflow { private String name; @Override public Object execute(EncodedValues args) { String greeting = args.get(0, String.class); String type = Workflow.getInfo().getWorkflowType(); // Register dynamic signal handler Workflow.registerListener( (DynamicSignalHandler) (signalName, encodedArgs) -> name = encodedArgs.get(0, String.class)); // Define activity options and get ActivityStub ActivityStub activity = Workflow.newUntypedActivityStub( ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(10)).build()); // Execute the dynamic Activity. Note that the provided Activity name is not // explicitly registered with the Worker String greetingResult = activity.execute("DynamicACT", String.class, greeting, name, type); // Return results return greetingResult; } } // Dynamic Activity implementation public static class DynamicGreetingActivityImpl implements DynamicActivity { @Override public Object execute(EncodedValues args) { String activityType = Activity.getExecutionContext().getInfo().getActivityType(); return activityType + ": " + args.get(0, String.class) + " " + args.get(1, String.class) + " from: " + args.get(2, String.class); } } /** * With our dynamic Workflow and Activities defined, we can now start execution. The main method * starts the worker and then the workflow. */ public static void main(String[] arg) { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } // Get a Workflow service stub. WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); /* * Define the workflow factory. It is used to create workflow workers for a specific task queue. */ WorkerFactory factory = WorkerFactory.newInstance(client); /* * Define the workflow worker. Workflow workers listen to a defined task queue and process * workflows and activities. */ Worker worker = factory.newWorker(TASK_QUEUE); /* * Register our dynamic workflow implementation with the worker. Workflow implementations must * be known to the worker at runtime in order to dispatch workflow tasks. */ worker.registerWorkflowImplementationTypes(DynamicGreetingWorkflowImpl.class); /* * Register our dynamic workflow activity implementation with the worker. Since workflow * activities are stateless and thread-safe, we need to register a shared instance. */ worker.registerActivitiesImplementations(new DynamicGreetingActivityImpl()); /* * Start all the Workers that are in this process. The Workers will then start polling for * Workflow Tasks and Activity Tasks. */ factory.start(); /* * Create the workflow stub Note that the Workflow type is not explicitly registered with the * Worker */ WorkflowOptions workflowOptions = WorkflowOptions.newBuilder().setTaskQueue(TASK_QUEUE).setWorkflowId(WORKFLOW_ID).build(); WorkflowStub workflow = client.newUntypedWorkflowStub("DynamicWF", workflowOptions); // Start workflow execution and signal right after Pass in the workflow args and signal args workflow.signalWithStart("greetingSignal", new Object[] {"John"}, new Object[] {"Hello"}); // Wait for workflow to finish getting the results String result = workflow.getResult(String.class); System.out.println(result); System.exit(0); } } ================================================ FILE: core/src/main/java/io/temporal/samples/hello/HelloEagerWorkflowStart.java ================================================ package io.temporal.samples.hello; import io.temporal.activity.ActivityInterface; import io.temporal.activity.ActivityMethod; import io.temporal.activity.ActivityOptions; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import io.temporal.workflow.Workflow; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; import java.io.IOException; import java.time.Duration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Sample Temporal Workflow Definition that starts eagerly and executes a single Local Activity. * Important elements of eager starting are: the client starting the workflow and the worker * executing it need to be shared, worker options needs to have .setDisableEagerExecution(false) * set, the activity is recommended to be a local activity for best performance */ public class HelloEagerWorkflowStart { // Define the task queue name static final String TASK_QUEUE = "HelloEagerWorkflowStartTaskQueue"; // Define our workflow unique id static final String WORKFLOW_ID = "HelloEagerWorkflowStartWorkflow"; /** * The Workflow Definition's Interface must contain one method annotated with @WorkflowMethod. * *

Workflow Definitions should not contain any heavyweight computations, non-deterministic * code, network calls, database operations, etc. Those things should be handled by the * Activities. * * @see io.temporal.workflow.WorkflowInterface * @see io.temporal.workflow.WorkflowMethod */ @WorkflowInterface public interface GreetingWorkflow { /** * This is the method that is executed when the Workflow Execution is started. The Workflow * Execution completes when this method finishes execution. */ @WorkflowMethod String getGreeting(String name); } /** * This is the Activity Definition's Interface. Activities are building blocks of any Temporal * Workflow and contain any business logic that could perform long running computation, network * calls, etc. * *

Annotating Activity Definition methods with @ActivityMethod is optional. * * @see io.temporal.activity.ActivityInterface * @see io.temporal.activity.ActivityMethod */ @ActivityInterface public interface GreetingActivities { // Define your activity method which can be called during workflow execution @ActivityMethod(name = "greet") String composeGreeting(String greeting, String name); } // Define the workflow implementation which implements our getGreeting workflow method. public static class GreetingWorkflowImpl implements GreetingWorkflow { /** * Define the GreetingActivities stub. Activity stubs are proxies for activity invocations that * are executed outside of the workflow thread on the activity worker, that can be on a * different host. Temporal is going to dispatch the activity results back to the workflow and * unblock the stub as soon as activity is completed on the activity worker. * *

In the {@link ActivityOptions} definition the "setStartToCloseTimeout" option sets the * overall timeout that our workflow is willing to wait for activity to complete. For this * example it is set to 2 seconds. */ private final GreetingActivities activities = Workflow.newActivityStub( GreetingActivities.class, ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(2)).build()); @Override public String getGreeting(String name) { // This is a blocking call that returns only after the activity has completed. return activities.composeGreeting("Hello", name); } } /** Simple activity implementation, that concatenates two strings. */ static class GreetingLocalActivitiesImpl implements GreetingActivities { private static final Logger log = LoggerFactory.getLogger(GreetingLocalActivitiesImpl.class); @Override public String composeGreeting(String greeting, String name) { log.info("Composing greeting..."); return greeting + " " + name + "!"; } } /** * With our Workflow and Activities defined, we can now start execution. The main method starts * the worker and then the workflow. */ public static void main(String[] args) { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } // Get a Workflow service stub. WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); /* * Define the workflow factory. It is used to create workflow workers for a specific task queue. * Here it's important that the worker shares the client for eager execution. */ WorkerFactory factory = WorkerFactory.newInstance(client); /* * Define the workflow worker. Workflow workers listen to a defined task queue and process * workflows and activities. */ Worker worker = factory.newWorker(TASK_QUEUE); /* * Register our workflow implementation with the worker. * Workflow implementations must be known to the worker at runtime in * order to dispatch workflow tasks. */ worker.registerWorkflowImplementationTypes(GreetingWorkflowImpl.class); /* * Register our Activity Types with the Worker. Since Activities are stateless and thread-safe, * the Activity Type is a shared instance. */ worker.registerActivitiesImplementations(new GreetingLocalActivitiesImpl()); /* * Start all the workers registered for a specific task queue. * The started workers then start polling for workflows and activities. */ factory.start(); // Create the workflow client stub. It is used to start our workflow execution. GreetingWorkflow workflow = client.newWorkflowStub( GreetingWorkflow.class, WorkflowOptions.newBuilder() .setWorkflowId(WORKFLOW_ID) .setTaskQueue(TASK_QUEUE) .setDisableEagerExecution(false) // set this to enable eager execution .build()); /* * Execute our workflow and wait for it to complete. The call to our getGreeting method is * synchronous. * * See {@link io.temporal.samples.hello.HelloSignal} for an example of starting workflow * without waiting synchronously for its result. */ String greeting = workflow.getGreeting("World"); // Display workflow execution results System.out.println(greeting); System.exit(0); } } ================================================ FILE: core/src/main/java/io/temporal/samples/hello/HelloException.java ================================================ package io.temporal.samples.hello; import com.google.common.base.Throwables; import io.temporal.activity.Activity; import io.temporal.activity.ActivityInterface; import io.temporal.activity.ActivityOptions; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowException; import io.temporal.client.WorkflowOptions; import io.temporal.common.RetryOptions; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import io.temporal.workflow.Workflow; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; import java.io.IOException; import java.time.Duration; /** * Sample Temporal workflow that demonstrates exception propagation across workflow activities, * child workflow, parent workflow, and the workflow client. */ public class HelloException { // Define the task queue name static final String TASK_QUEUE = "HelloExceptionTaskQueue"; // Define the workflow unique id static final String WORKFLOW_ID = "HelloExceptionWorkflow"; /** * Define the parent workflow interface. It must contain one method annotated with @WorkflowMethod * * @see io.temporal.workflow.WorkflowInterface * @see io.temporal.workflow.WorkflowMethod */ @WorkflowInterface public interface GreetingWorkflow { /** * Define the parent workflow method. This method is executed when the workflow is started. The * workflow completes when the workflow method finishes execution. */ @WorkflowMethod String getGreeting(String name); } /** * Define the child workflow interface. It must contain one method annotated with @WorkflowMethod * * @see io.temporal.workflow.WorkflowInterface * @see io.temporal.workflow.WorkflowMethod */ @WorkflowInterface public interface GreetingChild { /** * Define the child workflow method. This method is executed when the workflow is started. The * workflow completes when the workflow method finishes execution. */ @WorkflowMethod String composeGreeting(String greeting, String name); } /** * This is the Activity Definition's Interface. Activities are building blocks of any Temporal * Workflow and contain any business logic that could perform long running computation, network * calls, etc. * *

Annotating Activity Definition methods with @ActivityMethod is optional. * * @see io.temporal.activity.ActivityInterface * @see io.temporal.activity.ActivityMethod */ @ActivityInterface public interface GreetingActivities { String composeGreeting(String greeting, String name); } // Define the parent workflow implementation. It implements the getGreeting workflow method public static class GreetingWorkflowImpl implements GreetingWorkflow { @Override public String getGreeting(String name) { // Create the child workflow stub GreetingChild child = Workflow.newChildWorkflowStub(GreetingChild.class); // Execute the child workflow return child.composeGreeting("Hello", name); } } // Define the child workflow implementation. It implements the composeGreeting workflow method public static class GreetingChildImpl implements GreetingChild { /* * Define the GreetingActivities stub. Activity stubs are proxies for activity invocations that * are executed outside of the workflow thread on the activity worker, that can be on a * different host. Temporal is going to dispatch the activity results back to the workflow and * unblock the stub as soon as activity is completed on the activity worker. * *

In the {@link ActivityOptions} definition the"setStartToCloseTimeout" option sets the * maximum time of a single Activity execution attempt. For this example it is set to 10 * seconds. */ private final GreetingActivities activities = Workflow.newActivityStub( GreetingActivities.class, ActivityOptions.newBuilder() .setStartToCloseTimeout(Duration.ofMinutes(1)) .setScheduleToStartTimeout(Duration.ofSeconds(5)) .setRetryOptions( RetryOptions.newBuilder() .setInitialInterval(Duration.ofSeconds(1)) .setMaximumAttempts(2) .build()) .build()); @Override public String composeGreeting(String greeting, String name) { return activities.composeGreeting(greeting, name); } } /* * Implementation of the workflow activity interface. It overwrites the defined composeGreeting * activity method. */ static class GreetingActivitiesImpl implements GreetingActivities { @Override public String composeGreeting(String greeting, String name) { try { // here we simulate IOException being thrown inside the activity method // in order to show how it propagates through the workflow execution throw new IOException(greeting + " " + name + "!"); } catch (IOException e) { /* * Instead of adding the thrown exception to the activity method signature * wrap it using Workflow.wrap before re-throwing it. * The original checked exception will be unwrapped and attached as the cause to the * {@link io.temporal.failure.ActivityFailure} */ throw Activity.wrap(e); } } } /** * With our Workflow and Activities defined, we can now start execution. The main method starts * the worker and then the workflow. */ public static void main(String[] args) { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } // Define the workflow service. WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); /* * Define the workflow factory. It is used to create workflow workers for a specific task queue. */ WorkerFactory factory = WorkerFactory.newInstance(client); /* * Define the workflow worker. Workflow workers listen to a defined task queue and process * workflows and activities. */ Worker worker = factory.newWorker(TASK_QUEUE); /* * Register our workflow parent and child implementations with the worker. * Since workflows are stateful in nature, we need to register our workflow types. */ worker.registerWorkflowImplementationTypes(GreetingWorkflowImpl.class, GreetingChildImpl.class); /* * Register our Activity Types with the Worker. Since Activities are stateless and thread-safe, * the Activity Type is a shared instance. */ worker.registerActivitiesImplementations(new GreetingActivitiesImpl()); /* * Start all the workers registered for a specific task queue. * The started workers then start polling for workflows and activities. */ factory.start(); // Create our workflow options WorkflowOptions workflowOptions = WorkflowOptions.newBuilder().setWorkflowId(WORKFLOW_ID).setTaskQueue(TASK_QUEUE).build(); // Create the workflow client stub. It is used to start our workflow execution. GreetingWorkflow workflow = client.newWorkflowStub(GreetingWorkflow.class, workflowOptions); try { // Execute our parent workflow. This will call the child workflow, which then calls the // defined workflow activity. The workflow activity throws the exception. workflow.getGreeting("World"); throw new IllegalStateException("unreachable"); } catch (WorkflowException e) { /* * This stack trace should help you better understand * how exception propagation works with Temporal. * * Looking at the stack trace from bottom-up (to understand the propagation) we first have: * 1) Caused by: io.temporal.failure.ApplicationFailure: message='Hello World!', type='java.io.IOException' * this is the IOException thrown by our activity. * 2) Caused by: io.temporal.failure.ActivityFailure - indicates the execution failure of our activity * 3) Caused by: io.temporal.failure.ChildWorkflowFailure - indicates the failure of our child workflow execution * 4) io.temporal.client.WorkflowFailedException - indicates the failure of our workflow execution */ System.out.println("\nStack Trace:\n" + Throwables.getStackTraceAsString(e)); /* Now let's see if our original IOException was indeed propagated all the way to our * WorkflowException which we caught in our code. * To do this let's print out its root cause: */ Throwable cause = Throwables.getRootCause(e); // here we should get our originally thrown IOException and the message "Hello World" System.out.println("\n Root cause: " + cause.getMessage()); } System.exit(0); } } ================================================ FILE: core/src/main/java/io/temporal/samples/hello/HelloLocalActivity.java ================================================ package io.temporal.samples.hello; import io.temporal.activity.ActivityInterface; import io.temporal.activity.ActivityMethod; import io.temporal.activity.LocalActivityOptions; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import io.temporal.workflow.Workflow; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; import java.io.IOException; import java.time.Duration; /** * Hello World Temporal workflow that executes a single local activity. Requires a local instance * the Temporal service to be running. * *

Some of the Activities are very short lived and do not need the queuing semantic, flow * control, rate limiting and routing capabilities. For these Temporal supports so called local * Activity feature. Local Activities are executed in the same worker process as the Workflow that * invoked them. Consider using local Activities for functions that are: * *

* *

The main benefit of local Activities is that they are much more efficient in utilizing * Temporal service resources and have much lower latency overhead comparing to the usual Activity * invocation. */ public class HelloLocalActivity { static final String TASK_QUEUE = "HelloLocalActivity"; /** * The Workflow Definition's Interface must contain one method annotated with @WorkflowMethod. * *

Workflow Definitions should not contain any heavyweight computations, non-deterministic * code, network calls, database operations, etc. Those things should be handled by the * Activities. * * @see io.temporal.workflow.WorkflowInterface * @see io.temporal.workflow.WorkflowMethod */ @WorkflowInterface public interface GreetingWorkflow { @WorkflowMethod String getGreeting(String name); } /** Activity interface is just a POJO. */ @ActivityInterface public interface GreetingActivities { @ActivityMethod String composeGreeting(String greeting, String name); } /** GreetingWorkflow implementation that calls GreetingsActivities#composeGreeting. */ public static class GreetingWorkflowImpl implements GreetingWorkflow { /** * Activity stub implements activity interface and proxies calls to it to Temporal activity * invocations. Because activities are reentrant, only a single stub can be used for multiple * activity invocations. */ private final GreetingActivities activities = Workflow.newLocalActivityStub( GreetingActivities.class, LocalActivityOptions.newBuilder() .setStartToCloseTimeout(Duration.ofSeconds(2)) .build()); @Override public String getGreeting(String name) { // This is a blocking call that returns only after the activity has completed. return activities.composeGreeting("Hello", name); } } static class GreetingLocalActivityImpl implements GreetingActivities { @Override public String composeGreeting(String greeting, String name) { return greeting + " " + name + "!"; } } public static void main(String[] args) { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } // gRPC stubs wrapper that talks to the temporal service. WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); // client that can be used to start and signal workflows WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); // worker factory that can be used to create workers for specific task queues WorkerFactory factory = WorkerFactory.newInstance(client); // Worker that listens on a task queue and hosts both workflow and activity implementations. Worker worker = factory.newWorker(TASK_QUEUE); // Workflows are stateful. So you need a type to create instances. worker.registerWorkflowImplementationTypes(GreetingWorkflowImpl.class); // Activities are stateless and thread safe. So a shared instance is used. worker.registerActivitiesImplementations(new GreetingLocalActivityImpl()); // Start listening to the workflow and activity task queues. factory.start(); // Start a workflow execution. Usually this is done from another program. // Uses task queue from the GreetingWorkflow @WorkflowMethod annotation. GreetingWorkflow workflow = client.newWorkflowStub( GreetingWorkflow.class, WorkflowOptions.newBuilder().setTaskQueue(TASK_QUEUE).build()); // Execute a workflow waiting for it to complete. See {@link // io.temporal.samples.hello.HelloSignal} // for an example of starting workflow without waiting synchronously for its result. String greeting = workflow.getGreeting("World"); System.out.println(greeting); System.exit(0); } } ================================================ FILE: core/src/main/java/io/temporal/samples/hello/HelloParallelActivity.java ================================================ package io.temporal.samples.hello; import io.temporal.activity.ActivityInterface; import io.temporal.activity.ActivityOptions; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import io.temporal.workflow.*; import java.io.IOException; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** Sample Temporal workflow that executes multiple Activity methods in parallel. */ public class HelloParallelActivity { // Define the task queue name static final String TASK_QUEUE = "HelloParallelActivityTaskQueue"; // Define our workflow unique id static final String WORKFLOW_ID = "HelloParallelActivityWorkflow"; /** * The Workflow Definition's Interface must contain one method annotated with @WorkflowMethod. * *

Workflow Definitions should not contain any heavyweight computations, non-deterministic * code, network calls, database operations, etc. Those things should be handled by the * Activities. * * @see io.temporal.workflow.WorkflowInterface * @see io.temporal.workflow.WorkflowMethod */ @WorkflowInterface public interface MultiGreetingWorkflow { /** * This is the method that is executed when the Workflow Execution is started. The Workflow * Execution completes when this method finishes execution. */ @WorkflowMethod List getGreetings(List names); } /** * This is the Activity Definition's Interface. Activities are building blocks of any Temporal * Workflow and contain any business logic that could perform long running computation, network * calls, etc. * *

Annotating Activity Definition methods with @ActivityMethod is optional. * * @see io.temporal.activity.ActivityInterface * @see io.temporal.activity.ActivityMethod */ @ActivityInterface public interface GreetingActivities { // Define your activity method which can be called during workflow execution String composeGreeting(String greeting, String name); } /** Simple activity implementation, that concatenates two strings. */ static class GreetingActivitiesImpl implements GreetingActivities { @Override public String composeGreeting(String greeting, String name) { return greeting + " " + name + "!"; } } // Define the workflow implementation which implements our getGreeting workflow method. public static class MultiGreetingWorkflowImpl implements MultiGreetingWorkflow { /** * Define the GreetingActivities stub. Activity stubs are proxies for activity invocations that * are executed outside of the workflow thread on the activity worker, that can be on a * different host. Temporal is going to dispatch the activity results back to the workflow and * unblock the stub as soon as activity is completed on the activity worker. * *

In the {@link ActivityOptions} definition the "setStartToCloseTimeout" option sets the * overall timeout that our workflow is willing to wait for activity to complete. For this * example it is set to 2 seconds. */ private final GreetingActivities activities = Workflow.newActivityStub( GreetingActivities.class, ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(2)).build()); @Override public List getGreetings(List names) { List results = new ArrayList(); List> promiseList = new ArrayList<>(); if (names != null) { for (String name : names) { promiseList.add(Async.function(activities::composeGreeting, "Hello", name)); } // Invoke all activities in parallel. Wait for all to complete Promise.allOf(promiseList).get(); // Loop through promises and get results for (Promise promise : promiseList) { if (promise.getFailure() == null) { results.add(promise.get()); } } } return results; } } /** * With our Workflow and Activities defined, we can now start execution. The main method starts * the worker and then the workflow. */ public static void main(String[] args) { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } // Define the workflow service. WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); /* * Define the workflow factory. It is used to create workflow workers for a specific task queue. */ WorkerFactory factory = WorkerFactory.newInstance(client); /* * Define the workflow worker. Workflow workers listen to a defined task queue and process * workflows and activities. */ Worker worker = factory.newWorker(TASK_QUEUE); /* * Register our workflow implementation with the worker. * Workflow implementations must be known to the worker at runtime in * order to dispatch workflow tasks. */ worker.registerWorkflowImplementationTypes(MultiGreetingWorkflowImpl.class); /* * Register our Activity Types with the Worker. Since Activities are stateless and thread-safe, * the Activity Type is a shared instance. */ worker.registerActivitiesImplementations(new GreetingActivitiesImpl()); /* * Start all the workers registered for a specific task queue. * The started workers then start polling for workflows and activities. */ factory.start(); // Create the workflow client stub. It is used to start our workflow execution. MultiGreetingWorkflow workflow = client.newWorkflowStub( MultiGreetingWorkflow.class, WorkflowOptions.newBuilder() .setWorkflowId(WORKFLOW_ID) .setTaskQueue(TASK_QUEUE) .build()); /* * Execute our workflow and wait for it to complete. The call to our getGreetings method is * synchronous. * */ List results = workflow.getGreetings(Arrays.asList("John", "Mary", "Michael", "Jennet")); // Display workflow execution results for (String result : results) { System.out.println(result); } System.exit(0); } } ================================================ FILE: core/src/main/java/io/temporal/samples/hello/HelloPeriodic.java ================================================ package io.temporal.samples.hello; import io.temporal.activity.Activity; import io.temporal.activity.ActivityInterface; import io.temporal.activity.ActivityOptions; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowExecutionAlreadyStarted; import io.temporal.client.WorkflowOptions; import io.temporal.client.WorkflowStub; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import io.temporal.workflow.SignalMethod; import io.temporal.workflow.Workflow; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; import java.io.IOException; import java.time.Duration; import java.util.Random; /** * Sample Temporal workflow that demonstrates periodic workflow execution with a random delay. To * learn about periodic execution with a fixed delay (defined by a cron), check out the {@link * HelloCron} example. */ public class HelloPeriodic { // Define the task queue name static final String TASK_QUEUE = "HelloPeriodicTaskQueue"; // Define the workflow unique id static final String WORKFLOW_ID = "HelloPeriodicWorkflow"; /** * The Workflow Definition's Interface must contain one method annotated with @WorkflowMethod. * *

Workflow Definitions should not contain any heavyweight computations, non-deterministic * code, network calls, database operations, etc. Those things should be handled by the * Activities. * * @see io.temporal.workflow.WorkflowInterface * @see io.temporal.workflow.WorkflowMethod */ @WorkflowInterface public interface GreetingWorkflow { /** * This is the method that is executed when the Workflow Execution is started. The Workflow * Execution completes when this method finishes execution. */ @WorkflowMethod void greetPeriodically(String name); /** Users will invoke this signal when they want the main workflow loop to complete. */ @SignalMethod void requestExit(); } /** * This is the Activity Definition's Interface. Activities are building blocks of any Temporal * Workflow and contain any business logic that could perform long-running computation, network * calls, etc. * *

Annotating Activity Definition methods with @ActivityMethod is optional. * * @see io.temporal.activity.ActivityInterface * @see io.temporal.activity.ActivityMethod */ @ActivityInterface public interface GreetingActivities { // Define your activity method which can be called during workflow execution void greet(String greeting); } // Define the workflow implementation which implements the greetPeriodically workflow method. public static class GreetingWorkflowImpl implements GreetingWorkflow { // In this example, we use an internal of 5 seconds with an intended variation of +/- 1 second // between executions of some useful work. In real applications a higher value may be more // appropriate, for example one that matches a business cycle of several hours or even days. private static final int SCHEDULE_PERIOD_TARGET_SECS = 5; private static final int SCHEDULE_PERIOD_VARIATION_SECS = 2; // The max history length of a single Temporal workflow is 50,000 commands. // Therefore, a workflow cannot run indefinitely. Instead, we use // the ContinueAsNew feature to continue the execution as a new run // (same approach is used by Temporal's Cron-style scheduling system as well). // In real life, the complexity of the workflow affects when we need to flow // to a new run: I.e. if the workflow uses more Temporal commands per // iteration, then the history grows faster, and thus we can perform fewer // iterations before we must ContinueAsNew. For a simple workflow such as // this, we could perform many thousands of iterations. However, for // demonstration purposes we will flow to a new run more frequently. // More details: https://docs.temporal.io/docs/java/workflows/#large-event-histories private static final int SINGLE_WORKFLOW_ITERATIONS = 10; // Here we introduce a random delay between periodic executions. // Note that inside of workflow code 'Workflow.newRandom()' must always // be used to construct instances of the 'Random' class. private final Random random = Workflow.newRandom(); /** * Define the GreetingActivities stub. Activity stubs are proxies for activity invocations that * are executed outside the workflow thread on the activity worker, that can be on a different * host. Temporal is going to dispatch the activity results back to the workflow and unblock the * stub as soon as activity is completed on the activity worker. * *

In the {@link ActivityOptions} definition the "setStartToCloseTimeout" option sets the * maximum time of a single Activity execution attempt. For this example it is set to 10 * seconds. */ private final GreetingActivities activities = Workflow.newActivityStub( GreetingActivities.class, ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(10)).build()); private boolean exitRequested = false; @Override public void requestExit() { exitRequested = true; } @Override public void greetPeriodically(String name) { for (int i = 0; i < SINGLE_WORKFLOW_ITERATIONS; i++) { // Compute the timing of the next iteration: int delayMillis = (SCHEDULE_PERIOD_TARGET_SECS * 1000) + random.nextInt(SCHEDULE_PERIOD_VARIATION_SECS * 1000) - (SCHEDULE_PERIOD_VARIATION_SECS * 500); // Perform some useful work. In this example, we execute a greeting activity: activities.greet( "Hello " + name + "!" + " I will sleep for " + delayMillis + " milliseconds and then I will greet you again."); // Sleep for the required time period or until an exit signal is received: Workflow.await(Duration.ofMillis(delayMillis), () -> exitRequested); if (exitRequested) { activities.greet( "Hello " + name + "!" + " It was requested to quit the periodic greetings, so this the last one."); return; } } // Create a workflow stub that will be used to continue this workflow as a new run: // (see the comment for 'SingleWorkflowRunIterations' for details) GreetingWorkflow continueAsNew = Workflow.newContinueAsNewStub(GreetingWorkflow.class); // Request that the new run will be invoked by the Temporal system: continueAsNew.greetPeriodically(name); } } /** * Implementation of our workflow activity interface. It overwrites our defined greet activity * method. */ static class GreetingActivitiesImpl implements GreetingActivities { @Override public void greet(String greeting) { System.out.println( "From " + Activity.getExecutionContext().getInfo().getWorkflowId() + ": " + greeting); } } /** * With our Workflow and Activities defined, we can now start execution. The main method starts * the worker and then the workflow. */ @SuppressWarnings( "CatchAndPrintStackTrace") // in this simple example advanced error logging is not required public static void main(String[] args) throws InterruptedException { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } // Define the workflow service. WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); /* * Define the workflow factory. It is used to create workflow workers for a specific task queue. */ WorkerFactory factory = WorkerFactory.newInstance(client); /* * Define the workflow worker. Workflow workers listen to a defined task queue and process * workflows and activities. */ Worker worker = factory.newWorker(TASK_QUEUE); /* * Register our workflow implementation with the worker. * Workflow implementations must be known to the worker at runtime in * order to dispatch workflow tasks. */ worker.registerWorkflowImplementationTypes(GreetingWorkflowImpl.class); /* * Register our Activity Types with the Worker. Since Activities are stateless and thread-safe, * the Activity Type is a shared instance. */ worker.registerActivitiesImplementations(new GreetingActivitiesImpl()); /* * Start all the workers registered for a specific task queue. * The started workers then start polling for workflows and activities. */ factory.start(); // Create the workflow client stub. It is used to start our workflow execution. GreetingWorkflow workflow = client.newWorkflowStub( GreetingWorkflow.class, // At most one instance. WorkflowOptions.newBuilder() .setWorkflowId(WORKFLOW_ID) .setTaskQueue(TASK_QUEUE) .build()); // Execute our workflow. try { WorkflowClient.start(workflow::greetPeriodically, "World"); System.out.println("Started a new GreetingWorkflow."); } catch (WorkflowExecutionAlreadyStarted e) { // If the workflow is already running, we cannot start it. Instead, we will connect to the // existing instance. workflow = client.newWorkflowStub(GreetingWorkflow.class, WORKFLOW_ID); System.out.println("Connected to an existing GreetingWorkflow."); } // The workflow is running now. In this example, we pause for a few seconds to observe its // output. final int ObservationPeriodSecs = 20; System.out.println( "Observing the workflow execution for " + ObservationPeriodSecs + " seconds."); try { Thread.sleep(ObservationPeriodSecs * 1000); } catch (InterruptedException intEx) { intEx.printStackTrace(); } // Signal the workflow to exit. System.out.println("Requesting the workflow to exit."); workflow.requestExit(); // Allow the workflow to finish before the worker is shut down. WorkflowStub.fromTyped(workflow).getResult(void.class); System.out.println("Good bye."); System.exit(0); } } ================================================ FILE: core/src/main/java/io/temporal/samples/hello/HelloPolymorphicActivity.java ================================================ package io.temporal.samples.hello; import io.temporal.activity.ActivityInterface; import io.temporal.activity.ActivityOptions; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import io.temporal.workflow.Workflow; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; import java.io.IOException; import java.time.Duration; /** * Sample Temporal Workflow Definition that demonstrates the execution of multiple Activities which * extend a common interface. */ public class HelloPolymorphicActivity { // Define the task queue name static final String TASK_QUEUE = "HelloPolymorphicActivityTaskQueue"; // Define the workflow unique id static final String WORKFLOW_ID = "HelloPolymorphicActivityWorkflow"; /** * The Workflow Definition's Interface must contain one method annotated with @WorkflowMethod. * *

Workflow Definitions should not contain any heavyweight computations, non-deterministic * code, network calls, database operations, etc. Those things should be handled by the * Activities. * * @see io.temporal.workflow.WorkflowInterface * @see io.temporal.workflow.WorkflowMethod */ @WorkflowInterface public interface GreetingWorkflow { /** * This is the method that is executed when the Workflow Execution is started. The Workflow * Execution completes when this method finishes execution. */ @WorkflowMethod String getGreeting(String name); } // Define the base interface for the two workflow activities // Note it is not annotated with @ActivityInterface public interface GreetingActivity { String composeGreeting(String name); } /** * Define the first activity interface. Workflow methods can call activities during execution. * Annotating activity methods with @ActivityMethod is optional * *

Note the activity interface extends the base GreetingActivity interface. Also note that in * order to void the collisions in the activity name (which is by default the name of the activity * method) we set the namePrefix annotation parameter. * * @see io.temporal.activity.ActivityInterface * @see io.temporal.activity.ActivityMethod */ @ActivityInterface(namePrefix = "Hello_") public interface HelloActivity extends GreetingActivity { @Override String composeGreeting(String name); } /** * Define the second activity interface. Workflow methods can call activities during execution. * Annotating activity methods with @ActivityMethod is optional * *

Note that the activity interface extends the base GreetingActivity interface. Also note that * in order to void the collisions in the activity name (which is by default the name of the * activity method) we set the namePrefix annotation parameter. * * @see io.temporal.activity.ActivityInterface * @see io.temporal.activity.ActivityMethod */ @ActivityInterface(namePrefix = "Bye_") public interface ByeActivity extends GreetingActivity { @Override String composeGreeting(String name); } // Define the workflow implementation which implements the getGreeting workflow method. public static class GreetingWorkflowImpl implements GreetingWorkflow { /** * Define the GreetingActivities stub. Activity stubs are proxies for activity invocations that * are executed outside of the workflow thread on the activity worker, that can be on a * different host. Temporal is going to dispatch the activity results back to the workflow and * unblock the stub as soon as activity is completed on the activity worker. * *

For this example we define two activity stubs, one for each of the defined activities. * *

In the {@link ActivityOptions} definition the "setStartToCloseTimeout" option sets the * maximum time of a single Activity execution attempt. For this example it is set to 2 seconds. */ private final GreetingActivity[] activities = new GreetingActivity[] { Workflow.newActivityStub( HelloActivity.class, ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(2)).build()), Workflow.newActivityStub( ByeActivity.class, ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(2)).build()) }; @Override public String getGreeting(String name) { StringBuilder result = new StringBuilder(); /* * Call the composeGreeting activity method * for each of our two activities. * Notice how you can use the common activities interface for each. * * Append the result of each of the activity invocation results and return it. */ for (GreetingActivity activity : activities) { result.append(activity.composeGreeting(name)); result.append('\n'); } return result.toString(); } } // Hello workflow activity implementation static class HelloActivityImpl implements HelloActivity { @Override public String composeGreeting(String name) { return "Hello " + name + "!"; } } // Bye workflow activity implementation static class ByeActivityImpl implements ByeActivity { @Override public String composeGreeting(String name) { return "Bye " + name + "!"; } } /** * With our Workflow and Activities defined, we can now start execution. The main method starts * the worker and then the workflow. */ public static void main(String[] args) { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } // Define the workflow service. WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); /* * Define the workflow factory. It is used to create workflow workers for a specific task queue. */ WorkerFactory factory = WorkerFactory.newInstance(client); /* * Define the workflow worker. Workflow workers listen to a defined task queue and process * workflows and activities. */ Worker worker = factory.newWorker(TASK_QUEUE); /* * Register our workflow implementation with the worker. * Workflow implementations must be known to the worker at runtime in * order to dispatch workflow tasks. */ worker.registerWorkflowImplementationTypes(GreetingWorkflowImpl.class); /* Register our workflow activities implementations with the worker. Since workflow activities are stateless and thread-safe, we need to register a shared instance. */ worker.registerActivitiesImplementations(new HelloActivityImpl(), new ByeActivityImpl()); /* * Start all the workers registered for a specific task queue. * The started workers then start polling for workflows and activities. */ factory.start(); // Create the workflow client stub. It is used to start our workflow execution. GreetingWorkflow workflow = client.newWorkflowStub( GreetingWorkflow.class, WorkflowOptions.newBuilder() .setWorkflowId(WORKFLOW_ID) .setTaskQueue(TASK_QUEUE) .build()); /* * Execute our workflow and wait for it to complete. The call to our getGreeting method is * synchronous. * * See {@link io.temporal.samples.hello.HelloSignal} for an example of starting workflow * without waiting synchronously for its result. */ String greeting = workflow.getGreeting("World"); // Print the workflow results. It should contain the results // of both of our defined activities System.out.println(greeting); System.exit(0); } } ================================================ FILE: core/src/main/java/io/temporal/samples/hello/HelloQuery.java ================================================ package io.temporal.samples.hello; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import io.temporal.workflow.QueryMethod; import io.temporal.workflow.Workflow; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; import java.io.IOException; import java.time.Duration; /** Sample Temporal Workflow Definition that demonstrates how to Query a Workflow. */ public class HelloQuery { // Define the task queue name static final String TASK_QUEUE = "HelloQueryTaskQueue"; // Define our workflow unique id static final String WORKFLOW_ID = "HelloQueryWorkflow"; /** * The Workflow Definition's Interface must contain one method annotated with @WorkflowMethod. * *

Workflow Definitions should not contain any heavyweight computations, non-deterministic * code, network calls, database operations, etc. Those things should be handled by the * Activities. * * @see io.temporal.workflow.WorkflowInterface * @see io.temporal.workflow.WorkflowMethod */ @WorkflowInterface public interface GreetingWorkflow { @WorkflowMethod void createGreeting(String name); // Workflow query method. Used to return our greeting as a query value @QueryMethod String queryGreeting(); } // Define the workflow implementation which implements our createGreeting and // queryGreeting workflow methods. public static class GreetingWorkflowImpl implements GreetingWorkflow { private String greeting; @Override public void createGreeting(String name) { // We set the value of greeting to "Hello" first. greeting = "Hello " + name + "!"; /* * Note that our createGreeting workflow method has return type of void. * It only sets the greeting and does not return it. * * Also note that inside a workflow method you should always * use Workflow.sleep or Workflow.currentTimeMillis rather than the * equivalent standard Java ones. */ Workflow.sleep(Duration.ofSeconds(2)); // after two seconds we change the value of our greeting to "Bye" greeting = "Bye " + name + "!"; } // our workflow query method returns the greeting @Override public String queryGreeting() { return greeting; } } /** * With our Workflow and Activities defined, we can now start execution. The main method starts * the worker and then the workflow. */ public static void main(String[] args) throws InterruptedException { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } // Define the workflow service. WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); /* * Define the workflow factory. It is used to create workflow workers for a specific task queue. */ WorkerFactory factory = WorkerFactory.newInstance(client); /* * Define the workflow worker. Workflow workers listen to a defined task queue and process * workflows and activities. */ Worker worker = factory.newWorker(TASK_QUEUE); /* * Register our workflow implementation with the worker. * Workflow implementations must be known to the worker at runtime in * order to dispatch workflow tasks. */ worker.registerWorkflowImplementationTypes(GreetingWorkflowImpl.class); /* * Start all the workers registered for a specific task queue. * The started workers then start polling for workflows and activities. */ factory.start(); // Create our workflow options WorkflowOptions workflowOptions = WorkflowOptions.newBuilder().setWorkflowId(WORKFLOW_ID).setTaskQueue(TASK_QUEUE).build(); // Create the workflow client stub. It is used to start our workflow execution. GreetingWorkflow workflow = client.newWorkflowStub(GreetingWorkflow.class, workflowOptions); // Start our workflow asynchronously to not use another thread to query. WorkflowClient.start(workflow::createGreeting, "World"); // After start for getGreeting returns, the workflow is guaranteed to be started. // So we can send a signal to it using workflow stub. /* * Query our workflow to get the current value of greeting. * Remember that original the workflow methods sets this value to "Hello" * So here we should get "Hello World". */ System.out.println(workflow.queryGreeting()); /* * Sleep for 2.5 seconds. This value is set because remember in our * workflow method the value of the greeting is updated after 2 seconds. * * Also note since here we are not inside a Workflow method, we can use the * standard Java Thread.sleep. */ Thread.sleep(2500); /* * Query our workflow to get the current value of greeting. * * Now we should get "Bye World". */ System.out.println(workflow.queryGreeting()); System.exit(0); } } ================================================ FILE: core/src/main/java/io/temporal/samples/hello/HelloSaga.java ================================================ package io.temporal.samples.hello; import io.temporal.activity.ActivityInterface; import io.temporal.activity.ActivityMethod; import io.temporal.activity.ActivityOptions; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import io.temporal.workflow.Async; import io.temporal.workflow.Promise; import io.temporal.workflow.Saga; import io.temporal.workflow.Workflow; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; import java.io.IOException; import java.time.Duration; /** * Sample Temporal workflow that demonstrates the workflow compensation capability. * *

Compensation deals with undoing or reversing work which has already successfully completed. * (also called SAGA). Temporal includes very powerful support for compensation which is showedcased * in this example. * * @see io.temporal.samples.bookingsaga.TripBookingSaga for another SAGA example. */ public class HelloSaga { // Define the task queue name static final String TASK_QUEUE = "HelloSagaTaskQueue"; // Define the workflow unique id static final String WORKFLOW_ID = "HelloSagaTaskWorkflow"; /** * Define the child workflow interface. It must contain one method annotated with @WorkflowMethod * * @see io.temporal.workflow.WorkflowInterface * @see io.temporal.workflow.WorkflowMethod */ @WorkflowInterface public interface ChildWorkflowOperation { /** * Define the child workflow method. This method is executed when the child workflow is started. * The child workflow completes when the workflow method finishes execution. */ @WorkflowMethod void execute(int amount); } // Define the child workflow implementation. It implements the execute workflow method public static class ChildWorkflowOperationImpl implements ChildWorkflowOperation { /* * Define the ActivityOperation stub. Activity stubs are proxies for activity invocations that * are executed outside of the workflow thread on the activity worker, that can be on a * different host. Temporal is going to dispatch the activity results back to the workflow and * unblock the stub as soon as activity is completed on the activity worker. * *

In the {@link ActivityOptions} definition the "setStartToCloseTimeout" option sets the * maximum time of a single Activity execution attempt. For this example it is set to 10 * seconds. */ ActivityOperation activity = Workflow.newActivityStub( ActivityOperation.class, ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(10)).build()); @Override public void execute(int amount) { activity.execute(amount); } } /** * Define the child workflow compensation interface. It must contain one method annotated * with @WorkflowMethod * * @see io.temporal.workflow.WorkflowInterface * @see io.temporal.workflow.WorkflowMethod */ @WorkflowInterface public interface ChildWorkflowCompensation { /** * Define the child workflow compensation method. This method is executed when the child * workflow is started. The child workflow completes when the workflow method finishes * execution. */ @WorkflowMethod void compensate(int amount); } // Define the child workflow compensation implementation. It implements the compensate child // workflow method public static class ChildWorkflowCompensationImpl implements ChildWorkflowCompensation { /* * Define the ActivityOperation stub. Activity stubs are proxies for activity invocations that * are executed outside of the workflow thread on the activity worker, that can be on a * different host. Temporal is going to dispatch activity results back to the workflow and * unblock the stub as soon as activity is completed on the activity worker. * *

In the {@link ActivityOptions} definition the"setStartToCloseTimeout" option sets the * maximum time of a single Activity execution attempt. For this example it is set to 10 * seconds. */ ActivityOperation activity = Workflow.newActivityStub( ActivityOperation.class, ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(10)).build()); @Override public void compensate(int amount) { activity.compensate(amount); } } /** * This is the Activity Definition's Interface. Activities are building blocks of any Temporal * Workflow and contain any business logic that could perform long running computation, network * calls, etc. * *

Annotating Activity Definition methods with @ActivityMethod is optional. * * @see io.temporal.activity.ActivityInterface * @see io.temporal.activity.ActivityMethod */ @ActivityInterface public interface ActivityOperation { @ActivityMethod void execute(int amount); @ActivityMethod void compensate(int amount); } /** * Implementation of the workflow activity interface. It overwrites the defined execute and * compensate activity methods. */ public static class ActivityOperationImpl implements ActivityOperation { @Override public void execute(int amount) { System.out.println("ActivityOperationImpl.execute() is called with amount " + amount); } @Override public void compensate(int amount) { System.out.println("ActivityCompensationImpl.compensate() is called with amount " + amount); } } /** * Define the main workflow interface. It must contain one method annotated with @WorkflowMethod * * @see io.temporal.workflow.WorkflowInterface * @see io.temporal.workflow.WorkflowMethod */ @WorkflowInterface public interface SagaWorkflow { /** * This is the method that is executed when the Workflow Execution is started. The Workflow * Execution completes when this method finishes execution. */ @WorkflowMethod void execute(); } // Define the main workflow implementation. It implements the execute workflow method public static class SagaWorkflowImpl implements SagaWorkflow { /* * Define the ActivityOperation stub. Activity stubs are proxies for activity invocations that * are executed outside of the workflow thread on the activity worker, that can be on a * different host. Temporal is going to dispatch activity results back to the workflow and * unblock the stub as soon as activity is completed on the activity worker. * *

In the {@link ActivityOptions} definition the "setStartToCloseTimeout" option sets the * maximum time of a single Activity execution attempt. For this example it is set to 2 seconds. */ ActivityOperation activity = Workflow.newActivityStub( ActivityOperation.class, ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(2)).build()); @Override public void execute() { // {@link io.temporal.workflow.Saga} implements the logic to perform compensation operations Saga saga = new Saga(new Saga.Options.Builder().setParallelCompensation(false).build()); try { /* * First we show how to compensate sync child workflow invocations. We first create a child * workflow stub and execute its "execute" method. Then we create a stub of the child * compensation workflow and register it with Saga. At this point this compensation workflow * is not invoked. It is invoked explicitly when we actually want to invoke compensation * (via saga.compensate()). */ ChildWorkflowOperation op1 = Workflow.newChildWorkflowStub(ChildWorkflowOperation.class); op1.execute(10); ChildWorkflowCompensation c1 = Workflow.newChildWorkflowStub(ChildWorkflowCompensation.class); saga.addCompensation(c1::compensate, -10); /* * Now we show compensation of workflow activities which are invoked asynchronously. We * invoke the activity "execute" method async. Then we register its "compensate" method as * the compensation method for it. * *

Again note that the compensation of this activity again is only explicitly invoked * (via saga.compensate()). */ Promise result = Async.procedure(activity::execute, 20); saga.addCompensation(activity::compensate, -20); // get the result of the activity (blocking) result.get(); /* * You can also supply an arbitrary lambda expression as a saga * compensation function. * Note that this compensation function is not associated with a child workflow * method or an activity method. It is associated with the currently executing * workflow method. * * Also note that here in this example we use System.out in the main workflow logic. * In production make sure to use Workflow.getLogger to log messages from workflow code. */ saga.addCompensation( () -> System.out.println("Other compensation logic in main workflow.")); /* * Here we throw a runtime exception on purpose to showcase * how to trigger compensation in case of an exception. * Note that compensation can be also triggered * without a specific exception being thrown. You can built in * compensation to be part of your core workflow business requirements, * meaning it can be triggered as part of your business logic. */ throw new RuntimeException("some error"); } catch (Exception e) { // we catch our exception and trigger workflow compensation saga.compensate(); } } } /** * With our Workflow and Activities defined, we can now start execution. The main method starts * the worker and then the workflow. */ public static void main(String[] args) { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } // Define the workflow service. WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); /* * Define the workflow factory. It is used to create workflow workers for a specific task queue. */ WorkerFactory factory = WorkerFactory.newInstance(client); /* * Define the workflow worker. Workflow workers listen to a defined task queue and process * workflows and activities. */ Worker worker = factory.newWorker(TASK_QUEUE); /* * Register our workflow implementations with the worker. Since workflows are stateful in nature, * we need to register our workflow types. */ worker.registerWorkflowImplementationTypes( HelloSaga.SagaWorkflowImpl.class, HelloSaga.ChildWorkflowOperationImpl.class, HelloSaga.ChildWorkflowCompensationImpl.class); /* * Register our Activity Types with the Worker. Since Activities are stateless and thread-safe, * the Activity Type is a shared instance. */ worker.registerActivitiesImplementations(new ActivityOperationImpl()); /* * Start all the workers registered for a specific task queue. * The started workers then start polling for workflows and activities. */ factory.start(); // Create our workflow options WorkflowOptions workflowOptions = WorkflowOptions.newBuilder().setWorkflowId(WORKFLOW_ID).setTaskQueue(TASK_QUEUE).build(); // Create the workflow client stub. It is used to start our workflow execution. HelloSaga.SagaWorkflow workflow = client.newWorkflowStub(HelloSaga.SagaWorkflow.class, workflowOptions); // Execute our workflow workflow.execute(); System.exit(0); } } ================================================ FILE: core/src/main/java/io/temporal/samples/hello/HelloSchedules.java ================================================ package io.temporal.samples.hello; import io.temporal.activity.Activity; import io.temporal.activity.ActivityInterface; import io.temporal.activity.ActivityOptions; import io.temporal.api.common.v1.Payload; import io.temporal.api.enums.v1.ScheduleOverlapPolicy; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.client.schedules.*; import io.temporal.common.converter.GlobalDataConverter; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import io.temporal.workflow.Workflow; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; import java.io.IOException; import java.time.Duration; import java.time.Instant; import java.util.Collections; /** * Sample Temporal workflow that demonstrates periodic workflow execution using a schedule. Schedule * is a new feature in Temporal designed to replace Cron workflows. Schedules allow for greater * control over when workflows are run and how they are run. */ public class HelloSchedules { // Define the task queue name static final String TASK_QUEUE = "HelloScheduleTaskQueue"; // Define the workflow unique id static final String WORKFLOW_ID = "HelloScheduleWorkflow"; // Define the schedule unique id static final String SCHEDULE_ID = "HelloSchedule"; /** * The Workflow Definition's Interface must contain one method annotated with @WorkflowMethod. * *

Workflow Definitions should not contain any heavyweight computations, non-deterministic * code, network calls, database operations, etc. Those things should be handled by the * Activities. * * @see WorkflowInterface * @see WorkflowMethod */ @WorkflowInterface public interface GreetingWorkflow { /** * This is the method that is executed when the Workflow Execution is started. The Workflow * Execution completes when this method finishes execution. */ @WorkflowMethod void greet(String name); } /** * This is the Activity Definition's Interface. Activities are building blocks of any Temporal * Workflow and contain any business logic that could perform long running computation, network * calls, etc. * *

Annotating Activity Definition methods with @ActivityMethod is optional. * * @see ActivityInterface * @see io.temporal.activity.ActivityMethod */ @ActivityInterface public interface GreetingActivities { // Define your activity method which can be called during workflow execution void greet(String greeting); } // Define the workflow implementation which implements the greet workflow method. public static class GreetingWorkflowImpl implements GreetingWorkflow { /** * Define the GreetingActivities stub. Activity stubs are proxies for activity invocations that * are executed outside of the workflow thread on the activity worker, that can be on a * different host. Temporal is going to dispatch the activity results back to the workflow and * unblock the stub as soon as activity is completed on the activity worker. * *

In the {@link ActivityOptions} definition the "setStartToCloseTimeout" option sets the * maximum time of a single Activity execution attempt. For this example it is set to 10 * seconds. */ private final GreetingActivities activities = Workflow.newActivityStub( GreetingActivities.class, ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(10)).build()); @Override public void greet(String name) { // Workflow Executions started by a Schedule have the following // additional properties appended to their search attributes. Payload scheduledByIDPayload = Workflow.getInfo().getSearchAttributes().getIndexedFieldsOrThrow("TemporalScheduledById"); String scheduledByID = GlobalDataConverter.get().fromPayload(scheduledByIDPayload, String.class, String.class); Payload startTimePayload = Workflow.getInfo() .getSearchAttributes() .getIndexedFieldsOrThrow("TemporalScheduledStartTime"); Instant startTime = GlobalDataConverter.get().fromPayload(startTimePayload, Instant.class, Instant.class); activities.greet( "Hello " + name + " from " + scheduledByID + " scheduled at " + startTime + "!"); } } /** * Implementation of the workflow activity interface. It overwrites the defined greet activity * method. */ static class GreetingActivitiesImpl implements GreetingActivities { @Override public void greet(String greeting) { System.out.println( "From " + Activity.getExecutionContext().getInfo().getWorkflowId() + ": " + greeting); } } /** * With the Workflow and Activities defined, we can now start execution. The main method starts * the worker and then the workflow. */ public static void main(String[] args) throws InterruptedException { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } // Get a Workflow service stub. WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); /* * Define the workflow factory. It is used to create workflow workers for a specific task queue. */ WorkerFactory factory = WorkerFactory.newInstance(client); /* * Define the workflow worker. Workflow workers listen to a defined task queue and process * workflows and activities. */ Worker worker = factory.newWorker(TASK_QUEUE); /* * Register the workflow implementation with the worker. * Workflow implementations must be known to the worker at runtime in * order to dispatch workflow tasks. */ worker.registerWorkflowImplementationTypes(GreetingWorkflowImpl.class); /* * Register the workflow activity implementation with the worker. Since workflow activities are * stateless and thread-safe, we need to register a shared instance. */ worker.registerActivitiesImplementations(new GreetingActivitiesImpl()); /* * Start all the workers registered for a specific task queue. * The started workers then start polling for workflows and activities. */ factory.start(); /* * Get a Schedule client which can be used to interact with schedule. */ ScheduleClient scheduleClient = ScheduleClient.newInstance(service); /* * Create the workflow options for our schedule. * Note: Not all workflow options are supported for schedules. */ WorkflowOptions workflowOptions = WorkflowOptions.newBuilder().setWorkflowId(WORKFLOW_ID).setTaskQueue(TASK_QUEUE).build(); /* * Create the action that will be run when the schedule is triggered. */ ScheduleActionStartWorkflow action = ScheduleActionStartWorkflow.newBuilder() .setWorkflowType(HelloSchedules.GreetingWorkflow.class) .setArguments("World") .setOptions(workflowOptions) .build(); // Define the schedule we want to create Schedule schedule = Schedule.newBuilder().setAction(action).setSpec(ScheduleSpec.newBuilder().build()).build(); // Create a schedule on the server ScheduleHandle handle = scheduleClient.createSchedule(SCHEDULE_ID, schedule, ScheduleOptions.newBuilder().build()); // Manually trigger the schedule once handle.trigger(ScheduleOverlapPolicy.SCHEDULE_OVERLAP_POLICY_ALLOW_ALL); // Update the schedule with a spec, so it will run periodically handle.update( (ScheduleUpdateInput input) -> { Schedule.Builder builder = Schedule.newBuilder(input.getDescription().getSchedule()); builder.setSpec( ScheduleSpec.newBuilder() // Run the schedule at 5pm on Friday .setCalendars( Collections.singletonList( ScheduleCalendarSpec.newBuilder() .setHour(Collections.singletonList(new ScheduleRange(17))) .setDayOfWeek(Collections.singletonList(new ScheduleRange(5))) .build())) // Run the schedule every 5s .setIntervals( Collections.singletonList(new ScheduleIntervalSpec(Duration.ofSeconds(5)))) .build()); // Make the schedule paused to demonstrate how to unpause a schedule builder.setState( ScheduleState.newBuilder() .setPaused(true) .setLimitedAction(true) .setRemainingActions(10) .build()); return new ScheduleUpdate(builder.build()); }); // Unpause schedule handle.unpause(); // Wait for the schedule to run 10 actions while (true) { ScheduleState state = handle.describe().getSchedule().getState(); if (state.getRemainingActions() == 0) { break; } Thread.sleep(5000); } // Delete the schedule once the sample is done handle.delete(); System.exit(0); } } ================================================ FILE: core/src/main/java/io/temporal/samples/hello/HelloSearchAttributes.java ================================================ package io.temporal.samples.hello; import io.temporal.activity.ActivityInterface; import io.temporal.activity.ActivityMethod; import io.temporal.activity.ActivityOptions; import io.temporal.api.common.v1.Payload; import io.temporal.api.common.v1.SearchAttributes; import io.temporal.api.common.v1.WorkflowExecution; import io.temporal.api.workflowservice.v1.DescribeWorkflowExecutionRequest; import io.temporal.api.workflowservice.v1.DescribeWorkflowExecutionResponse; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.common.converter.DataConverter; import io.temporal.common.converter.GlobalDataConverter; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import io.temporal.workflow.Workflow; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; import java.io.IOException; import java.time.Duration; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.HashMap; import java.util.Map; /** * Sample Temporal workflow that demonstrates setting up and retrieving workflow search attributes. */ public class HelloSearchAttributes { // Define the task queue name static final String TASK_QUEUE = "HelloSearchAttributesTaskQueue"; // Define our workflow unique id static final String WORKFLOW_ID = "HelloSearchAttributesWorkflow"; /** * The Workflow Definition's Interface must contain one method annotated with @WorkflowMethod. * *

Workflow Definitions should not contain any heavyweight computations, non-deterministic * code, network calls, database operations, etc. Those things should be handled by the * Activities. * * @see io.temporal.workflow.WorkflowInterface * @see io.temporal.workflow.WorkflowMethod */ @WorkflowInterface public interface GreetingWorkflow { /** * This is the method that is executed when the Workflow Execution is started. The Workflow * Execution completes when this method finishes execution. */ @WorkflowMethod String getGreeting(String name); } /** * This is the Activity Definition's Interface. Activities are building blocks of any Temporal * Workflow and contain any business logic that could perform long running computation, network * calls, etc. * *

Annotating Activity Definition methods with @ActivityMethod is optional. * * @see io.temporal.activity.ActivityInterface * @see io.temporal.activity.ActivityMethod */ @ActivityInterface public interface GreetingActivities { @ActivityMethod String composeGreeting(String greeting, String name); } // Define the workflow implementation which implements our getGreeting workflow method. public static class GreetingWorkflowImpl implements GreetingWorkflow { /** * Define the GreetingActivities stub. Activity stubs implement activity interfaces and proxy * calls to it to Temporal activity invocations. Since Temporal activities are reentrant, a * single activity stub can be used for multiple activity invocations. * *

In the {@link ActivityOptions} definition the "setStartToCloseTimeout" option sets the * maximum time of a single Activity execution attempt. For this example it is set to 2 seconds. */ private final GreetingActivities activities = Workflow.newActivityStub( GreetingActivities.class, ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(2)).build()); @Override public String getGreeting(String name) { // This is a blocking call that returns only after the activity has completed. return activities.composeGreeting("Hello", name); } } /** * Implementation of our workflow activity interface. It overwrites our defined composeGreeting * activity method. */ static class GreetingActivitiesImpl implements GreetingActivities { @Override public String composeGreeting(String greeting, String name) { return greeting + " " + name + "!"; } } /** * With our Workflow and Activities defined, we can now start execution. The main method starts * the worker and then the workflow. */ public static void main(String[] args) { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } // Define the workflow service. WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); /* * Define the workflow factory. It is used to create workflow workers for a specific task queue. */ WorkerFactory factory = WorkerFactory.newInstance(client); /* * Define the workflow worker. Workflow workers listen to a defined task queue and process * workflows and activities. */ Worker worker = factory.newWorker(TASK_QUEUE); /* * Register our workflow implementation with the worker. * Workflow implementations must be known to the worker at runtime in * order to dispatch workflow tasks. */ worker.registerWorkflowImplementationTypes(HelloSearchAttributes.GreetingWorkflowImpl.class); /* * Register our Activity Types with the Worker. Since Activities are stateless and thread-safe, * the Activity Type is a shared instance. */ worker.registerActivitiesImplementations(new HelloSearchAttributes.GreetingActivitiesImpl()); /* * Start all the workers registered for a specific task queue. * The started workers then start polling for workflows and activities. */ factory.start(); // Set our workflow options. // Note that we set our search attributes here WorkflowOptions workflowOptions = WorkflowOptions.newBuilder() .setWorkflowId(WORKFLOW_ID) .setTaskQueue(TASK_QUEUE) .setSearchAttributes(generateSearchAttributes()) .build(); // Create the workflow client stub. It is used to start our workflow execution. HelloSearchAttributes.GreetingWorkflow workflow = client.newWorkflowStub(HelloSearchAttributes.GreetingWorkflow.class, workflowOptions); // Execute a workflow waiting for it to complete. String greeting = workflow.getGreeting("SearchAttributes"); // Get the workflow execution for the same id as our defined workflow WorkflowExecution execution = WorkflowExecution.newBuilder().setWorkflowId(WORKFLOW_ID).build(); // Create the DescribeWorkflowExecutionRequest through which we can query our client for our // search queries DescribeWorkflowExecutionRequest request = DescribeWorkflowExecutionRequest.newBuilder() .setNamespace(client.getOptions().getNamespace()) .setExecution(execution) .build(); try { // Get the DescribeWorkflowExecutionResponse from our service DescribeWorkflowExecutionResponse resp = service.blockingStub().describeWorkflowExecution(request); // get all search attributes SearchAttributes searchAttributes = resp.getWorkflowExecutionInfo().getSearchAttributes(); // Get the specific value of a keyword from the payload. // In this case it is the "CustomKeywordField" with the value of "keys" // You can update the code to extract other defined search attribute as well String keyword = getKeywordFromSearchAttribute(searchAttributes, "CustomKeywordField"); // Print the value of the "CustomKeywordField" field System.out.printf("In workflow we get CustomKeywordField is: %s\n", keyword); } catch (Exception e) { System.out.println(e); } // Print the workflow execution results System.out.println(greeting); System.exit(0); } // Generate our example search option private static Map generateSearchAttributes() { Map searchAttributes = new HashMap<>(); searchAttributes.put( "CustomKeywordField", "keys"); // each field can also be array such as: String[] keys = {"k1", "k2"}; searchAttributes.put("CustomIntField", 1); searchAttributes.put("CustomDoubleField", 0.1); searchAttributes.put("CustomBoolField", true); searchAttributes.put("CustomDatetimeField", generateDateTimeFieldValue()); searchAttributes.put( "CustomStringField", "String field is for text. When query, it will be tokenized for partial match. StringTypeField cannot be used in Order By"); return searchAttributes; } // CustomDatetimeField takes times encoded in the RFC 3339 format. private static String generateDateTimeFieldValue() { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssXXX"); return ZonedDateTime.now(ZoneId.systemDefault()).format(formatter); } // example for extracting a value from search attributes static String getKeywordFromSearchAttribute(SearchAttributes searchAttributes, String key) { Payload field = searchAttributes.getIndexedFieldsOrThrow(key); DataConverter dataConverter = GlobalDataConverter.get(); return dataConverter.fromPayload(field, String.class, String.class); } } ================================================ FILE: core/src/main/java/io/temporal/samples/hello/HelloSideEffect.java ================================================ package io.temporal.samples.hello; import io.temporal.activity.ActivityInterface; import io.temporal.activity.ActivityOptions; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import io.temporal.workflow.QueryMethod; import io.temporal.workflow.Workflow; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; import java.io.IOException; import java.security.SecureRandom; import java.time.Duration; import java.util.Random; import java.util.UUID; /** * Sample Temporal workflow that shows use of workflow SideEffect. * *

Workflow methods must be deterministic. In order to execute non-deterministic code, such as * random number generation as shown in this example, you should use Workflow.SideEffect. * Workflow.SideEffect is typically used for very quick-running operations, where as Workflow * Activities or Local Activities, which can also execute non-deterministic code, are meant for more * expensive operations. * *

Note: you should not use SideEffect function to modify the workflow state. For that you should * only use the SideEffect's return value! */ public class HelloSideEffect { // Define the task queue name static final String TASK_QUEUE = "HelloSideEffectTaskQueue"; // Define our workflow unique id static final String WORKFLOW_ID = "HelloSideEffectTaskWorkflow"; /** * The Workflow Definition's Interface must contain one method annotated with @WorkflowMethod. * *

Workflow code includes core processing logic. It shouldn't contain any heavyweight * computations, non-deterministic code, network calls, database operations, etc. All those things * should be handled by Activities. * * @see io.temporal.workflow.WorkflowInterface * @see io.temporal.workflow.WorkflowMethod */ @WorkflowInterface public interface SideEffectWorkflow { /** * This is the method that is executed when the Workflow Execution is started. The Workflow * Execution completes when this method finishes execution. */ @WorkflowMethod String execute(); @QueryMethod String getResult(); } /** * This is the Activity Definition's Interface. Activities are building blocks of any Temporal * Workflow and contain any business logic that could perform long running computation, network * calls, etc. * *

Annotating Activity Definition methods with @ActivityMethod is optional. * * @see io.temporal.activity.ActivityInterface * @see io.temporal.activity.ActivityMethod */ @ActivityInterface public interface SideEffectActivities { // Define your activity methods which can be called during workflow execution String sayHello(String greeting); String sayGoodBye(String greeting); } // Define the workflow implementation which implements our execute workflow method. public static class SideEffectWorkflowImpl implements SideEffectWorkflow { /** * Define the SideEffectActivities stub. Activity stubs are proxies for activity invocations * that are executed outside of the workflow thread on the activity worker, that can be on a * different host. Temporal is going to dispatch the activity results back to the workflow and * unblock the stub as soon as activity is completed on the activity worker. * *

In the {@link ActivityOptions} definition the "setStartToCloseTimeout" option sets maximum * time of a single Activity execution attempt. For this example it is set to 2 seconds. */ private final SideEffectActivities activities = Workflow.newActivityStub( SideEffectActivities.class, ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(2)).build()); int randomInt, sideEffectsRandomInt; UUID randomUUID; String result; @Override public String execute() { // Replay-safe way to create random number using Workflow.newRandom randomInt = Workflow.newRandom().nextInt(); // Replay-safe way to create random uuid randomUUID = Workflow.randomUUID(); /* * Random number using side effects. Note that this value is recorded in workflow history. On * replay the same value is returned so determinism is guaranteed. */ sideEffectsRandomInt = Workflow.sideEffect( int.class, () -> { Random random = new SecureRandom(); return random.nextInt(); }); /* * Since our randoms are all created safely (using SideEffects or Workflow deterministic * methods) the workflow result should be same as the queries ran after workflow completion. * In the case we did not use safe methods, the queries could have a different result. */ if ((randomUUID.version() + randomInt + sideEffectsRandomInt) % 2 == 0) { result = activities.sayHello("World"); } else { result = activities.sayGoodBye("World!"); } return result; } @Override public String getResult() { return result; } } /** Simple activity implementation. */ static class SideEffectActivitiesImpl implements SideEffectActivities { @Override public String sayHello(String greeting) { return "Hello " + greeting; } @Override public String sayGoodBye(String greeting) { return "Goodbye " + greeting; } } /** * With our Workflow and Activities defined, we can now start execution. The main method starts * the worker and then the workflow. */ public static void main(String[] args) { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } // Define the workflow service. WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); /* * Define the workflow factory. It is used to create workflow workers for a specific task queue. */ WorkerFactory factory = WorkerFactory.newInstance(client); /* * Define the workflow worker. Workflow workers listen to a defined task queue and process * workflows and activities. */ Worker worker = factory.newWorker(TASK_QUEUE); /* * Register our workflow implementation with the worker. Workflow implementations must be known * to the worker at runtime in order to dispatch workflow tasks. */ worker.registerWorkflowImplementationTypes(SideEffectWorkflowImpl.class); /* * Register our Activity Types with the Worker. Since Activities are stateless and thread-safe, * the Activity Type is a shared instance. */ worker.registerActivitiesImplementations(new SideEffectActivitiesImpl()); /* * Start all the workers registered for a specific task queue. The started workers then start * polling for workflows and activities. */ factory.start(); // Create the workflow client stub. It is used to start our workflow execution. SideEffectWorkflow workflow = client.newWorkflowStub( SideEffectWorkflow.class, WorkflowOptions.newBuilder() .setWorkflowId(WORKFLOW_ID) .setTaskQueue(TASK_QUEUE) .build()); /* * Execute our workflow and wait for it to complete. The call to our start method is * synchronous. * *

See {@link io.temporal.samples.hello.HelloSignal} for an example of starting workflow * without waiting synchronously for its result. */ String result = workflow.execute(); // Print workflow result System.out.println(result); // Note that query should return the exact same result System.out.println(workflow.getResult()); System.exit(0); } } ================================================ FILE: core/src/main/java/io/temporal/samples/hello/HelloSignal.java ================================================ package io.temporal.samples.hello; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import io.temporal.workflow.SignalMethod; import io.temporal.workflow.Workflow; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * Sample Temporal workflow that demonstrates how to use workflow signal methods to signal from * external sources. */ public class HelloSignal { // Define the task queue name static final String TASK_QUEUE = "HelloSignalTaskQueue"; // Define the workflow unique id static final String WORKFLOW_ID = "HelloSignalWorkflow"; /** * The Workflow Definition's Interface must contain one method annotated with @WorkflowMethod. * *

Workflow Definitions should not contain any heavyweight computations, non-deterministic * code, network calls, database operations, etc. Those things should be handled by the * Activities. * * @see io.temporal.workflow.WorkflowInterface * @see io.temporal.workflow.WorkflowMethod */ @WorkflowInterface public interface GreetingWorkflow { /** * This is the method that is executed when the Workflow Execution is started. The Workflow * Execution completes when this method finishes execution. */ @WorkflowMethod List getGreetings(); // Define the workflow waitForName signal method. This method is executed when the workflow // receives a signal. @SignalMethod void waitForName(String name); // Define the workflow exit signal method. This method is executed when the workflow receives a // signal. @SignalMethod void exit(); } // Define the workflow implementation which implements the getGreetings workflow method. public static class GreetingWorkflowImpl implements GreetingWorkflow { // messageQueue holds up to 10 messages (received from signals) List messageQueue = new ArrayList<>(10); boolean exit = false; @Override public List getGreetings() { List receivedMessages = new ArrayList<>(10); while (true) { // Block current thread until the unblocking condition is evaluated to true Workflow.await(() -> !messageQueue.isEmpty() || exit); if (messageQueue.isEmpty() && exit) { // no messages in queue and exit signal was sent, return the received messages return receivedMessages; } String message = messageQueue.remove(0); receivedMessages.add(message); } } @Override public void waitForName(String name) { messageQueue.add("Hello " + name + "!"); } @Override public void exit() { exit = true; } } /** * With the Workflow and Activities defined, we can now start execution. The main method starts * the worker and then the workflow. */ public static void main(String[] args) throws Exception { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } // Get a Workflow service stub. WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); /* * Define the workflow factory. It is used to create workflow workers for a specific task queue. */ WorkerFactory factory = WorkerFactory.newInstance(client); /* * Define the workflow worker. Workflow workers listen to a defined task queue and process * workflows and activities. */ Worker worker = factory.newWorker(TASK_QUEUE); /* * Register the workflow implementation with the worker. * Workflow implementations must be known to the worker at runtime in * order to dispatch workflow tasks. */ worker.registerWorkflowImplementationTypes(GreetingWorkflowImpl.class); /* * Start all the workers registered for a specific task queue. * The started workers then start polling for workflows and activities. */ factory.start(); // Create the workflow options WorkflowOptions workflowOptions = WorkflowOptions.newBuilder().setTaskQueue(TASK_QUEUE).setWorkflowId(WORKFLOW_ID).build(); // Create the workflow client stub. It is used to start the workflow execution. GreetingWorkflow workflow = client.newWorkflowStub(GreetingWorkflow.class, workflowOptions); // Start workflow asynchronously and call its getGreeting workflow method WorkflowClient.start(workflow::getGreetings); // After start for getGreeting returns, the workflow is guaranteed to be started. // So we can send a signal to it using the workflow stub. // This workflow keeps receiving signals until exit is called // When the workflow is started the getGreetings will block for the previously defined // conditions // Send the first workflow signal workflow.waitForName("World"); /* * Here we create a new workflow stub using the same workflow id. * We do this to demonstrate that to send a signal to an already running workflow * you only need to know its workflow id. */ GreetingWorkflow workflowById = client.newWorkflowStub(GreetingWorkflow.class, WORKFLOW_ID); // Send the second signal to our workflow workflowById.waitForName("Universe"); // Now let's send our exit signal to the workflow workflowById.exit(); /* * We now call our getGreetings workflow method synchronously after our workflow has started. * This reconnects our workflowById workflow stub to the existing workflow and blocks until * a result is available. Note that this behavior assumes that WorkflowOptions are not configured * with WorkflowIdReusePolicy.AllowDuplicate. If they were, this call would fail with the * WorkflowExecutionAlreadyStartedException exception. */ List greetings = workflowById.getGreetings(); // Print our two greetings which were sent by signals System.out.println(greetings); System.exit(0); } } ================================================ FILE: core/src/main/java/io/temporal/samples/hello/HelloSignalWithStartAndWorkflowInit.java ================================================ package io.temporal.samples.hello; import io.temporal.activity.ActivityInterface; import io.temporal.activity.ActivityOptions; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowFailedException; import io.temporal.client.WorkflowOptions; import io.temporal.client.WorkflowStub; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import io.temporal.worker.WorkflowImplementationOptions; import io.temporal.workflow.*; import java.io.IOException; import java.time.Duration; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang.StringUtils; /** * Sample Temporal workflow that demonstrates how to use WorkflowInit with clients starting * execution using SignalWithStart */ public class HelloSignalWithStartAndWorkflowInit { static final String TASK_QUEUE = "HelloWithInitTaskQueue"; public interface MyWorkflow { @WorkflowMethod String greet(Person person); @SignalMethod void addGreeting(Person person); } @WorkflowInterface public interface MyWorkflowWithInit extends MyWorkflow {} @WorkflowInterface public interface MyWorkflowNoInit extends MyWorkflow {} public static class WithInitMyWorkflowImpl implements MyWorkflowWithInit { // We dont initialize peopleToGreet on purpose private List peopleToGreet; private MyGreetingActivities activities = Workflow.newActivityStub( MyGreetingActivities.class, ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(2)).build()); @WorkflowInit public WithInitMyWorkflowImpl(Person person) { peopleToGreet = new ArrayList<>(); } @Override public String greet(Person person) { peopleToGreet.add(person); List greetings = new ArrayList<>(); while (!peopleToGreet.isEmpty()) { // run activity... greetings.add(activities.greet(peopleToGreet.get(0))); peopleToGreet.remove(0); } return StringUtils.join(greetings, ","); } @Override public void addGreeting(Person person) { peopleToGreet.add(person); } } public static class WithoutInitMyWorkflowImpl implements MyWorkflowNoInit { // We dont initialize peopleToGreet on purpose private List peopleToGreet; private MyGreetingActivities activities = Workflow.newActivityStub( MyGreetingActivities.class, ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(2)).build()); @Override public String greet(Person person) { peopleToGreet.add(person); List greetings = new ArrayList<>(); while (!peopleToGreet.isEmpty()) { // run activity... greetings.add(activities.greet(peopleToGreet.get(0))); peopleToGreet.remove(0); } return StringUtils.join(greetings, ","); } @Override public void addGreeting(Person person) { peopleToGreet.add(person); } } @ActivityInterface public interface MyGreetingActivities { public String greet(Person person); } public static class MyGreetingActivitiesImpl implements MyGreetingActivities { @Override public String greet(Person person) { return "Hello " + person.firstName + " " + person.lastName; } } public static class Person { String firstName; String lastName; int age; public Person() {} public Person(String firstName, String lastName, int age) { this.firstName = firstName; this.lastName = lastName; this.age = age; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } public static void main(String[] args) { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); WorkerFactory factory = WorkerFactory.newInstance(client); Worker worker = factory.newWorker(TASK_QUEUE); worker.registerWorkflowImplementationTypes(WithInitMyWorkflowImpl.class); // We explicitly want to fail this workflow on NPE as thats what we expect without WorkflowInit // As we didnt initialize peopleToGreet on purpose worker.registerWorkflowImplementationTypes( WorkflowImplementationOptions.newBuilder() .setFailWorkflowExceptionTypes(NullPointerException.class) .build(), WithoutInitMyWorkflowImpl.class); worker.registerActivitiesImplementations(new MyGreetingActivitiesImpl()); factory.start(); MyWorkflowWithInit withInitStub = client.newWorkflowStub( MyWorkflowWithInit.class, WorkflowOptions.newBuilder() .setWorkflowId("with-init") .setTaskQueue(TASK_QUEUE) .build()); // Start with init workflow which is expected to succeed // As WorkflowInit will initialize peopleToGreet before signal handler is invoked WorkflowStub.fromTyped(withInitStub) .signalWithStart( "addGreeting", new Object[] {new Person("Michael", "Jordan", 55)}, new Object[] {new Person("John", "Stockton", 57)}); String result = WorkflowStub.fromTyped(withInitStub).getResult(String.class); System.out.println("Result: " + result); // Start without init, this execution is expected to fail as we set // NullPointerException as a workflow failure type // NPE is caused because we did not initialize peopleToGreet array MyWorkflowNoInit noInitStub = client.newWorkflowStub( MyWorkflowNoInit.class, WorkflowOptions.newBuilder() .setWorkflowId("without-init") .setTaskQueue(TASK_QUEUE) .build()); WorkflowStub.fromTyped(noInitStub) .signalWithStart( "addGreeting", new Object[] {new Person("Michael", "Jordan", 55)}, new Object[] {new Person("John", "Stockton", 57)}); try { WorkflowStub.fromTyped(noInitStub).getResult(String.class); } catch (WorkflowFailedException e) { System.out.println("Expected workflow failure: " + e.getMessage()); } System.exit(0); } } ================================================ FILE: core/src/main/java/io/temporal/samples/hello/HelloSignalWithTimer.java ================================================ package io.temporal.samples.hello; import io.temporal.activity.ActivityInterface; import io.temporal.activity.ActivityOptions; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.client.WorkflowStub; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.failure.CanceledFailure; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import io.temporal.workflow.*; import java.io.IOException; import java.time.Duration; import org.slf4j.Logger; /** * Sample Temporal workflow that shows receiving signals for a specific time period and then process * last one received and continue as new. */ public class HelloSignalWithTimer { static final String TASK_QUEUE = "HelloSignalWithTimerTaskQueue"; static final String WORKFLOW_ID = "HelloSignalWithTimerWorkflow"; @WorkflowInterface public interface SignalWithTimerWorkflow { @WorkflowMethod void execute(); @SignalMethod void newValue(String value); @SignalMethod void exit(); } @ActivityInterface public interface ValueProcessingActivities { void processValue(String value); } public static class SignalWithTimerWorkflowImpl implements SignalWithTimerWorkflow { private Logger logger = Workflow.getLogger(SignalWithTimerWorkflowImpl.class); private String lastValue = ""; private CancellationScope timerScope; private boolean exit = false; private final ValueProcessingActivities activities = Workflow.newActivityStub( ValueProcessingActivities.class, ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(2)).build()); @Override public void execute() { // Just in case if exit signal is sent as soon as execution is started if (exit) { return; } // Start timer in cancellation scope so we can cancel it on exit signal received timerScope = Workflow.newCancellationScope( () -> { try { // You can add a signal handler that updates the sleep duration // As it may change via business logic over time // For sample we just hard code it to 5 seconds Workflow.newTimer(Duration.ofSeconds(5)).get(); } catch (CanceledFailure e) { // Exit signal is received causing cancellation of timer scope and timer // For sample we just log it, you can handle it if needed logger.info("Timer canceled via exit signal"); } }); timerScope.run(); // Process last received signal and either exit or ContinueAsNew depending on if we got // Exit signal or not activities.processValue(lastValue); if (exit) { return; } else { SignalWithTimerWorkflow nextRun = Workflow.newContinueAsNewStub(SignalWithTimerWorkflow.class); nextRun.execute(); } } @Override public void newValue(String value) { // Note that we can receive a signal at the same time workflow is trying to complete or // ContinueAsNew. This would cause workflow task failure with UnhandledCommand // in order to deliver this signal to our execution. // You can choose what to do in this case depending on business logic. // For this sample we just ignore it, alternative could be to process it or carry it over // to the continued execution if needed. lastValue = value; } @Override public void exit() { if (timerScope != null) { timerScope.cancel("exit received"); } this.exit = true; } } static class ValueProcessingActivitiesImpl implements ValueProcessingActivities { @Override public void processValue(String value) { // Here you would access downstream services to process the value // Dummy impl for sample, do nothing System.out.println("Processing value: " + value); } } public static void main(String[] args) { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); WorkerFactory factory = WorkerFactory.newInstance(client); Worker worker = factory.newWorker(TASK_QUEUE); worker.registerWorkflowImplementationTypes(SignalWithTimerWorkflowImpl.class); worker.registerActivitiesImplementations(new ValueProcessingActivitiesImpl()); factory.start(); SignalWithTimerWorkflow workflow = client.newWorkflowStub( SignalWithTimerWorkflow.class, WorkflowOptions.newBuilder() .setWorkflowId(WORKFLOW_ID) .setTaskQueue(TASK_QUEUE) .build()); // Start execution, this unblocks when its created by service WorkflowClient.start(workflow::execute); // Send signals 2s apart 12 times (to simulate cancellation on last ContinueAsNew) for (int i = 0; i < 12; i++) { workflow.newValue("Value " + i); sleep(2); } sleep(1); // Send exit signal workflow.exit(); // Wait for execution to complete after receiving exit signal. // This should unblock pretty much immediately WorkflowStub.fromTyped(workflow).getResult(Void.class); System.exit(0); } private static void sleep(int seconds) { try { Thread.sleep(seconds * 1000L); } catch (Exception e) { System.out.println("Error: " + e.getMessage()); } } } ================================================ FILE: core/src/main/java/io/temporal/samples/hello/HelloStandaloneActivity.java ================================================ package io.temporal.samples.hello; import io.temporal.activity.ActivityInterface; import io.temporal.activity.ActivityMethod; import io.temporal.client.ActivityClient; import io.temporal.client.ActivityClientOptions; import io.temporal.client.StartActivityOptions; import io.temporal.client.WorkflowClient; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import java.io.IOException; import java.time.Duration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Sample Temporal application that executes a Standalone Activity — an Activity that runs * independently, without being orchestrated by a Workflow. Requires a local instance of the * Temporal service to be running. * *

Unlike regular Activities, a Standalone Activity is started directly from a Temporal Client * using {@link ActivityClient}, not from inside a Workflow Definition. Writing the Activity and * registering it with the Worker is identical in both cases. */ public class HelloStandaloneActivity { static final String TASK_QUEUE = "HelloStandaloneActivityTaskQueue"; static final String ACTIVITY_ID = "hello-standalone-activity-id"; /** * Activity interface. Writing a Standalone Activity is identical to writing an Activity * orchestrated by a Workflow — the same Activity can be used for both. * * @see io.temporal.activity.ActivityInterface * @see io.temporal.activity.ActivityMethod */ @ActivityInterface public interface GreetingActivities { // Define your activity method which can be called directly from a Temporal Client. @ActivityMethod String composeGreeting(String greeting, String name); } /** Simple activity implementation that concatenates two strings. */ public static class GreetingActivitiesImpl implements GreetingActivities { private static final Logger log = LoggerFactory.getLogger(GreetingActivitiesImpl.class); @Override public String composeGreeting(String greeting, String name) { log.info("Composing greeting..."); return greeting + ", " + name + "!"; } } public static void main(String[] args) { // Load configuration from environment and files. ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } // gRPC stubs wrapper that talks to the temporal service. WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); // WorkflowClient is required to create a Worker. WorkflowClient workflowClient = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); // Worker factory that can be used to create workers for specific task queues. WorkerFactory factory = WorkerFactory.newInstance(workflowClient); // Worker that listens on a task queue and hosts activity implementations. Worker worker = factory.newWorker(TASK_QUEUE); // Activities are stateless and thread safe. So a shared instance is used. worker.registerActivitiesImplementations(new GreetingActivitiesImpl()); // Start listening to the activity task queue. factory.start(); // ActivityClient executes standalone activities directly from application code, // without a Workflow. ActivityClient client = ActivityClient.newInstance( service, ActivityClientOptions.newBuilder().setNamespace(profile.getNamespace()).build()); // Options specifying the activity ID, task queue, and timeout. StartActivityOptions options = StartActivityOptions.newBuilder() .setId(ACTIVITY_ID) .setTaskQueue(TASK_QUEUE) .setStartToCloseTimeout(Duration.ofSeconds(10)) .build(); try { // Execute the activity and wait for its result. The typed API uses an unbound method // reference so the SDK can infer the activity type name and result type automatically. String result = client.execute( GreetingActivities.class, GreetingActivities::composeGreeting, options, "Hello", "World"); System.out.println(result); } finally { // Shut down the worker before the service so polling threads stop cleanly. factory.shutdown(); service.shutdown(); } } } ================================================ FILE: core/src/main/java/io/temporal/samples/hello/HelloTypedSearchAttributes.java ================================================ package io.temporal.samples.hello; import io.temporal.activity.ActivityInterface; import io.temporal.activity.ActivityMethod; import io.temporal.activity.ActivityOptions; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.common.SearchAttributeKey; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import io.temporal.workflow.Workflow; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; import java.io.IOException; import java.time.Duration; import java.time.OffsetDateTime; import java.time.ZoneOffset; import java.util.Arrays; import java.util.List; import java.util.StringJoiner; /** * Sample Temporal workflow that demonstrates setting up, updating, and retrieving workflow search * attributes using the typed search attributes API. * *

NOTE: you may need to add these custom search attributes yourself before running the sample. * If you are using autosetup image for service, you will need to create the * "CustomKeywordListField" search attribute with Temporal cli, for example: * *

temporal operator search-attribute create -name "CustomKeywordListField" -type "KeywordList" * *

If you run your test and don't have some custom SA defined that are used here you would see * error like: INVALID_ARGUMENT: Namespace default has no mapping defined for search attribute * CustomBoolField when trying to start the workflow execution. In that case use cli to add the * needed search attribute with its needed type. */ public class HelloTypedSearchAttributes { // Define the task queue name static final String TASK_QUEUE = "HelloTypedSearchAttributesTaskQueue"; // Define our workflow unique id static final String WORKFLOW_ID = "HelloTypedSearchAttributesWorkflow"; // Define all our search attributes with appropriate types static final SearchAttributeKey CUSTOM_KEYWORD_SA = SearchAttributeKey.forKeyword("CustomKeywordField"); static final SearchAttributeKey> CUSTOM_KEYWORD_LIST_SA = SearchAttributeKey.forKeywordList("CustomKeywordListField"); static final SearchAttributeKey CUSTOM_LONG_SA = SearchAttributeKey.forLong("CustomIntField"); static final SearchAttributeKey CUSTOM_DOUBLE_SA = SearchAttributeKey.forDouble("CustomDoubleField"); static final SearchAttributeKey CUSTOM_BOOL_SA = SearchAttributeKey.forBoolean("CustomBoolField"); static final SearchAttributeKey CUSTOM_OFFSET_DATE_TIME_SA = SearchAttributeKey.forOffsetDateTime("CustomDatetimeField"); static final SearchAttributeKey CUSTOM_STRING_SA = SearchAttributeKey.forText("CustomStringField"); /** * The Workflow Definition's Interface must contain one method annotated with @WorkflowMethod. * *

Workflow Definitions should not contain any heavyweight computations, non-deterministic * code, network calls, database operations, etc. Those things should be handled by the * Activities. * * @see WorkflowInterface * @see WorkflowMethod */ @WorkflowInterface public interface GreetingWorkflow { /** * This is the method that is executed when the Workflow Execution is started. The Workflow * Execution completes when this method finishes execution. */ @WorkflowMethod String getGreeting(String name); } /** * This is the Activity Definition's Interface. Activities are building blocks of any Temporal * Workflow and contain any business logic that could perform long running computation, network * calls, etc. * *

Annotating Activity Definition methods with @ActivityMethod is optional. * * @see ActivityInterface * @see ActivityMethod */ @ActivityInterface public interface GreetingActivities { @ActivityMethod String composeGreeting(String greeting, List salutations, String name); } // Define the workflow implementation which implements our getGreeting workflow method. public static class GreetingWorkflowImpl implements GreetingWorkflow { /** * Define the GreetingActivities stub. Activity stubs implement activity interfaces and proxy * calls to it to Temporal activity invocations. Since Temporal activities are reentrant, a * single activity stub can be used for multiple activity invocations. * *

In the {@link ActivityOptions} definition the "setStartToCloseTimeout" option sets the * maximum time of a single Activity execution attempt. For this example it is set to 2 seconds. */ private final GreetingActivities activities = Workflow.newActivityStub( GreetingActivities.class, ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(2)).build()); @Override public String getGreeting(String name) { // Show how to update typed search attributes inside a workflow. The first parameter shows how // to remove a search attribute. The second parameter shows how to update a value. Workflow.upsertTypedSearchAttributes( CUSTOM_LONG_SA.valueUnset(), CUSTOM_KEYWORD_SA.valueSet("Hello")); // Get the search attributes currently set on this workflow io.temporal.common.SearchAttributes searchAttributes = Workflow.getTypedSearchAttributes(); // Get a particular value out of the container using the typed key String greeting = searchAttributes.get(CUSTOM_KEYWORD_SA); List salutations = searchAttributes.get(CUSTOM_KEYWORD_LIST_SA); // This is a blocking call that returns only after the activity has completed. return activities.composeGreeting(greeting, salutations, name); } } /** * Implementation of our workflow activity interface. It overwrites our defined composeGreeting * activity method. */ static class GreetingActivitiesImpl implements GreetingActivities { @Override public String composeGreeting(String greeting, List salutations, String name) { StringJoiner greetingJoiner = new StringJoiner(" "); greetingJoiner.add(greeting); greetingJoiner.add(name); salutations.forEach(s -> greetingJoiner.add(s)); return greetingJoiner.toString(); } } /** * With our Workflow and Activities defined, we can now start execution. The main method starts * the worker and then the workflow. */ public static void main(String[] args) { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } // Define the workflow service. WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); /* * Define the workflow factory. It is used to create workflow workers for a specific task queue. */ WorkerFactory factory = WorkerFactory.newInstance(client); /* * Define the workflow worker. Workflow workers listen to a defined task queue and process * workflows and activities. */ Worker worker = factory.newWorker(TASK_QUEUE); /* * Register our workflow implementation with the worker. * Workflow implementations must be known to the worker at runtime in * order to dispatch workflow tasks. */ worker.registerWorkflowImplementationTypes( HelloTypedSearchAttributes.GreetingWorkflowImpl.class); /* * Register our Activity Types with the Worker. Since Activities are stateless and thread-safe, * the Activity Type is a shared instance. */ worker.registerActivitiesImplementations( new HelloTypedSearchAttributes.GreetingActivitiesImpl()); /* * Start all the workers registered for a specific task queue. * The started workers then start polling for workflows and activities. */ factory.start(); // Set our workflow options. // Note that we set our search attributes here WorkflowOptions workflowOptions = WorkflowOptions.newBuilder() .setWorkflowId(WORKFLOW_ID) .setTaskQueue(TASK_QUEUE) .setTypedSearchAttributes(generateTypedSearchAttributes()) .build(); // Create the workflow client stub. It is used to start our workflow execution. HelloTypedSearchAttributes.GreetingWorkflow workflow = client.newWorkflowStub(HelloTypedSearchAttributes.GreetingWorkflow.class, workflowOptions); // Execute a workflow waiting for it to complete. String greeting = workflow.getGreeting("TypedSearchAttributes"); // Print the workflow execution results System.out.println(greeting); System.exit(0); } // Generate our example search option private static io.temporal.common.SearchAttributes generateTypedSearchAttributes() { return io.temporal.common.SearchAttributes.newBuilder() .set(CUSTOM_KEYWORD_SA, "keyword") .set(CUSTOM_KEYWORD_LIST_SA, Arrays.asList("how", "are", "you", "doing?")) .set(CUSTOM_LONG_SA, 1l) .set(CUSTOM_DOUBLE_SA, 0.1) .set(CUSTOM_BOOL_SA, true) .set(CUSTOM_OFFSET_DATE_TIME_SA, OffsetDateTime.now(ZoneOffset.UTC)) .set( CUSTOM_STRING_SA, "String field is for text. When query, it will be tokenized for partial match. StringTypeField cannot be used in Order By") .build(); } } ================================================ FILE: core/src/main/java/io/temporal/samples/hello/HelloUpdate.java ================================================ package io.temporal.samples.hello; import com.google.common.base.Throwables; import io.temporal.activity.ActivityOptions; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.client.WorkflowStub; import io.temporal.client.WorkflowUpdateException; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.failure.ApplicationFailure; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import io.temporal.workflow.SignalMethod; import io.temporal.workflow.UpdateMethod; import io.temporal.workflow.UpdateValidatorMethod; import io.temporal.workflow.Workflow; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; import java.io.IOException; import java.time.Duration; import java.util.ArrayList; import java.util.List; /** * Sample Temporal workflow that demonstrates how to use workflow update methods to update a * workflow execution from external sources. Workflow update is another way to interact with a * running workflow along with signals and queries. Workflow update combines aspects of signals and * queries. Like signals, workflow update can mutate workflow state. Like queries, workflow update * can return a value. * *

Note: Make sure to set {@code frontend.enableUpdateWorkflowExecution=true} in your Temporal * config to enabled update. */ public class HelloUpdate { // Define the task queue name static final String TASK_QUEUE = "HelloUpdateTaskQueue"; // Define the workflow unique id static final String WORKFLOW_ID = "HelloUpdateWorkflow"; /** * The Workflow Definition's Interface must contain one method annotated with @WorkflowMethod. * *

Workflow Definitions should not contain any heavyweight computations, non-deterministic * code, network calls, database operations, etc. Those things should be handled by the * Activities. * * @see WorkflowInterface * @see WorkflowMethod */ @WorkflowInterface public interface GreetingWorkflow { /** * This is the method that is executed when the Workflow Execution is started. The Workflow * Execution completes when this method finishes execution. */ @WorkflowMethod List getGreetings(); /* * Define the workflow addGreeting update method. This method is executed when the workflow * receives an update request. */ @UpdateMethod int addGreeting(String name); /* * Define an optional workflow update validator. The validator must take the same parameters as the update handle. * The validator is run before the update handle. * If the validator fails by throwing any exception the update request will be rejected and the handle will not run. * If the validator passes the update will be considered accepted and the handler will run. */ @UpdateValidatorMethod(updateName = "addGreeting") void addGreetingValidator(String name); // Define the workflow exit signal method. This method is executed when the workflow receives a // signal. @SignalMethod void exit(); } // Define the workflow implementation which implements the getGreetings workflow method. public static class GreetingWorkflowImpl implements GreetingWorkflow { // messageQueue holds up to 10 messages (received from updates) private final List messageQueue = new ArrayList<>(10); private final List receivedMessages = new ArrayList<>(10); private boolean exit = false; private final HelloActivity.GreetingActivities activities = Workflow.newActivityStub( HelloActivity.GreetingActivities.class, ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(2)).build()); @Override public List getGreetings() { while (true) { // Block current thread until the unblocking condition is evaluated to true Workflow.await(() -> !messageQueue.isEmpty() || exit); if (messageQueue.isEmpty() && exit) { /* * no messages in queue and exit signal was sent, return the received messages. * * Note: A accepted update will not stop workflow completion. If a workflow tries to complete after an update * has been sent by a client, but before it has been accepted by the workflow, the workflow will not complete. */ return receivedMessages; } String message = messageQueue.remove(0); receivedMessages.add(message); } } @Override public int addGreeting(String name) { if (name.isEmpty()) { /* * Updates can fail by throwing a TemporalFailure. All other exceptions cause the workflow * task to fail and potentially retried. * * Note: A check like this could (and should) belong in the validator, this is just to demonstrate failing an * update. */ throw ApplicationFailure.newFailure("Cannot greet someone with an empty name", "Failure"); } // Updates can mutate workflow state like variables or call activities messageQueue.add(activities.composeGreeting("Hello", name)); // Updates can return data back to the client return receivedMessages.size() + messageQueue.size(); } @Override public void addGreetingValidator(String name) { /* * Update validators have the same restrictions as Queries. So workflow state cannot be * mutated inside a validator. */ if (receivedMessages.size() >= 10) { /* * Throwing any exception inside an update validator will cause the update to be rejected. * Note: rejected update will not appear in the workflow history */ throw new IllegalStateException("Only 10 greetings may be added"); } } @Override public void exit() { exit = true; } } /** * With the Workflow and Activities defined, we can now start execution. The main method starts * the worker and then the workflow. */ public static void main(String[] args) throws Exception { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } // Get a Workflow service stub. WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); /* * Define the workflow factory. It is used to create workflow workers for a specific task queue. */ WorkerFactory factory = WorkerFactory.newInstance(client); /* * Define the workflow worker. Workflow workers listen to a defined task queue and process * workflows and activities. */ Worker worker = factory.newWorker(TASK_QUEUE); /* * Register the workflow implementation with the worker. * Workflow implementations must be known to the worker at runtime in * order to dispatch workflow tasks. */ worker.registerWorkflowImplementationTypes(GreetingWorkflowImpl.class); /* * Register our Activity Types with the Worker. Since Activities are stateless and thread-safe, * the Activity Type is a shared instance. */ worker.registerActivitiesImplementations(new HelloActivity.GreetingActivitiesImpl()); /* * Start all the workers registered for a specific task queue. * The started workers then start polling for workflows and activities. */ factory.start(); // Create the workflow options WorkflowOptions workflowOptions = WorkflowOptions.newBuilder().setTaskQueue(TASK_QUEUE).setWorkflowId(WORKFLOW_ID).build(); // Create the workflow client stub. It is used to start the workflow execution. GreetingWorkflow workflow = client.newWorkflowStub(GreetingWorkflow.class, workflowOptions); // Start workflow asynchronously and call its getGreeting workflow method WorkflowClient.start(workflow::getGreetings); // After start for getGreeting returns, the workflow is guaranteed to be started. // So we can send an update to it using the workflow stub. // This workflow keeps receiving updates until exit is called // When the workflow is started the getGreetings will block for the previously defined // conditions // Send the first workflow update workflow.addGreeting("World"); /* * Here we create a new workflow stub using the same workflow id. * We do this to demonstrate that to send an update to an already running workflow * you only need to know its workflow id. */ GreetingWorkflow workflowById = client.newWorkflowStub(GreetingWorkflow.class, WORKFLOW_ID); // Send the second update to our workflow workflowById.addGreeting("Universe"); /* * Create an untyped workflow stub to demonstrate sending an update * with the untyped stub. */ WorkflowStub greetingStub = client.newUntypedWorkflowStub(WORKFLOW_ID); greetingStub.update("addGreeting", int.class, "Temporal"); try { // The update request will fail on a empty name and the exception will be thrown here. workflowById.addGreeting(""); System.exit(-1); } catch (WorkflowUpdateException e) { Throwable cause = Throwables.getRootCause(e); /* * Here we should get our originally thrown ApplicationError * and the message "Cannot greet someone with an empty name". */ System.out.println("\n Update failed, root cause: " + cause.getMessage()); } // Send our update validators limit of 10 updates int sentUpdates = workflowById.addGreeting("Update"); while (sentUpdates < 10) { sentUpdates = workflowById.addGreeting("Again"); } // The update request will be rejected because our validator will fail try { workflowById.addGreeting("Will be rejected"); System.exit(-1); } catch (WorkflowUpdateException e) { Throwable cause = Throwables.getRootCause(e); System.out.println("\n Update rejected: " + cause.getMessage()); } // Now let's send our exit signal to the workflow workflowById.exit(); /* * We now call our getGreetings workflow method synchronously after our workflow has started. * This reconnects our workflowById workflow stub to the existing workflow and blocks until * a result is available. Note that this behavior assumes that WorkflowOptions are not configured * with WorkflowIdReusePolicy.AllowDuplicate. If they were, this call would fail with the * WorkflowExecutionAlreadyStartedException exception. */ List greetings = workflowById.getGreetings(); // Print our two greetings which were sent by signals System.out.println(greetings); System.exit(0); } } ================================================ FILE: core/src/main/java/io/temporal/samples/hello/HelloWorkflowTimer.java ================================================ package io.temporal.samples.hello; import io.temporal.activity.*; import io.temporal.client.ActivityCompletionException; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.client.WorkflowStub; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.failure.ActivityFailure; import io.temporal.failure.CanceledFailure; import io.temporal.failure.ChildWorkflowFailure; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import io.temporal.workflow.*; import java.io.IOException; import java.time.Duration; /** Sample shows how to use workflow timer instead of WorkflowOptions->Run/ExecutionTimeout */ public class HelloWorkflowTimer { private static String WORKFLOW_ID = "HelloWorkflowWithTimer"; private static String TASK_QUEUE = "HelloWorkflowWithTimerTaskQueue"; // Change time to 12 to 20 seconds to handle cancellation while child workflow is running private static int TIME_SECS = 8; // Workflow @WorkflowInterface public interface WorkflowWithTimer { @WorkflowMethod String execute(String input); } public static class WorkflowWithTimerImpl implements WorkflowWithTimer { // Our timer cancellation scope private CancellationScope timerCancellationScope; // Our workflow cancellation scope private CancellationScope workflowCancellationScope; // Workflow result private String workflowResult = ""; private Promise workflowTimerPromise; @Override public String execute(String input) { // Create workflow timer (within timer cancel;ation scope so it can be canceled) // which denotes the max amount of time we allow this execution to run // Using workflow timer instead of workflow run/execution timeouts allow us to react to this // timer // fires, be able to chose if we want to fail or complete execution, and do some "cleanup" // tasks if // necessary before we do so. If we used workflow run/execution timeouts insted we would not // be able // to react to this timer firing (its server timer only) timerCancellationScope = Workflow.newCancellationScope( () -> { workflowTimerPromise = Workflow.newTimer( Duration.ofSeconds(TIME_SECS), TimerOptions.newBuilder().setSummary("Workflow Timer").build()) // We can use thenApply here to cancel our cancelation scope when this timer // fires. Note we cannot complete the execution from here, see // https://github.com/temporalio/sdk-java/issues/87 .thenApply( ignore -> { // Cancel the workflow cancellation scope allowing us to react to this // timer firing if (workflowCancellationScope != null) { workflowCancellationScope.cancel("Workflow timer fired"); } return null; }); }); timerCancellationScope.run(); // Create workflow cancellation scope in which we put our core business logic workflowCancellationScope = Workflow.newCancellationScope( () -> { WorkflowWithTimerActivities activities = Workflow.newActivityStub( WorkflowWithTimerActivities.class, ActivityOptions.newBuilder() .setStartToCloseTimeout(Duration.ofSeconds(12)) // Set heartbeat timeout to 1s .setHeartbeatTimeout(Duration.ofSeconds(2)) // We want to wait for activity to complete cancellation .setCancellationType( ActivityCancellationType.WAIT_CANCELLATION_COMPLETED) .build()); WorkflowWithTimerChildWorkflow childWorkflow = Workflow.newChildWorkflowStub( WorkflowWithTimerChildWorkflow.class, ChildWorkflowOptions.newBuilder() .setWorkflowId(WORKFLOW_ID + "-Child") // We want to wait for child workflow cancellation completion .setCancellationType( ChildWorkflowCancellationType.WAIT_CANCELLATION_COMPLETED) .build()); try { // Run our activities workflowResult = activities.sayHello(input); // Then our child workflow childWorkflow.executeChild(input); } catch (ActivityFailure af) { // Handle cancellation of scope while activities are pending (running) if (af.getCause() instanceof CanceledFailure) { workflowResult = "Workflow timer fired while activities were executing."; // Here we can do more work if needed } } catch (ChildWorkflowFailure cwf) { // Handle cancellation of scope while child workflow is pending (running) if (cwf.getCause() instanceof CanceledFailure) { workflowResult = "Workflow timer fired while child workflow was executing."; // Here we can do more work if needed } } }); // Run the workflow cancellation scope // We need to handle CanceledFailure here in case we cancel the scope // right before activity/child workflows are scheduled try { workflowCancellationScope.run(); } catch (CanceledFailure e) { workflowResult = "Workflow cancelled."; } // Cancel our workflow timer if it didnt fire if (!workflowTimerPromise.isCompleted()) { timerCancellationScope.cancel("Workflow completed before workflow timer."); } return workflowResult; } } // Activities @ActivityInterface public interface WorkflowWithTimerActivities { String sayHello(String input); } public static class WorkflowWithTimerActivitiesImpl implements WorkflowWithTimerActivities { @Override public String sayHello(String input) { // here we just heartbeat then sleep for 1s for (int i = 0; i < 10; i++) { try { Activity.getExecutionContext().heartbeat("heartbeating: " + i); } catch (ActivityCompletionException e) { // Do some cleanup if needed, then re-throw throw e; } sleep(1); } return "Hello " + input; } // Just sample sleep method private void sleep(int seconds) { try { Thread.sleep(seconds * 1000L); } catch (Exception e) { System.out.println(e.getMessage()); } } } // Child Workflows @WorkflowInterface public interface WorkflowWithTimerChildWorkflow { @WorkflowMethod String executeChild(String input); } public static class WorkflowWithTimerChildWorkflowImpl implements WorkflowWithTimerChildWorkflow { @Override public String executeChild(String input) { // For sample we just sleep for 5 seconds and return some result try { Workflow.sleep(Duration.ofSeconds(5)); return "From executeChild - " + input; // Note that similarly to parent workflow if child is running activities/child workflows // we need to handle this in same way as parent does // Fpr sample we can just handle CanceledFailure and rethrow } catch (CanceledFailure e) { // Can do cleanup if needed throw e; } } } public static void main(String[] args) { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } // Create service stubs WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); // Create workflow client WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); // Create worker factory WorkerFactory factory = WorkerFactory.newInstance(client); // Create worker Worker worker = factory.newWorker(TASK_QUEUE); // Register workflow and child workflow worker.registerWorkflowImplementationTypes( WorkflowWithTimerImpl.class, WorkflowWithTimerChildWorkflowImpl.class); // Register activities worker.registerActivitiesImplementations(new WorkflowWithTimerActivitiesImpl()); // Start factory (and worker) factory.start(); // Create workflow stub WorkflowWithTimer workflow = client.newWorkflowStub( WorkflowWithTimer.class, WorkflowOptions.newBuilder() // Note we do not set workflow run/execution timeouts // As its not recommended in most cases // In same we show how we can implement this with workflow timer instead .setWorkflowId(WORKFLOW_ID) .setTaskQueue(TASK_QUEUE) .build()); // Start workflow execution async WorkflowClient.start(workflow::execute, "Some Name Here"); // Wait for execution to complete (sync) WorkflowStub workflowStub = WorkflowStub.fromTyped(workflow); String result = workflowStub.getResult(String.class); System.out.println("Workflow result: " + result); // Stop main method System.exit(0); } } ================================================ FILE: core/src/main/java/io/temporal/samples/hello/README.md ================================================ ## Hello samples Each Hello World sample demonstrates one feature of the SDK in a single file. **Note that the single file format is used for sample brevity and is not something we recommend for real applications.** To run each hello world sample, use one of the following commands: ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.hello.HelloAccumulator ./gradlew -q execute -PmainClass=io.temporal.samples.hello.HelloActivity ./gradlew -q execute -PmainClass=io.temporal.samples.hello.HelloActivityRetry ./gradlew -q execute -PmainClass=io.temporal.samples.hello.HelloActivityExclusiveChoice ./gradlew -q execute -PmainClass=io.temporal.samples.hello.HelloAsync ./gradlew -q execute -PmainClass=io.temporal.samples.hello.HelloParallelActivity ./gradlew -q execute -PmainClass=io.temporal.samples.hello.HelloAsyncActivityCompletion ./gradlew -q execute -PmainClass=io.temporal.samples.hello.HelloAsyncLambda ./gradlew -q execute -PmainClass=io.temporal.samples.hello.HelloCancellationScope ./gradlew -q execute -PmainClass=io.temporal.samples.hello.HelloDetachedCancellationScope ./gradlew -q execute -PmainClass=io.temporal.samples.hello.HelloChild ./gradlew -q execute -PmainClass=io.temporal.samples.hello.HelloCron ./gradlew -q execute -PmainClass=io.temporal.samples.hello.HelloDynamic ./gradlew -q execute -PmainClass=io.temporal.samples.hello.HelloEagerWorkflowStart ./gradlew -q execute -PmainClass=io.temporal.samples.hello.HelloException ./gradlew -q execute -PmainClass=io.temporal.samples.hello.HelloLocalActivity ./gradlew -q execute -PmainClass=io.temporal.samples.hello.HelloPeriodic ./gradlew -q execute -PmainClass=io.temporal.samples.hello.HelloPolymorphicActivity ./gradlew -q execute -PmainClass=io.temporal.samples.hello.HelloQuery ./gradlew -q execute -PmainClass=io.temporal.samples.hello.HelloSaga ./gradlew -q execute -PmainClass=io.temporal.samples.hello.HelloSchedules ./gradlew -q execute -PmainClass=io.temporal.samples.hello.HelloSignal ./gradlew -q execute -PmainClass=io.temporal.samples.hello.HelloSearchAttributes ./gradlew -q execute -PmainClass=io.temporal.samples.hello.HelloTypedSearchAttributes ./gradlew -q execute -PmainClass=io.temporal.samples.hello.HelloSideEffect ./gradlew -q execute -PmainClass=io.temporal.samples.hello.HelloUpdate ./gradlew -q execute -PmainClass=io.temporal.samples.hello.HelloSignalWithTimer ./gradlew -q execute -PmainClass=io.temporal.samples.hello.HelloSignalWithStartAndWorkflowInit ./gradlew -q execute -PmainClass=io.temporal.samples.hello.HelloStandaloneActivity ``` ================================================ FILE: core/src/main/java/io/temporal/samples/keymanagementencryption/awsencryptionsdk/EncryptedPayloads.java ================================================ package io.temporal.samples.keymanagementencryption.awsencryptionsdk; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowClientOptions; import io.temporal.client.WorkflowOptions; import io.temporal.common.converter.CodecDataConverter; import io.temporal.common.converter.DefaultDataConverter; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.samples.hello.HelloActivity; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import java.io.IOException; import java.util.Collections; import software.amazon.cryptography.materialproviders.IKeyring; import software.amazon.cryptography.materialproviders.MaterialProviders; import software.amazon.cryptography.materialproviders.model.CreateAwsKmsMultiKeyringInput; import software.amazon.cryptography.materialproviders.model.MaterialProvidersConfig; public class EncryptedPayloads { static final String TASK_QUEUE = "EncryptedPayloads"; public static void main(String[] args) { // Configure your keyring. In this sample we are configuring a basic AWS KMS keyring, but the // AWS encryption SDK has multiple options depending on your use case. // // See more here: // https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/which-keyring.html String generatorKey = System.getenv("AWS_KEY_ARN"); final MaterialProviders materialProviders = MaterialProviders.builder() .MaterialProvidersConfig(MaterialProvidersConfig.builder().build()) .build(); // Create the AWS KMS keyring final CreateAwsKmsMultiKeyringInput keyringInput = CreateAwsKmsMultiKeyringInput.builder().generator(generatorKey).build(); final IKeyring kmsKeyring = materialProviders.CreateAwsKmsMultiKeyring(keyringInput); // gRPC stubs wrapper that talks to the local docker instance of temporal service. // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); // client that can be used to start and signal workflows WorkflowClient client = WorkflowClient.newInstance( service, WorkflowClientOptions.newBuilder() .setDataConverter( new CodecDataConverter( DefaultDataConverter.newDefaultInstance(), // Create our encryption codec Collections.singletonList(new KeyringCodec(kmsKeyring)))) .build()); // worker factory that can be used to create workers for specific task queues WorkerFactory factory = WorkerFactory.newInstance(client); // Worker that listens on a task queue and hosts both workflow and activity implementations. Worker worker = factory.newWorker(TASK_QUEUE); // Register the workflows and activities worker.registerWorkflowImplementationTypes(HelloActivity.GreetingWorkflowImpl.class); worker.registerActivitiesImplementations(new HelloActivity.GreetingActivitiesImpl()); // Start listening to the workflow and activity task queues. factory.start(); // Start a workflow execution. HelloActivity.GreetingWorkflow workflow = client.newWorkflowStub( HelloActivity.GreetingWorkflow.class, WorkflowOptions.newBuilder().setTaskQueue(TASK_QUEUE).build()); // Execute a workflow waiting for it to complete. String greeting = workflow.getGreeting("My Secret Friend"); System.out.println(greeting); System.exit(0); } } ================================================ FILE: core/src/main/java/io/temporal/samples/keymanagementencryption/awsencryptionsdk/KeyringCodec.java ================================================ package io.temporal.samples.keymanagementencryption.awsencryptionsdk; import com.amazonaws.encryptionsdk.AwsCrypto; import com.google.protobuf.ByteString; import com.google.protobuf.InvalidProtocolBufferException; import io.temporal.api.common.v1.Payload; import io.temporal.common.converter.EncodingKeys; import io.temporal.payload.codec.PayloadCodec; import io.temporal.payload.context.ActivitySerializationContext; import io.temporal.payload.context.HasWorkflowSerializationContext; import io.temporal.payload.context.SerializationContext; import io.temporal.workflow.unsafe.WorkflowUnsafe; import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.jetbrains.annotations.NotNull; import software.amazon.cryptography.materialproviders.IKeyring; /** * KeyringCodec is a {@link PayloadCodec} that encrypts and decrypts payloads using the AWS * Encryption SDK. It uses the provided {@link IKeyring} to encrypt and decrypt payloads. It can * optionally support using a {@link SerializationContext}. */ class KeyringCodec implements PayloadCodec { // Metadata encoding key for the AWS Encryption SDK static final ByteString METADATA_ENCODING = ByteString.copyFrom("awsencriptionsdk/binary/encrypted", StandardCharsets.UTF_8); private final AwsCrypto crypto; private final IKeyring kmsKeyring; private final boolean useSerializationContext; @Nullable private final SerializationContext serializationContext; /** * Constructs a new KeyringCodec with the provided {@link IKeyring}. The codec will not use a * {@link SerializationContext}. * * @param kmsKeyring the keyring to use for encryption and decryption. */ public KeyringCodec(IKeyring kmsKeyring) { this.crypto = AwsCrypto.standard(); this.kmsKeyring = kmsKeyring; this.useSerializationContext = false; this.serializationContext = null; } /** * Constructs a new KeyringCodec with the provided {@link IKeyring}. * * @param crypto the AWS Crypto object to use for encryption and decryption. * @param kmsKeyring the keyring to use for encryption and decryption. * @param useSerializationContext whether to use a {@link SerializationContext} for encoding and * decoding payloads. */ public KeyringCodec(AwsCrypto crypto, IKeyring kmsKeyring, boolean useSerializationContext) { this.crypto = crypto; this.kmsKeyring = kmsKeyring; this.useSerializationContext = useSerializationContext; this.serializationContext = null; } private KeyringCodec( AwsCrypto crypto, IKeyring kmsKeyring, SerializationContext serializationContext) { this.crypto = crypto; this.kmsKeyring = kmsKeyring; this.useSerializationContext = true; this.serializationContext = serializationContext; } @NotNull @Override public List encode(@NotNull List payloads) { // Disable deadlock detection for encoding payloads because this may make a network call // to encrypt the data. return WorkflowUnsafe.deadlockDetectorOff( () -> payloads.stream().map(this::encodePayload).collect(Collectors.toList())); } @NotNull @Override public List decode(@NotNull List payloads) { // Disable deadlock detection for decoding payloads because this may make a network call // to decrypt the data. return WorkflowUnsafe.deadlockDetectorOff( () -> payloads.stream().map(this::decodePayload).collect(Collectors.toList())); } @NotNull @Override public PayloadCodec withContext(@Nonnull SerializationContext context) { if (!useSerializationContext) { return this; } return new KeyringCodec(crypto, kmsKeyring, context); } private Map getEncryptionContext() { // If we are not using a serialization context, return an empty map // There may not be a serialization context if certain cases, such as when the codec is used // for encoding/decoding payloads for a Nexus operation. if (!useSerializationContext || serializationContext == null || !(serializationContext instanceof HasWorkflowSerializationContext)) { return Collections.emptyMap(); } String workflowId = ((HasWorkflowSerializationContext) serializationContext).getWorkflowId(); String activityType = null; if (serializationContext instanceof ActivitySerializationContext) { activityType = ((ActivitySerializationContext) serializationContext).getActivityType(); } String signature = activityType != null ? workflowId + activityType : workflowId; return Collections.singletonMap("signature", signature); } private Payload encodePayload(Payload payload) { byte[] plaintext = payload.toByteArray(); byte[] ciphertext = crypto.encryptData(kmsKeyring, plaintext, getEncryptionContext()).getResult(); return Payload.newBuilder() .setData(ByteString.copyFrom(ciphertext)) .putMetadata(EncodingKeys.METADATA_ENCODING_KEY, METADATA_ENCODING) .build(); } private Payload decodePayload(Payload payload) { if (METADATA_ENCODING.equals( payload.getMetadataOrDefault(EncodingKeys.METADATA_ENCODING_KEY, null))) { byte[] ciphertext = payload.getData().toByteArray(); byte[] plaintext = crypto.decryptData(kmsKeyring, ciphertext, getEncryptionContext()).getResult(); try { return Payload.parseFrom(plaintext); } catch (InvalidProtocolBufferException e) { throw new RuntimeException(e); } } return payload; } } ================================================ FILE: core/src/main/java/io/temporal/samples/keymanagementencryption/awsencryptionsdk/README.md ================================================ ## AWS Encryption SDK Sample This sample demonstrates how a user can leverage the [AWS Encryption](https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/java.html) SDK to build a `PayloadCodec` to encrypt and decrypt payloads using [AWS KMS](https://aws.amazon.com/kms/) and envelope encryption. ### About the AWS Encryption SDK: >The AWS Encryption SDK is a client-side encryption library designed to make it easy for everyone to encrypt and decrypt data using industry standards and best practices. It enables you to focus on the core functionality of your application, rather than on how to best encrypt and decrypt your data. The AWS Encryption SDK is provided free of charge under the Apache 2.0 license. For more details please see [Amazons Documentation](https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/introduction.html) ### Choosing a Key Ring This sample uses am [AWS KMS keyring](https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/use-kms-keyring.html). This approach is convenient as you don't need to manage or secure your own keys. One drawback of this approach is it will require a call to KMS every time you need encrypt or decrypt data. If this is a concern you may want to consider using an [AWS KMS Hierarchical keyring](https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/use-hierarchical-keyring.html). Note: You can also use the AWS Encryption SDK without any AWS services using the raw keyrings. For more details please see [Amazons Documentation on choosing a key ring](https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/which-keyring.html). ### Running this sample Make sure your AWS account credentials are up-to-date and can access KMS. Export the following environment variables - `AWS_KEY_ARN`: Your AWS key ARN. ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.keymanagementencryption.awsencryptionsdk.EncryptedPayloads ``` ================================================ FILE: core/src/main/java/io/temporal/samples/listworkflows/Customer.java ================================================ package io.temporal.samples.listworkflows; public class Customer { private String accountNum; private String name; private String email; private String customerType; public Customer() {} public Customer(String accountNum, String name, String email, String customerType) { this.accountNum = accountNum; this.name = name; this.email = email; this.customerType = customerType; } public String getAccountNum() { return accountNum; } public void setAccountNum(String accountNum) { this.accountNum = accountNum; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getCustomerType() { return customerType; } public void setCustomerType(String customerType) { this.customerType = customerType; } } ================================================ FILE: core/src/main/java/io/temporal/samples/listworkflows/CustomerActivities.java ================================================ package io.temporal.samples.listworkflows; import io.temporal.activity.ActivityInterface; @ActivityInterface public interface CustomerActivities { void getCustomerAccount(Customer customer); void updateCustomerAccount(Customer customer, String message); void sendUpdateEmail(Customer customer); } ================================================ FILE: core/src/main/java/io/temporal/samples/listworkflows/CustomerActivitiesImpl.java ================================================ package io.temporal.samples.listworkflows; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CustomerActivitiesImpl implements CustomerActivities { private static final Logger log = LoggerFactory.getLogger(CustomerActivitiesImpl.class); @Override public void getCustomerAccount(Customer customer) { // simulate some actual work... sleepSeconds(1); } @Override public void updateCustomerAccount(Customer customer, String message) { // simulate some actual work... sleepSeconds(1); } @Override public void sendUpdateEmail(Customer customer) { // simulate some actual work... sleepSeconds(1); } private void sleepSeconds(int seconds) { try { Thread.sleep(TimeUnit.SECONDS.toMillis(seconds)); } catch (InterruptedException e) { // This is being swallowed on purpose Thread.currentThread().interrupt(); log.error("Exception in thread sleep: ", e); } } } ================================================ FILE: core/src/main/java/io/temporal/samples/listworkflows/CustomerWorkflow.java ================================================ package io.temporal.samples.listworkflows; import io.temporal.workflow.SignalMethod; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; @WorkflowInterface public interface CustomerWorkflow { @WorkflowMethod void updateAccountMessage(Customer customer, String message); @SignalMethod void exit(); } ================================================ FILE: core/src/main/java/io/temporal/samples/listworkflows/CustomerWorkflowImpl.java ================================================ package io.temporal.samples.listworkflows; import io.temporal.activity.ActivityOptions; import io.temporal.common.RetryOptions; import io.temporal.workflow.Workflow; import java.time.Duration; import java.util.Optional; public class CustomerWorkflowImpl implements CustomerWorkflow { private boolean exit; private final CustomerActivities customerActivities = Workflow.newActivityStub( CustomerActivities.class, ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(2)).build()); private final RetryOptions customerRetryOptions = RetryOptions.newBuilder().setMaximumAttempts(5).build(); private final Duration expiration = Duration.ofMinutes(1); @Override public void updateAccountMessage(Customer customer, String message) { Workflow.retry( customerRetryOptions, Optional.of(expiration), () -> { customerActivities.getCustomerAccount(customer); customerActivities.updateCustomerAccount(customer, message); customerActivities.sendUpdateEmail(customer); }); Workflow.await(Duration.ofMinutes(1), () -> exit); } @Override public void exit() { this.exit = true; } } ================================================ FILE: core/src/main/java/io/temporal/samples/listworkflows/README.md ================================================ # Demo List Workflows The sample demonstrates: 1) Setting custom search attributes for a Workflow 2) Using ListWorkflowExecutionsRequest and custom Search Attribute query to list Workflow Executions that match that query ## Running 1. Unlike the other examples, this one has to be started with Elasticsearch capabilities enabled. If you are using docker you can do that with: ```bash git clone https://github.com/temporalio/docker-compose.git cd docker-compose docker-compose -f docker-compose-cas-es.yml up ``` 2. Run the following command to start the sample: ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.listworkflows.Starter ``` ================================================ FILE: core/src/main/java/io/temporal/samples/listworkflows/Starter.java ================================================ package io.temporal.samples.listworkflows; import io.temporal.api.enums.v1.WorkflowExecutionStatus; import io.temporal.api.workflow.v1.WorkflowExecutionInfo; import io.temporal.api.workflowservice.v1.ListWorkflowExecutionsRequest; import io.temporal.api.workflowservice.v1.ListWorkflowExecutionsResponse; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; public class Starter { public static final String TASK_QUEUE = "customerTaskQueue"; private static WorkflowServiceStubs service; private static WorkflowClient client; private static WorkerFactory factory; public static void main(String[] args) { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); factory = WorkerFactory.newInstance(client); // create some fake customers List customers = new ArrayList<>(); customers.add(new Customer("c1", "John", "john@john.com", "new")); customers.add(new Customer("c2", "Mary", "mary@mary.com", "established")); customers.add(new Customer("c3", "Richard", "richard@richard.com", "established")); customers.add(new Customer("c4", "Anna", "anna@anna.com", "new")); customers.add(new Customer("c5", "Michael", "michael@michael.com", "established")); // create the worker for workflow and activities createWorker(); // start customer workflows and define custom search attributes for each startWorkflows(customers); // small delay before we start querying executions try { Thread.sleep(2 * 1000); } catch (InterruptedException e) { throw new RuntimeException("Exception happened in thread sleep: ", e); } // query "new" customers for all "CustomerWorkflow" workflows with status "Running" (1) ListWorkflowExecutionsResponse newCustomersResponse = getExecutionsResponse( "WorkflowType='CustomerWorkflow' and CustomStringField='new' and ExecutionStatus=" + WorkflowExecutionStatus.WORKFLOW_EXECUTION_STATUS_RUNNING_VALUE); System.out.println("***** Customers with type 'new'"); System.out.println( "Currently being processed: " + newCustomersResponse.getExecutionsList().size()); List newExecutionInfo = newCustomersResponse.getExecutionsList(); for (WorkflowExecutionInfo wei : newExecutionInfo) { System.out.println("Customer: " + wei.getExecution().getWorkflowId()); } // query "established" customers for all "CustomerWorkflow" workflows with status "Running" (1) ListWorkflowExecutionsResponse establishedCustomersResponse = getExecutionsResponse( "WorkflowType = 'CustomerWorkflow' and CustomStringField='established' and ExecutionStatus=" + WorkflowExecutionStatus.WORKFLOW_EXECUTION_STATUS_RUNNING_VALUE); System.out.println("\n***** Customers with type 'established'"); System.out.println( "Currently being processed: " + establishedCustomersResponse.getExecutionsList().size()); List establishedExecutionInfo = establishedCustomersResponse.getExecutionsList(); for (WorkflowExecutionInfo wei : establishedExecutionInfo) { System.out.println("Customer: " + wei.getExecution().getWorkflowId()); } // signal exit to all customer workflows stopWorkflows(customers); // sleep for 3 seconds before we shut down the worker sleep(3); System.exit(0); } private static ListWorkflowExecutionsResponse getExecutionsResponse(String query) { ListWorkflowExecutionsRequest listWorkflowExecutionRequest = ListWorkflowExecutionsRequest.newBuilder() .setNamespace(client.getOptions().getNamespace()) .setQuery(query) .build(); ListWorkflowExecutionsResponse listWorkflowExecutionsResponse = service.blockingStub().listWorkflowExecutions(listWorkflowExecutionRequest); return listWorkflowExecutionsResponse; } private static void createWorker() { Worker worker = factory.newWorker(TASK_QUEUE); worker.registerWorkflowImplementationTypes(CustomerWorkflowImpl.class); worker.registerActivitiesImplementations(new CustomerActivitiesImpl()); factory.start(); } private static Map generateSearchAttributesFor(Customer customer) { Map searchAttributes = new HashMap<>(); searchAttributes.put("CustomStringField", customer.getCustomerType()); return searchAttributes; } private static void startWorkflows(List customers) { // start a workflow for each customer that we need to add message to account for (Customer c : customers) { String message = "New message for: " + c.getName(); WorkflowOptions newCustomerWorkflowOptions = WorkflowOptions.newBuilder() .setWorkflowId(c.getAccountNum()) .setTaskQueue(TASK_QUEUE) // set the search attributes for this customer workflow .setSearchAttributes(generateSearchAttributesFor(c)) .build(); CustomerWorkflow newCustomerWorkflow = client.newWorkflowStub(CustomerWorkflow.class, newCustomerWorkflowOptions); // start async WorkflowClient.start(newCustomerWorkflow::updateAccountMessage, c, message); } } private static void stopWorkflows(List customers) { for (Customer c : customers) { CustomerWorkflow existingCustomerWorkflow = client.newWorkflowStub(CustomerWorkflow.class, c.getAccountNum()); // signal the exist method to stop execution existingCustomerWorkflow.exit(); } } private static void sleep(int seconds) { try { Thread.sleep(TimeUnit.SECONDS.toMillis(seconds)); } catch (InterruptedException e) { System.out.println("Exception: " + e.getMessage()); System.exit(0); } } } ================================================ FILE: core/src/main/java/io/temporal/samples/metrics/MetricsStarter.java ================================================ package io.temporal.samples.metrics; import com.sun.net.httpserver.HttpServer; import com.uber.m3.tally.RootScopeBuilder; import com.uber.m3.tally.Scope; import com.uber.m3.util.ImmutableMap; import io.micrometer.prometheus.PrometheusConfig; import io.micrometer.prometheus.PrometheusMeterRegistry; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.common.reporter.MicrometerClientStatsReporter; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.samples.metrics.workflow.MetricsWorkflow; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.serviceclient.WorkflowServiceStubsOptions; import java.io.IOException; public class MetricsStarter { public static void main(String[] args) { // Set up prometheus registry and stats reported PrometheusMeterRegistry registry = new PrometheusMeterRegistry(PrometheusConfig.DEFAULT); // Set up a new scope, report every 1 second Scope scope = new RootScopeBuilder() // shows how to set custom tags .tags( ImmutableMap.of( "starterCustomTag1", "starterCustomTag1Value", "starterCustomTag2", "starterCustomTag2Value")) .reporter(new MicrometerClientStatsReporter(registry)) .reportEvery(com.uber.m3.util.Duration.ofSeconds(1)); // Start the prometheus scrape endpoint for starter metrics HttpServer scrapeEndpoint = MetricsUtils.startPrometheusScrapeEndpoint(registry, 8078); // Stopping the starter will stop the http server that exposes the // scrape endpoint. Runtime.getRuntime().addShutdownHook(new Thread(() -> scrapeEndpoint.stop(1))); // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } // Add metrics scope to workflow service stub options, preserving env config WorkflowServiceStubsOptions stubOptions = WorkflowServiceStubsOptions.newBuilder(profile.toWorkflowServiceStubsOptions()) .setMetricsScope(scope) .build(); WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(stubOptions); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); WorkflowOptions workflowOptions = WorkflowOptions.newBuilder() .setWorkflowId("metricsWorkflow") .setTaskQueue(MetricsWorker.DEFAULT_TASK_QUEUE_NAME) .build(); MetricsWorkflow workflow = client.newWorkflowStub(MetricsWorkflow.class, workflowOptions); String result = workflow.exec("hello metrics"); System.out.println("Result: " + result); System.out.println("Starter metrics are available at http://localhost:8078/metrics"); // We don't shut down the process here so metrics can be viewed. } } ================================================ FILE: core/src/main/java/io/temporal/samples/metrics/MetricsUtils.java ================================================ package io.temporal.samples.metrics; import static java.nio.charset.StandardCharsets.UTF_8; import com.sun.net.httpserver.HttpServer; import io.micrometer.prometheus.PrometheusMeterRegistry; import java.io.IOException; import java.io.OutputStream; import java.net.InetSocketAddress; public class MetricsUtils { /** * Starts HttpServer to expose a scrape endpoint. See * https://micrometer.io/docs/registry/prometheus for more info. */ public static HttpServer startPrometheusScrapeEndpoint( PrometheusMeterRegistry registry, int port) { try { HttpServer server = HttpServer.create(new InetSocketAddress(port), 0); server.createContext( "/metrics", httpExchange -> { String response = registry.scrape(); httpExchange.sendResponseHeaders(200, response.getBytes(UTF_8).length); try (OutputStream os = httpExchange.getResponseBody()) { os.write(response.getBytes(UTF_8)); } }); server.start(); return server; } catch (IOException e) { throw new RuntimeException(e); } } } ================================================ FILE: core/src/main/java/io/temporal/samples/metrics/MetricsWorker.java ================================================ package io.temporal.samples.metrics; import com.sun.net.httpserver.HttpServer; import com.uber.m3.tally.RootScopeBuilder; import com.uber.m3.tally.Scope; import com.uber.m3.util.ImmutableMap; import io.micrometer.prometheus.PrometheusConfig; import io.micrometer.prometheus.PrometheusMeterRegistry; import io.temporal.client.WorkflowClient; import io.temporal.common.reporter.MicrometerClientStatsReporter; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.samples.metrics.activities.MetricsActivitiesImpl; import io.temporal.samples.metrics.workflow.MetricsWorkflowImpl; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.serviceclient.WorkflowServiceStubsOptions; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import java.io.IOException; public class MetricsWorker { // task queue to be used for this sample public static final String DEFAULT_TASK_QUEUE_NAME = "metricsqueue"; public static void main(String[] args) { // Set up prometheus registry and stats reported PrometheusMeterRegistry registry = new PrometheusMeterRegistry(PrometheusConfig.DEFAULT); // Set up a new scope, report every 1 second Scope scope = new RootScopeBuilder() // shows how to set custom tags .tags( ImmutableMap.of( "workerCustomTag1", "workerCustomTag1Value", "workerCustomTag2", "workerCustomTag2Value")) .reporter(new MicrometerClientStatsReporter(registry)) .reportEvery(com.uber.m3.util.Duration.ofSeconds(1)); // Start the prometheus scrape endpoint HttpServer scrapeEndpoint = MetricsUtils.startPrometheusScrapeEndpoint(registry, 8077); // Stopping the worker will stop the http server that exposes the // scrape endpoint. Runtime.getRuntime().addShutdownHook(new Thread(() -> scrapeEndpoint.stop(1))); // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } // Add metrics scope to workflow service stub options, preserving env config WorkflowServiceStubsOptions stubOptions = WorkflowServiceStubsOptions.newBuilder(profile.toWorkflowServiceStubsOptions()) .setMetricsScope(scope) .build(); WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(stubOptions); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); WorkerFactory factory = WorkerFactory.newInstance(client); Worker worker = factory.newWorker(DEFAULT_TASK_QUEUE_NAME); worker.registerWorkflowImplementationTypes(MetricsWorkflowImpl.class); worker.registerActivitiesImplementations(new MetricsActivitiesImpl()); factory.start(); System.out.println("Workers metrics are available at http://localhost:8077/metrics"); } } ================================================ FILE: core/src/main/java/io/temporal/samples/metrics/README.md ================================================ # Setting up SDK metrics (Prometheus) This sample shows setup for SDK metrics. 1. Start the Worker: ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.metrics.MetricsWorker ``` 2. Start the Starter: ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.metrics.MetricsStarter ``` 3. See the worker metrics on the exposed Prometheus Scrape Endpoint: [http://localhost:8077/metrics](http://localhost:8077/metrics) 4. See the starter metrics on the exposed Prometheus Scrape Endpoint [http://localhost:8078/metrics](http://localhost:8078/metrics) 5. Stop the worker and starter ================================================ FILE: core/src/main/java/io/temporal/samples/metrics/activities/MetricsActivities.java ================================================ package io.temporal.samples.metrics.activities; import io.temporal.activity.ActivityInterface; @ActivityInterface public interface MetricsActivities { String performA(String input); String performB(String input); } ================================================ FILE: core/src/main/java/io/temporal/samples/metrics/activities/MetricsActivitiesImpl.java ================================================ package io.temporal.samples.metrics.activities; import io.temporal.activity.Activity; import io.temporal.activity.ActivityExecutionContext; public class MetricsActivitiesImpl implements MetricsActivities { @Override public String performA(String input) { // simulate some failures to trigger retries if (Activity.getExecutionContext().getInfo().getAttempt() < 3) { incRetriesCustomMetric(Activity.getExecutionContext()); throw Activity.wrap(new NullPointerException("simulated")); } return "Performed activity A with input " + input + "\n"; } @Override public String performB(String input) { // simulate some failures to trigger retries if (Activity.getExecutionContext().getInfo().getAttempt() < 5) { incRetriesCustomMetric(Activity.getExecutionContext()); throw Activity.wrap(new NullPointerException("simulated")); } return "Performed activity B with input " + input + "\n"; } private void incRetriesCustomMetric(ActivityExecutionContext context) { // We can create a child scope and add extra tags // Scope scope = // context // .getMetricsScope() // .tagged( // Stream.of( // new String[][] { // {"workflow_id", context.getInfo().getWorkflowId()}, // {"activity_id", context.getInfo().getActivityId()}, // { // "activity_start_to_close_timeout", // context.getInfo().getStartToCloseTimeout().toString() // }, // }) // .collect(Collectors.toMap(data -> data[0], data -> data[1]))); // // scope.counter("custom_activity_retries").inc(1); // For sample we use root scope context.getMetricsScope().counter("custom_activity_retries").inc(1); } } ================================================ FILE: core/src/main/java/io/temporal/samples/metrics/workflow/MetricsWorkflow.java ================================================ package io.temporal.samples.metrics.workflow; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; @WorkflowInterface public interface MetricsWorkflow { @WorkflowMethod String exec(String input); } ================================================ FILE: core/src/main/java/io/temporal/samples/metrics/workflow/MetricsWorkflowImpl.java ================================================ package io.temporal.samples.metrics.workflow; import com.uber.m3.tally.Scope; import io.temporal.activity.ActivityOptions; import io.temporal.samples.metrics.activities.MetricsActivities; import io.temporal.workflow.Workflow; import java.time.Duration; import java.util.Collections; public class MetricsWorkflowImpl implements MetricsWorkflow { private final MetricsActivities activities = Workflow.newActivityStub( MetricsActivities.class, ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(2)).build()); @Override public String exec(String input) { /* * Custom metric, we can use child scope and attach workflow_id as it's not attached by default * like task_queue ,workflow_type, etc */ Scope scope = Workflow.getMetricsScope() .tagged(Collections.singletonMap("workflow_id", Workflow.getInfo().getWorkflowId())); scope.counter("custom_metric").inc(1); String result = activities.performA(input); Workflow.sleep(Duration.ofSeconds(5)); result += activities.performB(input); return result; } } ================================================ FILE: core/src/main/java/io/temporal/samples/moneybatch/Account.java ================================================ package io.temporal.samples.moneybatch; import io.temporal.activity.ActivityInterface; @ActivityInterface public interface Account { void deposit(String accountId, String referenceId, int amountCents); void withdraw(String accountId, String referenceId, int amountCents); } ================================================ FILE: core/src/main/java/io/temporal/samples/moneybatch/AccountActivityWorker.java ================================================ package io.temporal.samples.moneybatch; import io.temporal.client.WorkflowClient; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import java.io.IOException; public class AccountActivityWorker { static final String TASK_QUEUE = "Account"; @SuppressWarnings("CatchAndPrintStackTrace") public static void main(String[] args) { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); WorkerFactory factory = WorkerFactory.newInstance(client); Worker worker = factory.newWorker(TASK_QUEUE); Account account = new AccountImpl(); worker.registerActivitiesImplementations(account); factory.start(); System.out.println("Activity Worker started for task queue: " + TASK_QUEUE); } } ================================================ FILE: core/src/main/java/io/temporal/samples/moneybatch/AccountImpl.java ================================================ package io.temporal.samples.moneybatch; public class AccountImpl implements Account { @Override public void deposit(String accountId, String referenceId, int amountCents) { System.out.printf( "Deposit to %s of %d cents requested. ReferenceId=%s\n", accountId, amountCents, referenceId); // throw new RuntimeException("simulated"); // Uncomment to simulate failure } @Override public void withdraw(String accountId, String referenceId, int amountCents) { System.out.printf( "Withdraw to %s of %d cents requested. ReferenceId=%s\n", accountId, amountCents, referenceId); } } ================================================ FILE: core/src/main/java/io/temporal/samples/moneybatch/AccountTransferWorker.java ================================================ package io.temporal.samples.moneybatch; import io.temporal.client.WorkflowClient; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import java.io.IOException; public class AccountTransferWorker { @SuppressWarnings("CatchAndPrintStackTrace") public static void main(String[] args) { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); WorkerFactory factory = WorkerFactory.newInstance(client); Worker worker = factory.newWorker(AccountActivityWorker.TASK_QUEUE); worker.registerWorkflowImplementationTypes(AccountTransferWorkflowImpl.class); factory.start(); System.out.println("Worker started for task queue: " + AccountActivityWorker.TASK_QUEUE); } } ================================================ FILE: core/src/main/java/io/temporal/samples/moneybatch/AccountTransferWorkflow.java ================================================ package io.temporal.samples.moneybatch; import io.temporal.workflow.QueryMethod; import io.temporal.workflow.SignalMethod; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; @WorkflowInterface public interface AccountTransferWorkflow { @WorkflowMethod void deposit(String toAccountId, int batchSize); @SignalMethod void withdraw(String fromAccountId, String referenceId, int amountCents); @QueryMethod int getBalance(); @QueryMethod int getCount(); } ================================================ FILE: core/src/main/java/io/temporal/samples/moneybatch/AccountTransferWorkflowImpl.java ================================================ package io.temporal.samples.moneybatch; import io.temporal.activity.ActivityOptions; import io.temporal.common.RetryOptions; import io.temporal.workflow.Workflow; import java.time.Duration; import java.util.HashSet; import java.util.Set; public class AccountTransferWorkflowImpl implements AccountTransferWorkflow { private final ActivityOptions options = ActivityOptions.newBuilder() .setStartToCloseTimeout(Duration.ofSeconds(5)) .setRetryOptions( RetryOptions.newBuilder() .setInitialInterval(Duration.ofSeconds(1)) .setMaximumInterval(Duration.ofSeconds(10)) .build()) .build(); private final Account account = Workflow.newActivityStub(Account.class, options); private Set references = new HashSet<>(); private int balance; private int count; @Override public void deposit(String toAccount, int batchSize) { Workflow.await(() -> count == batchSize); String referenceId = Workflow.randomUUID().toString(); account.deposit(toAccount, referenceId, balance); } @Override public void withdraw(String fromAccountId, String referenceId, int amountCents) { if (!references.add(referenceId)) { return; // duplicate } account.withdraw(fromAccountId, referenceId, amountCents); balance += amountCents; count++; } @Override public int getBalance() { return balance; } @Override public int getCount() { return count; } } ================================================ FILE: core/src/main/java/io/temporal/samples/moneybatch/README.md ================================================ # Demonstrates Signal Batching Demonstrates a situation when a single deposit should be initiated for multiple withdrawals. For example, a seller might want to be paid once per fixed number of transactions. The sample can be easily extended to perform a payment based on more complex criteria like a specific time or accumulated amount. The sample also demonstrates the *signal with start* way of starting Workflows. If the Workflow is already running, it just receives the Signal. If it is not running, then it is started first, and then the signal is delivered to it. You can think about *signal with start* as a lazy way to create Workflows when signaling them. **How to run the Money Batch Sample** Money Batch sample has three separate processes. One to host Workflow Executions, another to host Activity Executions, and the third one to request transfers (start Workflow Executions). Start Workflow Worker: ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.moneybatch.AccountTransferWorker ``` Start Activity Worker: ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.moneybatch.AccountActivityWorker ``` Execute at least three times to request three transfers (example batch size): ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.moneybatch.TransferRequester ``` ================================================ FILE: core/src/main/java/io/temporal/samples/moneybatch/TransferRequester.java ================================================ package io.temporal.samples.moneybatch; import io.temporal.client.BatchRequest; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import java.io.IOException; import java.util.Random; import java.util.UUID; public class TransferRequester { /** Number of withdrawals to batch */ public static final int BATCH_SIZE = 3; @SuppressWarnings("CatchAndPrintStackTrace") public static void main(String[] args) { String reference = UUID.randomUUID().toString(); int amountCents = (new Random().nextInt(5) + 1) * 25; // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient workflowClient = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); String from = "account1"; String to = "account2"; WorkflowOptions options = WorkflowOptions.newBuilder() .setTaskQueue(AccountActivityWorker.TASK_QUEUE) .setWorkflowId(to) .build(); AccountTransferWorkflow transferWorkflow = workflowClient.newWorkflowStub(AccountTransferWorkflow.class, options); // Signal with start sends a signal to a workflow starting it if not yet running BatchRequest request = workflowClient.newSignalWithStartRequest(); request.add(transferWorkflow::deposit, to, BATCH_SIZE); request.add(transferWorkflow::withdraw, from, reference, amountCents); workflowClient.signalWithStart(request); System.out.printf("Transfer of %d cents from %s to %s requested", amountCents, from, to); System.exit(0); } } ================================================ FILE: core/src/main/java/io/temporal/samples/moneytransfer/Account.java ================================================ package io.temporal.samples.moneytransfer; import io.temporal.activity.ActivityInterface; @ActivityInterface public interface Account { void deposit(String accountId, String referenceId, int amountCents); void withdraw(String accountId, String referenceId, int amountCents); } ================================================ FILE: core/src/main/java/io/temporal/samples/moneytransfer/AccountActivityWorker.java ================================================ package io.temporal.samples.moneytransfer; import io.temporal.client.WorkflowClient; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import java.io.IOException; public class AccountActivityWorker { public static final String TASK_QUEUE = "AccountTransfer"; @SuppressWarnings("CatchAndPrintStackTrace") public static void main(String[] args) { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } // gRPC stubs wrapper that talks to the temporal service. WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); // client that can be used to start and signal workflows WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); // worker factory that can be used to create workers for specific task queues WorkerFactory factory = WorkerFactory.newInstance(client); Worker worker = factory.newWorker(TASK_QUEUE); Account account = new AccountImpl(); worker.registerActivitiesImplementations(account); // Start all workers created by this factory. factory.start(); System.out.println("Activity Worker started for task queue: " + TASK_QUEUE); } } ================================================ FILE: core/src/main/java/io/temporal/samples/moneytransfer/AccountImpl.java ================================================ package io.temporal.samples.moneytransfer; public class AccountImpl implements Account { @Override public void withdraw(String accountId, String referenceId, int amountCents) { System.out.printf( "Withdraw to %s of %d cents requested. ReferenceId=%s\n", accountId, amountCents, referenceId); } @Override public void deposit(String accountId, String referenceId, int amountCents) { System.out.printf( "Deposit to %s of %d cents requested. ReferenceId=%s\n", accountId, amountCents, referenceId); // throw new RuntimeException("simulated"); } } ================================================ FILE: core/src/main/java/io/temporal/samples/moneytransfer/AccountTransferWorker.java ================================================ package io.temporal.samples.moneytransfer; import static io.temporal.samples.moneytransfer.AccountActivityWorker.TASK_QUEUE; import io.temporal.client.WorkflowClient; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import java.io.IOException; public class AccountTransferWorker { @SuppressWarnings("CatchAndPrintStackTrace") public static void main(String[] args) { // Get worker to poll the common task queue. // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } // gRPC stubs wrapper that talks to the temporal service. WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); // client that can be used to start and signal workflows WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); // worker factory that can be used to create workers for specific task queues WorkerFactory factory = WorkerFactory.newInstance(client); Worker worker = factory.newWorker(TASK_QUEUE); worker.registerWorkflowImplementationTypes(AccountTransferWorkflowImpl.class); // Start all workers created by this factory. factory.start(); System.out.println("Worker started for task queue: " + TASK_QUEUE); } } ================================================ FILE: core/src/main/java/io/temporal/samples/moneytransfer/AccountTransferWorkflow.java ================================================ package io.temporal.samples.moneytransfer; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; @WorkflowInterface public interface AccountTransferWorkflow { @WorkflowMethod void transfer(String fromAccountId, String toAccountId, String referenceId, int amountCents); } ================================================ FILE: core/src/main/java/io/temporal/samples/moneytransfer/AccountTransferWorkflowImpl.java ================================================ package io.temporal.samples.moneytransfer; import io.temporal.activity.ActivityOptions; import io.temporal.workflow.Workflow; import java.time.Duration; public class AccountTransferWorkflowImpl implements AccountTransferWorkflow { private final ActivityOptions options = ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(5)).build(); private final Account account = Workflow.newActivityStub(Account.class, options); @Override public void transfer( String fromAccountId, String toAccountId, String referenceId, int amountCents) { account.withdraw(fromAccountId, referenceId, amountCents); account.deposit(toAccountId, referenceId, amountCents); } } ================================================ FILE: core/src/main/java/io/temporal/samples/moneytransfer/README.MD ================================================ The Money Transfer sample has three separate processes. One to host Workflow Executions, another to host Activity Executions, and the third one to request transfers (start Workflow Executions). Start Workflow Worker: ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.moneytransfer.AccountTransferWorker ``` Start Activity Worker: ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.moneytransfer.AccountActivityWorker ``` Execute once per requested transfer: ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.moneytransfer.TransferRequester ``` ================================================ FILE: core/src/main/java/io/temporal/samples/moneytransfer/TransferRequester.java ================================================ package io.temporal.samples.moneytransfer; import static io.temporal.samples.moneytransfer.AccountActivityWorker.TASK_QUEUE; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import java.io.IOException; import java.util.Random; import java.util.UUID; public class TransferRequester { @SuppressWarnings("CatchAndPrintStackTrace") public static void main(String[] args) { String reference; int amountCents; if (args.length == 0) { reference = UUID.randomUUID().toString(); amountCents = new Random().nextInt(5000); } else { reference = args[0]; amountCents = Integer.parseInt(args[1]); } // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); // client that can be used to start and signal workflows WorkflowClient workflowClient = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); // now we can start running instances of the saga - its state will be persisted WorkflowOptions options = WorkflowOptions.newBuilder().setTaskQueue(TASK_QUEUE).build(); AccountTransferWorkflow transferWorkflow = workflowClient.newWorkflowStub(AccountTransferWorkflow.class, options); String from = "account1"; String to = "account2"; WorkflowClient.start(transferWorkflow::transfer, from, to, reference, amountCents); System.out.printf("Transfer of %d cents from %s to %s requested", amountCents, from, to); System.exit(0); } } ================================================ FILE: core/src/main/java/io/temporal/samples/nexus/README.MD ================================================ # Nexus Temporal Nexus is a new feature of the Temporal platform designed to connect durable executions across team, namespace, region, and cloud boundaries. It promotes a more modular architecture for sharing a subset of your team’s capabilities via well-defined service API contracts for other teams to use, that abstract underlying Temporal primitives, like Workflows, or execute arbitrary code. Learn more at [temporal.io/nexus](https://temporal.io/nexus). This sample shows how to use Temporal for authoring a Nexus service and call it from a workflow. ### Sample directory structure - [service](./service) - shared service definition - [caller](./caller) - caller workflows, worker, and starter - [handler](./handler) - handler workflow, operations, and worker - [options](./options) - command line argument parsing utility ## Getting started locally ### Get `temporal` CLI to enable local development 1. Follow the instructions on the [docs site](https://learn.temporal.io/getting_started/go/dev_environment/#set-up-a-local-temporal-service-for-development-with-temporal-cli) to install Temporal CLI. > NOTE: The recommended version is at least v1.3.0. ### Spin up environment #### Start temporal server > HTTP port is required for Nexus communications ``` temporal server start-dev ``` ### Initialize environment In a separate terminal window #### Create caller and target namespaces ``` temporal operator namespace create --namespace my-target-namespace temporal operator namespace create --namespace my-caller-namespace ``` #### Create Nexus endpoint ``` temporal operator nexus endpoint create \ --name my-nexus-endpoint-name \ --target-namespace my-target-namespace \ --target-task-queue my-handler-task-queue \ --description-file ./core/src/main/java/io/temporal/samples/nexus/service/description.md ``` ## Getting started with a self-hosted service or Temporal Cloud Nexus is currently available as [Public Preview](https://docs.temporal.io/evaluate/development-production-features/release-stages). Self hosted users can [try Nexus out](https://github.com/temporalio/temporal/blob/main/docs/architecture/nexus.md#trying-nexus-out) in single cluster deployments with server version 1.25.0. ### Make Nexus calls across namespace boundaries > Instructions apply for local development, for Temporal Cloud or a self-hosted setups, supply the relevant [CLI > flags](./options/ClientOptions.java) to properly set up the connection. In separate terminal windows: ### Nexus handler worker ``` ./gradlew -q execute -PmainClass=io.temporal.samples.nexus.handler.HandlerWorker \ --args="-target-host localhost:7233 -namespace my-target-namespace" ``` ### Nexus caller worker ``` ./gradlew -q execute -PmainClass=io.temporal.samples.nexus.caller.CallerWorker \ --args="-target-host localhost:7233 -namespace my-caller-namespace" ``` ### Start caller workflow ``` ./gradlew -q execute -PmainClass=io.temporal.samples.nexus.caller.CallerStarter \ --args="-target-host localhost:7233 -namespace my-caller-namespace" ``` ### Output which should result in: ``` [main] INFO i.t.s.nexus.caller.CallerStarter - Workflow result: Nexus Echo 👋 [main] INFO i.t.s.nexus.caller.CallerStarter - Workflow result: ¡Hola! Nexus 👋 ``` ================================================ FILE: core/src/main/java/io/temporal/samples/nexus/caller/CallerStarter.java ================================================ package io.temporal.samples.nexus.caller; import io.temporal.api.common.v1.WorkflowExecution; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.samples.nexus.options.ClientOptions; import io.temporal.samples.nexus.service.SampleNexusService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CallerStarter { private static final Logger logger = LoggerFactory.getLogger(CallerStarter.class); public static void main(String[] args) { WorkflowClient client = ClientOptions.getWorkflowClient(args); WorkflowOptions workflowOptions = WorkflowOptions.newBuilder().setTaskQueue(CallerWorker.DEFAULT_TASK_QUEUE_NAME).build(); EchoCallerWorkflow echoWorkflow = client.newWorkflowStub(EchoCallerWorkflow.class, workflowOptions); WorkflowExecution execution = WorkflowClient.start(echoWorkflow::echo, "Nexus Echo 👋"); logger.info( "Started EchoCallerWorkflow workflowId: {} runId: {}", execution.getWorkflowId(), execution.getRunId()); logger.info("Workflow result: {}", echoWorkflow.echo("Nexus Echo 👋")); HelloCallerWorkflow helloWorkflow = client.newWorkflowStub(HelloCallerWorkflow.class, workflowOptions); execution = WorkflowClient.start(helloWorkflow::hello, "Nexus", SampleNexusService.Language.EN); logger.info( "Started HelloCallerWorkflow workflowId: {} runId: {}", execution.getWorkflowId(), execution.getRunId()); logger.info( "Workflow result: {}", helloWorkflow.hello("Nexus", SampleNexusService.Language.ES)); } } ================================================ FILE: core/src/main/java/io/temporal/samples/nexus/caller/CallerWorker.java ================================================ package io.temporal.samples.nexus.caller; import io.temporal.client.WorkflowClient; import io.temporal.samples.nexus.options.ClientOptions; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import io.temporal.worker.WorkflowImplementationOptions; import io.temporal.workflow.NexusServiceOptions; import java.util.Collections; public class CallerWorker { public static final String DEFAULT_TASK_QUEUE_NAME = "my-caller-workflow-task-queue"; public static void main(String[] args) { WorkflowClient client = ClientOptions.getWorkflowClient(args); WorkerFactory factory = WorkerFactory.newInstance(client); Worker worker = factory.newWorker(DEFAULT_TASK_QUEUE_NAME); worker.registerWorkflowImplementationTypes( WorkflowImplementationOptions.newBuilder() .setNexusServiceOptions( Collections.singletonMap( "SampleNexusService", NexusServiceOptions.newBuilder().setEndpoint("my-nexus-endpoint-name").build())) .build(), EchoCallerWorkflowImpl.class, HelloCallerWorkflowImpl.class); factory.start(); } } ================================================ FILE: core/src/main/java/io/temporal/samples/nexus/caller/EchoCallerWorkflow.java ================================================ package io.temporal.samples.nexus.caller; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; @WorkflowInterface public interface EchoCallerWorkflow { @WorkflowMethod String echo(String message); } ================================================ FILE: core/src/main/java/io/temporal/samples/nexus/caller/EchoCallerWorkflowImpl.java ================================================ package io.temporal.samples.nexus.caller; import io.temporal.samples.nexus.service.SampleNexusService; import io.temporal.workflow.NexusOperationOptions; import io.temporal.workflow.NexusServiceOptions; import io.temporal.workflow.Workflow; import java.time.Duration; public class EchoCallerWorkflowImpl implements EchoCallerWorkflow { SampleNexusService sampleNexusService = Workflow.newNexusServiceStub( SampleNexusService.class, NexusServiceOptions.newBuilder() .setOperationOptions( NexusOperationOptions.newBuilder() .setScheduleToCloseTimeout(Duration.ofSeconds(10)) .build()) .build()); @Override public String echo(String message) { return sampleNexusService.echo(new SampleNexusService.EchoInput(message)).getMessage(); } } ================================================ FILE: core/src/main/java/io/temporal/samples/nexus/caller/HelloCallerWorkflow.java ================================================ package io.temporal.samples.nexus.caller; import io.temporal.samples.nexus.service.SampleNexusService; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; @WorkflowInterface public interface HelloCallerWorkflow { @WorkflowMethod String hello(String message, SampleNexusService.Language language); } ================================================ FILE: core/src/main/java/io/temporal/samples/nexus/caller/HelloCallerWorkflowImpl.java ================================================ package io.temporal.samples.nexus.caller; import io.temporal.samples.nexus.service.SampleNexusService; import io.temporal.workflow.NexusOperationHandle; import io.temporal.workflow.NexusOperationOptions; import io.temporal.workflow.NexusServiceOptions; import io.temporal.workflow.Workflow; import java.time.Duration; public class HelloCallerWorkflowImpl implements HelloCallerWorkflow { SampleNexusService sampleNexusService = Workflow.newNexusServiceStub( SampleNexusService.class, NexusServiceOptions.newBuilder() .setOperationOptions( NexusOperationOptions.newBuilder() .setScheduleToCloseTimeout(Duration.ofSeconds(10)) .build()) .build()); @Override public String hello(String message, SampleNexusService.Language language) { NexusOperationHandle handle = Workflow.startNexusOperation( sampleNexusService::hello, new SampleNexusService.HelloInput(message, language)); // Optionally wait for the operation to be started. NexusOperationExecution will contain the // operation token in case this operation is asynchronous. handle.getExecution().get(); return handle.getResult().get().getMessage(); } } ================================================ FILE: core/src/main/java/io/temporal/samples/nexus/handler/EchoClient.java ================================================ package io.temporal.samples.nexus.handler; import io.temporal.samples.nexus.service.SampleNexusService; public interface EchoClient { SampleNexusService.EchoOutput echo(SampleNexusService.EchoInput input); } ================================================ FILE: core/src/main/java/io/temporal/samples/nexus/handler/EchoClientImpl.java ================================================ package io.temporal.samples.nexus.handler; import io.temporal.samples.nexus.service.SampleNexusService; // Note that this is a class, not a Temporal worker. This is to demonstrate that Nexus services can // simply call a class instead of a worker for fast operations that don't need retry handling. public class EchoClientImpl implements EchoClient { @Override public SampleNexusService.EchoOutput echo(SampleNexusService.EchoInput input) { return new SampleNexusService.EchoOutput(input.getMessage()); } } ================================================ FILE: core/src/main/java/io/temporal/samples/nexus/handler/HandlerWorker.java ================================================ package io.temporal.samples.nexus.handler; import io.temporal.client.WorkflowClient; import io.temporal.samples.nexus.options.ClientOptions; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; public class HandlerWorker { public static final String DEFAULT_TASK_QUEUE_NAME = "my-handler-task-queue"; public static void main(String[] args) { WorkflowClient client = ClientOptions.getWorkflowClient(args); WorkerFactory factory = WorkerFactory.newInstance(client); Worker worker = factory.newWorker(DEFAULT_TASK_QUEUE_NAME); worker.registerWorkflowImplementationTypes(HelloHandlerWorkflowImpl.class); worker.registerNexusServiceImplementation(new SampleNexusServiceImpl()); factory.start(); } } ================================================ FILE: core/src/main/java/io/temporal/samples/nexus/handler/HelloHandlerWorkflow.java ================================================ package io.temporal.samples.nexus.handler; import io.temporal.samples.nexus.service.SampleNexusService; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; @WorkflowInterface public interface HelloHandlerWorkflow { @WorkflowMethod SampleNexusService.HelloOutput hello(SampleNexusService.HelloInput input); } ================================================ FILE: core/src/main/java/io/temporal/samples/nexus/handler/HelloHandlerWorkflowImpl.java ================================================ package io.temporal.samples.nexus.handler; import io.temporal.failure.ApplicationFailure; import io.temporal.samples.nexus.service.SampleNexusService; public class HelloHandlerWorkflowImpl implements HelloHandlerWorkflow { @Override public SampleNexusService.HelloOutput hello(SampleNexusService.HelloInput input) { switch (input.getLanguage()) { case EN: return new SampleNexusService.HelloOutput("Hello " + input.getName() + " 👋"); case FR: return new SampleNexusService.HelloOutput("Bonjour " + input.getName() + " 👋"); case DE: return new SampleNexusService.HelloOutput("Hallo " + input.getName() + " 👋"); case ES: return new SampleNexusService.HelloOutput("¡Hola! " + input.getName() + " 👋"); case TR: return new SampleNexusService.HelloOutput("Merhaba " + input.getName() + " 👋"); } throw ApplicationFailure.newFailure( "Unsupported language: " + input.getLanguage(), "UNSUPPORTED_LANGUAGE"); } } ================================================ FILE: core/src/main/java/io/temporal/samples/nexus/handler/SampleNexusServiceImpl.java ================================================ package io.temporal.samples.nexus.handler; import io.nexusrpc.handler.OperationHandler; import io.nexusrpc.handler.OperationImpl; import io.nexusrpc.handler.ServiceImpl; import io.temporal.client.WorkflowOptions; import io.temporal.nexus.Nexus; import io.temporal.nexus.WorkflowRunOperation; import io.temporal.samples.nexus.service.SampleNexusService; // To create a service implementation, annotate the class with @ServiceImpl and provide the // interface that the service implements. The service implementation class should have methods that // return OperationHandler that correspond to the operations defined in the service interface. @ServiceImpl(service = SampleNexusService.class) public class SampleNexusServiceImpl { private final EchoClient echoClient; // The injected EchoClient makes this class unit-testable. // The no-arg constructor provides a default; the second allows tests to inject a mock. // If you are not using the sync call or do not need to mock a handler, then you will not // need this constructor pairing. public SampleNexusServiceImpl() { this(new EchoClientImpl()); } public SampleNexusServiceImpl(EchoClient echoClient) { this.echoClient = echoClient; } // The Echo Nexus Service exemplifies making a synchronous call using OperationHandler.sync. // In this case, it is calling the EchoClient class - not a workflow - and simply returning the // result. @OperationImpl public OperationHandler echo() { return OperationHandler.sync( // The method is for making arbitrary short calls to other services or databases, or // perform simple computations such as this one. Users can also access a workflow client by // calling // Nexus.getOperationContext().getWorkflowClient(ctx) to make arbitrary calls such as // signaling, querying, or listing workflows. (ctx, details, input) -> echoClient.echo(input)); } @OperationImpl public OperationHandler hello() { // Use the WorkflowRunOperation.fromWorkflowMethod constructor, which is the easiest // way to expose a workflow as an operation. To expose a workflow with a different input // parameters then the operation or from an untyped stub, use the // WorkflowRunOperation.fromWorkflowHandler constructor and the appropriate constructor method // on WorkflowHandle. return WorkflowRunOperation.fromWorkflowMethod( (ctx, details, input) -> Nexus.getOperationContext() .getWorkflowClient() .newWorkflowStub( HelloHandlerWorkflow.class, // Workflow IDs should typically be business meaningful IDs and are used to // dedupe workflow starts. For this example, we're using the request ID // allocated by Temporal when the caller workflow schedules // the operation, this ID is guaranteed to be stable across retries of this // operation. // // Task queue defaults to the task queue this operation is handled on. WorkflowOptions.newBuilder().setWorkflowId(details.getRequestId()).build()) ::hello); } } ================================================ FILE: core/src/main/java/io/temporal/samples/nexus/options/ClientOptions.java ================================================ package io.temporal.samples.nexus.options; import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; import io.grpc.netty.shaded.io.netty.handler.ssl.util.InsecureTrustManagerFactory; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowClientOptions; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.serviceclient.WorkflowServiceStubsOptions; import java.io.FileInputStream; import java.io.FileNotFoundException; import javax.net.ssl.SSLException; import org.apache.commons.cli.*; public class ClientOptions { public static WorkflowClient getWorkflowClient(String[] args) { return getWorkflowClient(args, WorkflowClientOptions.newBuilder()); } public static WorkflowClient getWorkflowClient( String[] args, WorkflowClientOptions.Builder clientOptions) { Options options = new Options(); Option targetHostOption = new Option("target-host", true, "Host:port for the Temporal service"); targetHostOption.setRequired(false); options.addOption(targetHostOption); Option namespaceOption = new Option("namespace", true, "Namespace to connect to"); namespaceOption.setRequired(false); options.addOption(namespaceOption); Option serverRootCaOption = new Option("server-root-ca-cert", true, "Optional path to root server CA cert"); serverRootCaOption.setRequired(false); options.addOption(serverRootCaOption); Option clientCertOption = new Option( "client-cert", true, "Optional path to client cert, mutually exclusive with API key"); clientCertOption.setRequired(false); options.addOption(clientCertOption); Option clientKeyOption = new Option( "client-key", true, "Optional path to client key, mutually exclusive with API key"); clientKeyOption.setRequired(false); options.addOption(clientKeyOption); Option apiKeyOption = new Option("api-key", true, "Optional API key, mutually exclusive with cert/key"); apiKeyOption.setRequired(false); options.addOption(apiKeyOption); Option serverNameOption = new Option( "server-name", true, "Server name to use for verifying the server's certificate"); serverNameOption.setRequired(false); options.addOption(serverNameOption); Option insercureSkipVerifyOption = new Option( "insecure-skip-verify", false, "Skip verification of the server's certificate and host name"); insercureSkipVerifyOption.setRequired(false); options.addOption(insercureSkipVerifyOption); CommandLineParser parser = new DefaultParser(); HelpFormatter formatter = new HelpFormatter(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (ParseException e) { System.out.println(e.getMessage()); formatter.printHelp("utility-name", options); System.exit(1); } String targetHost = cmd.getOptionValue("target-host", "localhost:7233"); String namespace = cmd.getOptionValue("namespace", "default"); String serverRootCaCert = cmd.getOptionValue("server-root-ca-cert", ""); String clientCert = cmd.getOptionValue("client-cert", ""); String clientKey = cmd.getOptionValue("client-key", ""); String serverName = cmd.getOptionValue("server-name", ""); boolean insecureSkipVerify = cmd.hasOption("insecure-skip-verify"); String apiKey = cmd.getOptionValue("api-key", ""); // API key and client cert/key are mutually exclusive if (!apiKey.isEmpty() && (!clientCert.isEmpty() || !clientKey.isEmpty())) { throw new IllegalArgumentException("API key and client cert/key are mutually exclusive"); } WorkflowServiceStubsOptions.Builder serviceStubOptionsBuilder = WorkflowServiceStubsOptions.newBuilder().setTarget(targetHost); // Configure TLS if client cert and key are provided if (!clientCert.isEmpty() || !clientKey.isEmpty()) { if (clientCert.isEmpty() || clientKey.isEmpty()) { throw new IllegalArgumentException("Both client-cert and client-key must be provided"); } try { SslContextBuilder sslContext = SslContextBuilder.forClient() .keyManager(new FileInputStream(clientCert), new FileInputStream(clientKey)); if (serverRootCaCert != null && !serverRootCaCert.isEmpty()) { sslContext.trustManager(new FileInputStream(serverRootCaCert)); } if (insecureSkipVerify) { sslContext.trustManager(InsecureTrustManagerFactory.INSTANCE); } serviceStubOptionsBuilder.setSslContext(GrpcSslContexts.configure(sslContext).build()); } catch (SSLException e) { throw new RuntimeException(e); } catch (FileNotFoundException e) { throw new RuntimeException(e); } if (serverName != null && !serverName.isEmpty()) { serviceStubOptionsBuilder.setChannelInitializer(c -> c.overrideAuthority(serverName)); } } // Configure API key if provided if (!apiKey.isEmpty()) { serviceStubOptionsBuilder.setEnableHttps(true); serviceStubOptionsBuilder.addApiKey(() -> apiKey); } WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(serviceStubOptionsBuilder.build()); return WorkflowClient.newInstance(service, clientOptions.setNamespace(namespace).build()); } } ================================================ FILE: core/src/main/java/io/temporal/samples/nexus/service/SampleNexusService.java ================================================ package io.temporal.samples.nexus.service; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import io.nexusrpc.Operation; import io.nexusrpc.Service; @Service public interface SampleNexusService { enum Language { EN, FR, DE, ES, TR } class HelloInput { private final String name; private final Language language; @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) public HelloInput( @JsonProperty("name") String name, @JsonProperty("language") Language language) { this.name = name; this.language = language; } @JsonProperty("name") public String getName() { return name; } @JsonProperty("language") public Language getLanguage() { return language; } } class HelloOutput { private final String message; @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) public HelloOutput(@JsonProperty("message") String message) { this.message = message; } @JsonProperty("message") public String getMessage() { return message; } } class EchoInput { private final String message; @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) public EchoInput(@JsonProperty("message") String message) { this.message = message; } @JsonProperty("message") public String getMessage() { return message; } } class EchoOutput { private final String message; @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) public EchoOutput(@JsonProperty("message") String message) { this.message = message; } @JsonProperty("message") public String getMessage() { return message; } } @Operation HelloOutput hello(HelloInput input); @Operation EchoOutput echo(EchoInput input); } ================================================ FILE: core/src/main/java/io/temporal/samples/nexus/service/description.md ================================================ ## Service: [SampleNexusService](https://github.com/temporalio/samples-java/blob/main/core/src/main/java/io/temporal/samples/nexus/service/SampleNexusService.java) - operation: `echo` - operation: `hello` See https://github.com/temporalio/samples-java/blob/main/core/src/main/java/io/temporal/samples/nexus/service/SampleNexusService.java for Input / Output types. ================================================ FILE: core/src/main/java/io/temporal/samples/nexuscancellation/README.MD ================================================ # Nexus Cancellation This sample shows how to cancel a Nexus operation from a caller workflow and specify a cancellation type. In this sample we will show using the `WAIT_REQUESTED` cancellation type, which allows the caller to return after the handler workflow has received the requested to be cancelled, but does not wait for the handler workflow to finish processing the cancellation request. To run this sample, set up your environment following the instructions in the main [Nexus Sample](../nexus/README.md). Next, in separate terminal windows: ### Nexus handler worker ``` ./gradlew -q execute -PmainClass=io.temporal.samples.nexuscancellation.handler.HandlerWorker \ --args="-target-host localhost:7233 -namespace my-target-namespace" ``` ### Nexus caller worker ``` ./gradlew -q execute -PmainClass=io.temporal.samples.nexuscancellation.caller.CallerWorker \ --args="-target-host localhost:7233 -namespace my-caller-namespace" ``` ### Start caller workflow ``` ./gradlew -q execute -PmainClass=io.temporal.samples.nexuscancellation.caller.CallerStarter \ --args="-target-host localhost:7233 -namespace my-caller-namespace" ``` ### Output which should result in on the caller side: ``` 14:33:52.810 i.t.s.n.caller.CallerStarter - Started workflow workflowId: 87e97bf0-ca8a-4ae6-a9dc-ae97e5c0ac41 runId: 01976b36-a524-71a1-b848-8eb385fec2c3 14:33:54.250 i.t.s.n.caller.CallerStarter - Workflow result: Hallo Nexus 👋 ``` on the handler side: ``` 14:33:54.177 INFO i.t.s.n.h.HelloHandlerWorkflowImpl - HelloHandlerWorkflow was cancelled successfully. 14:33:56.167 INFO i.t.s.n.h.HelloHandlerWorkflowImpl - HelloHandlerWorkflow was cancelled successfully. 14:33:57.172 INFO i.t.s.n.h.HelloHandlerWorkflowImpl - HelloHandlerWorkflow was cancelled successfully. 14:33:57.176 INFO i.t.s.n.h.HelloHandlerWorkflowImpl - HelloHandlerWorkflow was cancelled successfully. ``` Notice the timing, the caller workflow returned before the handler workflow was cancelled. This is because of the use of `WAIT_REQUESTED` as the cancellation type in the Nexus operation. This means the caller didn't have to wait for the handler workflow to finish, but still guarantees the handler workflow will receive the cancellation request. ================================================ FILE: core/src/main/java/io/temporal/samples/nexuscancellation/caller/CallerStarter.java ================================================ package io.temporal.samples.nexuscancellation.caller; import io.temporal.api.common.v1.WorkflowExecution; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.samples.nexus.options.ClientOptions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CallerStarter { private static final Logger logger = LoggerFactory.getLogger(CallerStarter.class); public static void main(String[] args) { WorkflowClient client = ClientOptions.getWorkflowClient(args); WorkflowOptions workflowOptions = WorkflowOptions.newBuilder().setTaskQueue(CallerWorker.DEFAULT_TASK_QUEUE_NAME).build(); HelloCallerWorkflow helloWorkflow = client.newWorkflowStub(HelloCallerWorkflow.class, workflowOptions); WorkflowExecution execution = WorkflowClient.start(helloWorkflow::hello, "Nexus"); logger.info( "Started workflow workflowId: {} runId: {}", execution.getWorkflowId(), execution.getRunId()); logger.info("Workflow result: {}", helloWorkflow.hello("Nexus")); } } ================================================ FILE: core/src/main/java/io/temporal/samples/nexuscancellation/caller/CallerWorker.java ================================================ package io.temporal.samples.nexuscancellation.caller; import io.temporal.client.WorkflowClient; import io.temporal.samples.nexus.options.ClientOptions; import io.temporal.samples.nexus.service.SampleNexusService; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import io.temporal.worker.WorkflowImplementationOptions; import io.temporal.workflow.NexusServiceOptions; import java.util.Collections; public class CallerWorker { public static final String DEFAULT_TASK_QUEUE_NAME = "my-caller-workflow-task-queue"; public static void main(String[] args) { WorkflowClient client = ClientOptions.getWorkflowClient(args); WorkerFactory factory = WorkerFactory.newInstance(client); Worker worker = factory.newWorker(DEFAULT_TASK_QUEUE_NAME); worker.registerWorkflowImplementationTypes( WorkflowImplementationOptions.newBuilder() .setNexusServiceOptions( Collections.singletonMap( SampleNexusService.class.getSimpleName(), NexusServiceOptions.newBuilder().setEndpoint("my-nexus-endpoint-name").build())) .build(), HelloCallerWorkflowImpl.class); factory.start(); } } ================================================ FILE: core/src/main/java/io/temporal/samples/nexuscancellation/caller/HelloCallerWorkflow.java ================================================ package io.temporal.samples.nexuscancellation.caller; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; @WorkflowInterface public interface HelloCallerWorkflow { @WorkflowMethod String hello(String message); } ================================================ FILE: core/src/main/java/io/temporal/samples/nexuscancellation/caller/HelloCallerWorkflowImpl.java ================================================ package io.temporal.samples.nexuscancellation.caller; import static io.temporal.samples.nexus.service.SampleNexusService.Language.*; import io.temporal.failure.CanceledFailure; import io.temporal.failure.NexusOperationFailure; import io.temporal.samples.nexus.service.SampleNexusService; import io.temporal.workflow.*; import java.time.Duration; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; public class HelloCallerWorkflowImpl implements HelloCallerWorkflow { public static final Logger log = Workflow.getLogger(HelloCallerWorkflowImpl.class); private static final SampleNexusService.Language[] languages = new SampleNexusService.Language[] {EN, FR, DE, ES, TR}; SampleNexusService sampleNexusService = Workflow.newNexusServiceStub( SampleNexusService.class, NexusServiceOptions.newBuilder() .setOperationOptions( NexusOperationOptions.newBuilder() .setScheduleToCloseTimeout(Duration.ofSeconds(10)) // Set the cancellation type to WAIT_REQUESTED. This means that the caller // will wait for the cancellation request to be received by the handler before // proceeding with the cancellation. // // By default, the caller would wait until the operation is completed. .setCancellationType(NexusOperationCancellationType.WAIT_REQUESTED) .build()) .build()); @Override public String hello(String message) { List> results = new ArrayList<>(languages.length); /* * Create our CancellationScope. Within this scope we call the nexus operation asynchronously * hello method asynchronously for each of our defined languages. */ CancellationScope scope = Workflow.newCancellationScope( () -> { for (SampleNexusService.Language language : languages) { results.add( Async.function( sampleNexusService::hello, new SampleNexusService.HelloInput(message, language))); } }); /* * Execute all nexus operations within the CancellationScope. Note that this execution is * non-blocking as the code inside our cancellation scope is also non-blocking. */ scope.run(); // We use "anyOf" here to wait for one of the nexus operation invocations to return SampleNexusService.HelloOutput result = Promise.anyOf(results).get(); // Trigger cancellation of all uncompleted nexus operations invocations within the cancellation // scope scope.cancel(); // Wait for all nexus operations to receive a cancellation request before // proceeding. // // Note: Once the workflow completes any pending cancellation requests are dropped by the // server. In general, it is a good practice to wait for all cancellation requests to be // processed before completing the workflow. for (Promise promise : results) { try { promise.get(); } catch (NexusOperationFailure e) { // If the operation was cancelled, we can ignore the failure if (e.getCause() instanceof CanceledFailure) { log.info("Operation was cancelled"); continue; } throw e; } } return result.getMessage(); } } ================================================ FILE: core/src/main/java/io/temporal/samples/nexuscancellation/handler/HandlerWorker.java ================================================ package io.temporal.samples.nexuscancellation.handler; import io.temporal.client.WorkflowClient; import io.temporal.samples.nexus.handler.SampleNexusServiceImpl; import io.temporal.samples.nexus.options.ClientOptions; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; public class HandlerWorker { public static final String DEFAULT_TASK_QUEUE_NAME = "my-handler-task-queue"; public static void main(String[] args) { WorkflowClient client = ClientOptions.getWorkflowClient(args); WorkerFactory factory = WorkerFactory.newInstance(client); Worker worker = factory.newWorker(DEFAULT_TASK_QUEUE_NAME); worker.registerWorkflowImplementationTypes(HelloHandlerWorkflowImpl.class); worker.registerNexusServiceImplementation(new SampleNexusServiceImpl()); factory.start(); } } ================================================ FILE: core/src/main/java/io/temporal/samples/nexuscancellation/handler/HelloHandlerWorkflowImpl.java ================================================ package io.temporal.samples.nexuscancellation.handler; import io.temporal.failure.ApplicationFailure; import io.temporal.failure.CanceledFailure; import io.temporal.samples.nexus.handler.HelloHandlerWorkflow; import io.temporal.samples.nexus.service.SampleNexusService; import io.temporal.workflow.Workflow; import java.time.Duration; import org.slf4j.Logger; public class HelloHandlerWorkflowImpl implements HelloHandlerWorkflow { public static final Logger log = Workflow.getLogger(HelloHandlerWorkflowImpl.class); @Override public SampleNexusService.HelloOutput hello(SampleNexusService.HelloInput input) { // Sleep for a random duration to simulate some work try { Workflow.sleep(Duration.ofSeconds(Workflow.newRandom().nextInt(5))); switch (input.getLanguage()) { case EN: return new SampleNexusService.HelloOutput("Hello " + input.getName() + " 👋"); case FR: return new SampleNexusService.HelloOutput("Bonjour " + input.getName() + " 👋"); case DE: return new SampleNexusService.HelloOutput("Hallo " + input.getName() + " 👋"); case ES: return new SampleNexusService.HelloOutput("¡Hola! " + input.getName() + " 👋"); case TR: return new SampleNexusService.HelloOutput("Merhaba " + input.getName() + " 👋"); } throw ApplicationFailure.newFailure( "Unsupported language: " + input.getLanguage(), "UNSUPPORTED_LANGUAGE"); } catch (CanceledFailure e) { // Simulate some work after cancellation is requested Workflow.newDetachedCancellationScope( () -> Workflow.sleep(Duration.ofSeconds(Workflow.newRandom().nextInt(5)))) .run(); log.info("HelloHandlerWorkflow was cancelled successfully."); throw e; } } } ================================================ FILE: core/src/main/java/io/temporal/samples/nexuscontextpropagation/README.MD ================================================ # Nexus Context Propagation This sample shows how to propagate MDC (Mapped Diagnostic Context) context values from Workflows to Nexus operations. Nexus does not support `ContextPropagator` since the header format is not compatible. Users should look at `NexusMDCContextInterceptor` for propagating MDC context values. To run this sample, set up your environment following the instructions in the main [Nexus Sample](../nexus/README.md). Next, in separate terminal windows: ### Nexus handler worker ``` ./gradlew -q execute -PmainClass=io.temporal.samples.nexuscontextpropagation.handler.HandlerWorker \ --args="-target-host localhost:7233 -namespace my-target-namespace" ``` ### Nexus caller worker ``` ./gradlew -q execute -PmainClass=io.temporal.samples.nexuscontextpropagation.caller.CallerWorker \ --args="-target-host localhost:7233 -namespace my-caller-namespace" ``` ### Start caller workflow ``` ./gradlew -q execute -PmainClass=io.temporal.samples.nexuscontextpropagation.caller.CallerStarter \ --args="-target-host localhost:7233 -namespace my-caller-namespace" ``` ### Output which should result in this on the caller side: ``` INFO i.t.s.n.caller.CallerStarter - Started EchoCallerWorkflow workflowId: 7ac97cb9-b457-4052-af94-d82478c35c5e runId: 01954eb9-6963-7b52-9a1d-b74e64643846 INFO i.t.s.n.caller.CallerStarter - Workflow result: Nexus Echo 👋 INFO i.t.s.n.caller.CallerStarter - Started HelloCallerWorkflow workflowId: 9e0bc89c-5709-4742-b7c0-868464c2fccf runId: 01954eb9-6ae3-7d6d-b355-71545688309d INFO i.t.s.n.caller.CallerStarter - Workflow result: Hello Nexus 👋 ``` And this on the handler side: ``` INFO i.t.s.n.handler.SampleNexusServiceImpl - Echo called from a workflow with ID : 7ac97cb9-b457-4052-af94-d82478c35c5e INFO i.t.s.n.h.HelloHandlerWorkflowImpl - HelloHandlerWorkflow called from a workflow with ID : 9e0bc89c-5709-4742-b7c0-868464c2fccf ``` ================================================ FILE: core/src/main/java/io/temporal/samples/nexuscontextpropagation/caller/CallerStarter.java ================================================ package io.temporal.samples.nexuscontextpropagation.caller; import io.temporal.api.common.v1.WorkflowExecution; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowClientOptions; import io.temporal.client.WorkflowOptions; import io.temporal.samples.nexus.caller.EchoCallerWorkflow; import io.temporal.samples.nexus.caller.HelloCallerWorkflow; import io.temporal.samples.nexus.options.ClientOptions; import io.temporal.samples.nexus.service.SampleNexusService; import io.temporal.samples.nexuscontextpropagation.propagation.MDCContextPropagator; import java.util.Collections; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CallerStarter { private static final Logger logger = LoggerFactory.getLogger(CallerStarter.class); public static void main(String[] args) { WorkflowClient client = ClientOptions.getWorkflowClient( args, WorkflowClientOptions.newBuilder() .setContextPropagators(Collections.singletonList(new MDCContextPropagator()))); WorkflowOptions workflowOptions = WorkflowOptions.newBuilder().setTaskQueue(CallerWorker.DEFAULT_TASK_QUEUE_NAME).build(); EchoCallerWorkflow echoWorkflow = client.newWorkflowStub(EchoCallerWorkflow.class, workflowOptions); WorkflowExecution execution = WorkflowClient.start(echoWorkflow::echo, "Nexus Echo 👋"); logger.info( "Started EchoCallerWorkflow workflowId: {} runId: {}", execution.getWorkflowId(), execution.getRunId()); logger.info("Workflow result: {}", echoWorkflow.echo("Nexus Echo 👋")); HelloCallerWorkflow helloWorkflow = client.newWorkflowStub(HelloCallerWorkflow.class, workflowOptions); execution = WorkflowClient.start(helloWorkflow::hello, "Nexus", SampleNexusService.Language.EN); logger.info( "Started HelloCallerWorkflow workflowId: {} runId: {}", execution.getWorkflowId(), execution.getRunId()); logger.info( "Workflow result: {}", helloWorkflow.hello("Nexus", SampleNexusService.Language.ES)); } } ================================================ FILE: core/src/main/java/io/temporal/samples/nexuscontextpropagation/caller/CallerWorker.java ================================================ package io.temporal.samples.nexuscontextpropagation.caller; import io.temporal.client.WorkflowClient; import io.temporal.samples.nexus.options.ClientOptions; import io.temporal.samples.nexuscontextpropagation.propagation.NexusMDCContextInterceptor; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import io.temporal.worker.WorkerFactoryOptions; import io.temporal.worker.WorkflowImplementationOptions; import io.temporal.workflow.NexusServiceOptions; import java.util.Collections; public class CallerWorker { public static final String DEFAULT_TASK_QUEUE_NAME = "my-caller-workflow-task-queue"; public static void main(String[] args) { WorkflowClient client = ClientOptions.getWorkflowClient(args); WorkerFactory factory = WorkerFactory.newInstance( client, WorkerFactoryOptions.newBuilder() .setWorkerInterceptors(new NexusMDCContextInterceptor()) .build()); Worker worker = factory.newWorker(DEFAULT_TASK_QUEUE_NAME); worker.registerWorkflowImplementationTypes( WorkflowImplementationOptions.newBuilder() .setNexusServiceOptions( Collections.singletonMap( "SampleNexusService", NexusServiceOptions.newBuilder().setEndpoint("my-nexus-endpoint-name").build())) .build(), EchoCallerWorkflowImpl.class, HelloCallerWorkflowImpl.class); factory.start(); } } ================================================ FILE: core/src/main/java/io/temporal/samples/nexuscontextpropagation/caller/EchoCallerWorkflowImpl.java ================================================ package io.temporal.samples.nexuscontextpropagation.caller; import io.temporal.samples.nexus.caller.EchoCallerWorkflow; import io.temporal.samples.nexus.service.SampleNexusService; import io.temporal.workflow.NexusOperationOptions; import io.temporal.workflow.NexusServiceOptions; import io.temporal.workflow.Workflow; import java.time.Duration; import org.slf4j.MDC; public class EchoCallerWorkflowImpl implements EchoCallerWorkflow { SampleNexusService sampleNexusService = Workflow.newNexusServiceStub( SampleNexusService.class, NexusServiceOptions.newBuilder() .setOperationOptions( NexusOperationOptions.newBuilder() .setScheduleToCloseTimeout(Duration.ofSeconds(10)) .build()) .build()); @Override public String echo(String message) { MDC.put("x-nexus-caller-workflow-id", Workflow.getInfo().getWorkflowId()); return sampleNexusService.echo(new SampleNexusService.EchoInput(message)).getMessage(); } } ================================================ FILE: core/src/main/java/io/temporal/samples/nexuscontextpropagation/caller/HelloCallerWorkflowImpl.java ================================================ package io.temporal.samples.nexuscontextpropagation.caller; import io.temporal.samples.nexus.caller.HelloCallerWorkflow; import io.temporal.samples.nexus.service.SampleNexusService; import io.temporal.workflow.NexusOperationHandle; import io.temporal.workflow.NexusOperationOptions; import io.temporal.workflow.NexusServiceOptions; import io.temporal.workflow.Workflow; import java.time.Duration; import org.slf4j.MDC; public class HelloCallerWorkflowImpl implements HelloCallerWorkflow { SampleNexusService sampleNexusService = Workflow.newNexusServiceStub( SampleNexusService.class, NexusServiceOptions.newBuilder() .setOperationOptions( NexusOperationOptions.newBuilder() .setScheduleToCloseTimeout(Duration.ofSeconds(10)) .build()) .build()); @Override public String hello(String message, SampleNexusService.Language language) { MDC.put("x-nexus-caller-workflow-id", Workflow.getInfo().getWorkflowId()); NexusOperationHandle handle = Workflow.startNexusOperation( sampleNexusService::hello, new SampleNexusService.HelloInput(message, language)); // Optionally wait for the operation to be started. NexusOperationExecution will contain the // operation token in case this operation is asynchronous. handle.getExecution().get(); return handle.getResult().get().getMessage(); } } ================================================ FILE: core/src/main/java/io/temporal/samples/nexuscontextpropagation/handler/HandlerWorker.java ================================================ package io.temporal.samples.nexuscontextpropagation.handler; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowClientOptions; import io.temporal.samples.nexus.options.ClientOptions; import io.temporal.samples.nexuscontextpropagation.propagation.MDCContextPropagator; import io.temporal.samples.nexuscontextpropagation.propagation.NexusMDCContextInterceptor; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import io.temporal.worker.WorkerFactoryOptions; import java.util.Collections; public class HandlerWorker { public static final String DEFAULT_TASK_QUEUE_NAME = "my-handler-task-queue"; public static void main(String[] args) { WorkflowClient client = ClientOptions.getWorkflowClient( args, WorkflowClientOptions.newBuilder() .setContextPropagators(Collections.singletonList(new MDCContextPropagator()))); WorkerFactory factory = WorkerFactory.newInstance( client, WorkerFactoryOptions.newBuilder() .setWorkerInterceptors(new NexusMDCContextInterceptor()) .build()); Worker worker = factory.newWorker(DEFAULT_TASK_QUEUE_NAME); worker.registerWorkflowImplementationTypes(HelloHandlerWorkflowImpl.class); worker.registerNexusServiceImplementation(new SampleNexusServiceImpl()); factory.start(); } } ================================================ FILE: core/src/main/java/io/temporal/samples/nexuscontextpropagation/handler/HelloHandlerWorkflowImpl.java ================================================ package io.temporal.samples.nexuscontextpropagation.handler; import io.temporal.failure.ApplicationFailure; import io.temporal.samples.nexus.handler.HelloHandlerWorkflow; import io.temporal.samples.nexus.service.SampleNexusService; import io.temporal.workflow.Workflow; import org.slf4j.Logger; import org.slf4j.MDC; public class HelloHandlerWorkflowImpl implements HelloHandlerWorkflow { public static final Logger log = Workflow.getLogger(HelloHandlerWorkflowImpl.class); @Override public SampleNexusService.HelloOutput hello(SampleNexusService.HelloInput input) { if (MDC.get("x-nexus-caller-workflow-id") != null) { log.info( "HelloHandlerWorkflow called from a workflow with ID : {}", MDC.get("x-nexus-caller-workflow-id")); } switch (input.getLanguage()) { case EN: return new SampleNexusService.HelloOutput("Hello " + input.getName() + " 👋"); case FR: return new SampleNexusService.HelloOutput("Bonjour " + input.getName() + " 👋"); case DE: return new SampleNexusService.HelloOutput("Hallo " + input.getName() + " 👋"); case ES: return new SampleNexusService.HelloOutput("¡Hola! " + input.getName() + " 👋"); case TR: return new SampleNexusService.HelloOutput("Merhaba " + input.getName() + " 👋"); } throw ApplicationFailure.newFailure( "Unsupported language: " + input.getLanguage(), "UNSUPPORTED_LANGUAGE"); } } ================================================ FILE: core/src/main/java/io/temporal/samples/nexuscontextpropagation/handler/SampleNexusServiceImpl.java ================================================ package io.temporal.samples.nexuscontextpropagation.handler; import io.nexusrpc.handler.OperationHandler; import io.nexusrpc.handler.OperationImpl; import io.nexusrpc.handler.ServiceImpl; import io.temporal.client.WorkflowOptions; import io.temporal.nexus.Nexus; import io.temporal.nexus.WorkflowRunOperation; import io.temporal.samples.nexus.handler.HelloHandlerWorkflow; import io.temporal.samples.nexus.service.SampleNexusService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; // To create a service implementation, annotate the class with @ServiceImpl and provide the // interface that the service implements. The service implementation class should have methods that // return OperationHandler that correspond to the operations defined in the service interface. @ServiceImpl(service = SampleNexusService.class) public class SampleNexusServiceImpl { private static final Logger logger = LoggerFactory.getLogger(SampleNexusServiceImpl.class); @OperationImpl public OperationHandler echo() { // OperationHandler.sync is a meant for exposing simple RPC handlers. return OperationHandler.sync( // The method is for making arbitrary short calls to other services or databases, or // perform simple computations such as this one. Users can also access a workflow client by // calling // Nexus.getOperationContext().getWorkflowClient(ctx) to make arbitrary calls such as // signaling, querying, or listing workflows. (ctx, details, input) -> { if (MDC.get("x-nexus-caller-workflow-id") != null) { logger.info( "Echo called from a workflow with ID : {}", MDC.get("x-nexus-caller-workflow-id")); } return new SampleNexusService.EchoOutput(input.getMessage()); }); } @OperationImpl public OperationHandler hello() { // Use the WorkflowRunOperation.fromWorkflowMethod constructor, which is the easiest // way to expose a workflow as an operation. To expose a workflow with a different input // parameters then the operation or from an untyped stub, use the // WorkflowRunOperation.fromWorkflowHandler constructor and the appropriate constructor method // on WorkflowHandle. return WorkflowRunOperation.fromWorkflowMethod( (ctx, details, input) -> Nexus.getOperationContext() .getWorkflowClient() .newWorkflowStub( HelloHandlerWorkflow.class, // Workflow IDs should typically be business meaningful IDs and are used to // dedupe workflow starts. // For this example, we're using the request ID allocated by Temporal when // the // caller workflow schedules // the operation, this ID is guaranteed to be stable across retries of this // operation. // // Task queue defaults to the task queue this operation is handled on. WorkflowOptions.newBuilder().setWorkflowId(details.getRequestId()).build()) ::hello); } } ================================================ FILE: core/src/main/java/io/temporal/samples/nexuscontextpropagation/propagation/MDCContextPropagator.java ================================================ package io.temporal.samples.nexuscontextpropagation.propagation; import io.temporal.api.common.v1.Payload; import io.temporal.common.context.ContextPropagator; import io.temporal.common.converter.DataConverter; import java.util.HashMap; import java.util.Map; import org.slf4j.MDC; public class MDCContextPropagator implements ContextPropagator { @Override public String getName() { return this.getClass().getName(); } @Override public Object getCurrentContext() { Map context = new HashMap<>(); if (MDC.getCopyOfContextMap() == null) { return context; } for (Map.Entry entry : MDC.getCopyOfContextMap().entrySet()) { if (entry.getKey().startsWith("x-nexus-")) { context.put(entry.getKey(), entry.getValue()); } } return context; } @Override public void setCurrentContext(Object context) { Map contextMap = (Map) context; for (Map.Entry entry : contextMap.entrySet()) { MDC.put(entry.getKey(), entry.getValue()); } } @Override public Map serializeContext(Object context) { Map contextMap = (Map) context; Map serializedContext = new HashMap<>(); for (Map.Entry entry : contextMap.entrySet()) { serializedContext.put( entry.getKey(), DataConverter.getDefaultInstance().toPayload(entry.getValue()).get()); } return serializedContext; } @Override public Object deserializeContext(Map context) { Map contextMap = new HashMap<>(); for (Map.Entry entry : context.entrySet()) { contextMap.put( entry.getKey(), DataConverter.getDefaultInstance() .fromPayload(entry.getValue(), String.class, String.class)); } return contextMap; } } ================================================ FILE: core/src/main/java/io/temporal/samples/nexuscontextpropagation/propagation/NexusMDCContextInterceptor.java ================================================ package io.temporal.samples.nexuscontextpropagation.propagation; import io.nexusrpc.OperationException; import io.nexusrpc.handler.OperationContext; import io.temporal.common.interceptors.NexusOperationInboundCallsInterceptor; import io.temporal.common.interceptors.WorkerInterceptorBase; import io.temporal.common.interceptors.WorkflowInboundCallsInterceptor; import io.temporal.common.interceptors.WorkflowOutboundCallsInterceptor; import java.util.Map; import org.slf4j.MDC; /** * Propagates MDC context from the caller workflow to the Nexus service through the operation * headers. */ public class NexusMDCContextInterceptor extends WorkerInterceptorBase { private static final String NEXUS_HEADER_PREFIX = "x-nexus-"; @Override public WorkflowInboundCallsInterceptor interceptWorkflow(WorkflowInboundCallsInterceptor next) { return new WorkflowInboundCallsInterceptorNexusMDC(next); } public static class WorkflowInboundCallsInterceptorNexusMDC extends io.temporal.common.interceptors.WorkflowInboundCallsInterceptorBase { private final WorkflowInboundCallsInterceptor next; public WorkflowInboundCallsInterceptorNexusMDC(WorkflowInboundCallsInterceptor next) { super(next); this.next = next; } @Override public void init(WorkflowOutboundCallsInterceptor outboundCalls) { next.init(new WorkflowOutboundCallsInterceptorNexusMDC(outboundCalls)); } } public static class WorkflowOutboundCallsInterceptorNexusMDC extends io.temporal.common.interceptors.WorkflowOutboundCallsInterceptorBase { private final WorkflowOutboundCallsInterceptor next; public WorkflowOutboundCallsInterceptorNexusMDC(WorkflowOutboundCallsInterceptor next) { super(next); this.next = next; } @Override public ExecuteNexusOperationOutput executeNexusOperation( ExecuteNexusOperationInput input) { Map contextMap = MDC.getCopyOfContextMap(); if (contextMap != null) { Map headerMap = input.getHeaders(); contextMap.forEach( (k, v) -> { if (k.startsWith(NEXUS_HEADER_PREFIX)) { headerMap.put(k, v); } }); } return next.executeNexusOperation(input); } } @Override public NexusOperationInboundCallsInterceptor interceptNexusOperation( OperationContext context, NexusOperationInboundCallsInterceptor next) { return new NexusOperationInboundCallsInterceptorNexusMDC(next); } private static class NexusOperationInboundCallsInterceptorNexusMDC extends io.temporal.common.interceptors.NexusOperationInboundCallsInterceptorBase { private final NexusOperationInboundCallsInterceptor next; public NexusOperationInboundCallsInterceptorNexusMDC( NexusOperationInboundCallsInterceptor next) { super(next); this.next = next; } @Override public StartOperationOutput startOperation(StartOperationInput input) throws OperationException { input .getOperationContext() .getHeaders() .forEach( (k, v) -> { if (k.startsWith(NEXUS_HEADER_PREFIX)) { MDC.put(k, v); } }); return next.startOperation(input); } @Override public CancelOperationOutput cancelOperation(CancelOperationInput input) { input .getOperationContext() .getHeaders() .forEach( (k, v) -> { if (k.startsWith(NEXUS_HEADER_PREFIX)) { MDC.put(k, v); } }); return next.cancelOperation(input); } } } ================================================ FILE: core/src/main/java/io/temporal/samples/nexusmessaging/README.md ================================================ This sample shows how to expose a long-running Workflow's queries, updates, and signals as Nexus operations. There are two self-contained examples, each in its own directory: | | `callerpattern/` | `ondemandpattern/` | |---|---|--------------------------------------------------------------| | **Pattern** | Signal an existing Workflow | Create and run Workflows on demand, and send signals to them | | **Who creates the Workflow?** | The handler worker starts it on boot | The caller starts it via a Nexus operation | | **Who knows the Workflow ID?** | Only the handler | The caller chooses and passes it in every operation | | **Nexus service** | `NexusGreetingService` | `NexusRemoteGreetingService` | Each directory is fully self-contained for clarity. The `GreetingWorkflow`, `GreetingWorkflowImpl`, `GreetingActivity` and `GreetingActivityImpl` classes are pretty much the same between the two — only the Nexus service interface and its implementation differ. This highlights that the same Workflow can be exposed through Nexus in different ways depending on whether the caller needs lifecycle control. See each directory's README for running instructions. ================================================ FILE: core/src/main/java/io/temporal/samples/nexusmessaging/callerpattern/README.md ================================================ ## Caller pattern The handler worker starts a `GreetingWorkflow` for a User ID. `NexusGreetingServiceImpl` holds that ID and routes every Nexus operation to it. The caller's input does not have that Workflow ID as the caller doesn't know it - but the caller sends in the User ID, and `NexusGreetingServiceImpl` knows how to get the desired Workflow ID from that User ID (see the getWorkflowId call). HandlerWorker is using the same getWorkflowId call to generate a Workflow ID from a User ID when it launches the Workflow. The caller Workflow: 1. Queries for supported languages (`getLanguages` — backed by a `@QueryMethod`) 2. Changes the language to Arabic (`setLanguage` — backed by an `@UpdateMethod` that calls an activity) 3. Confirms the change via a second query (`getLanguage`) 4. Approves the Workflow (`approve` — backed by a `@SignalMethod`) ### Running Start a Temporal server: ```bash temporal server start-dev ``` Create the namespaces and Nexus endpoint: ```bash temporal operator namespace create --namespace nexus-messaging-handler-namespace temporal operator namespace create --namespace nexus-messaging-caller-namespace temporal operator nexus endpoint create \ --name nexus-messaging-nexus-endpoint \ --target-namespace nexus-messaging-handler-namespace \ --target-task-queue nexus-messaging-handler-task-queue ``` This sample loads connection settings from `ClientConfigProfile`. The `nexus-messaging-handler` and `nexus-messaging-caller` profiles are defined in `core/src/main/resources/config.toml`. You can override settings with environment variables or by editing the TOML file (see the `envconfig` sample for details). In one terminal, start the handler worker: ```bash ./gradlew -q :core:execute -PmainClass=io.temporal.samples.nexusmessaging.callerpattern.handler.HandlerWorker ``` In a second terminal, start the caller worker: ```bash ./gradlew -q :core:execute -PmainClass=io.temporal.samples.nexusmessaging.callerpattern.caller.CallerWorker ``` In a third terminal, run the following command to start the example: ```bash ./gradlew -q :core:execute -PmainClass=io.temporal.samples.nexusmessaging.callerpattern.caller.CallerStarter ``` Expected output: ``` Supported languages: [CHINESE, ENGLISH] Language changed: ENGLISH -> ARABIC Workflow approved ``` ================================================ FILE: core/src/main/java/io/temporal/samples/nexusmessaging/callerpattern/caller/CallerStarter.java ================================================ package io.temporal.samples.nexusmessaging.callerpattern.caller; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.envconfig.LoadClientConfigProfileOptions; import io.temporal.serviceclient.WorkflowServiceStubs; import java.nio.file.Paths; import java.util.List; import java.util.UUID; public class CallerStarter { public static void main(String[] args) { ClientConfigProfile profile; try { String configFilePath = Paths.get(CallerStarter.class.getResource("/config.toml").toURI()).toString(); profile = ClientConfigProfile.load( LoadClientConfigProfileOptions.newBuilder() .setConfigFilePath(configFilePath) .setConfigFileProfile(CallerWorker.CONFIG_PROFILE) .build()); } catch (Exception e) { throw new RuntimeException("Failed to load client configuration", e); } WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); CallerWorkflow workflow = client.newWorkflowStub( CallerWorkflow.class, WorkflowOptions.newBuilder() .setWorkflowId("nexus-messaging-caller-" + UUID.randomUUID()) .setTaskQueue(CallerWorker.TASK_QUEUE) .build()); // Launch the worker, passing in an identifier which the Nexus service will use // to find the matching workflow (See NexusGreetingServiceImpl::getWorkflowId) List log = workflow.run("user-1"); log.forEach(System.out::println); } } ================================================ FILE: core/src/main/java/io/temporal/samples/nexusmessaging/callerpattern/caller/CallerWorker.java ================================================ package io.temporal.samples.nexusmessaging.callerpattern.caller; import io.temporal.client.WorkflowClient; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.envconfig.LoadClientConfigProfileOptions; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import io.temporal.worker.WorkflowImplementationOptions; import io.temporal.workflow.NexusServiceOptions; import java.nio.file.Paths; import java.util.Collections; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CallerWorker { private static final Logger logger = LoggerFactory.getLogger(CallerWorker.class); static final String CONFIG_PROFILE = "nexus-messaging-caller"; public static final String TASK_QUEUE = "nexus-messaging-caller-task-queue"; static final String NEXUS_ENDPOINT = "nexus-messaging-nexus-endpoint"; public static void main(String[] args) throws InterruptedException { ClientConfigProfile profile; try { String configFilePath = Paths.get(CallerWorker.class.getResource("/config.toml").toURI()).toString(); profile = ClientConfigProfile.load( LoadClientConfigProfileOptions.newBuilder() .setConfigFilePath(configFilePath) .setConfigFileProfile(CONFIG_PROFILE) .build()); } catch (Exception e) { throw new RuntimeException("Failed to load client configuration", e); } WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); WorkerFactory factory = WorkerFactory.newInstance(client); Worker worker = factory.newWorker(TASK_QUEUE); worker.registerWorkflowImplementationTypes( WorkflowImplementationOptions.newBuilder() .setNexusServiceOptions( // The key must match the @Service-annotated interface name. Collections.singletonMap( "NexusGreetingService", NexusServiceOptions.newBuilder().setEndpoint(NEXUS_ENDPOINT).build())) .build(), CallerWorkflowImpl.class); factory.start(); logger.info("Caller worker started, ctrl+c to exit"); Thread.currentThread().join(); } } ================================================ FILE: core/src/main/java/io/temporal/samples/nexusmessaging/callerpattern/caller/CallerWorkflow.java ================================================ package io.temporal.samples.nexusmessaging.callerpattern.caller; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; import java.util.List; @WorkflowInterface public interface CallerWorkflow { @WorkflowMethod List run(String userId); } ================================================ FILE: core/src/main/java/io/temporal/samples/nexusmessaging/callerpattern/caller/CallerWorkflowImpl.java ================================================ package io.temporal.samples.nexusmessaging.callerpattern.caller; import io.temporal.failure.ApplicationFailure; import io.temporal.samples.nexusmessaging.callerpattern.service.Language; import io.temporal.samples.nexusmessaging.callerpattern.service.NexusGreetingService; import io.temporal.workflow.NexusOperationOptions; import io.temporal.workflow.NexusServiceOptions; import io.temporal.workflow.Workflow; import java.time.Duration; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; public class CallerWorkflowImpl implements CallerWorkflow { private static final Logger logger = Workflow.getLogger(CallerWorkflowImpl.class); // The endpoint is configured at the worker level in CallerWorker; only operation options are // set here. NexusGreetingService greetingService = Workflow.newNexusServiceStub( NexusGreetingService.class, NexusServiceOptions.newBuilder() .setOperationOptions( NexusOperationOptions.newBuilder() .setScheduleToCloseTimeout(Duration.ofSeconds(10)) .build()) .build()); @Override public List run(String userId) { // Messages in the log array are passed back to the caller who will then log them to report what // is happening. // The same message is also logged for demo purposes, so that things are visible in the caller // workflow output. List log = new ArrayList<>(); // Call a Nexus operation backed by a query against the entity workflow. // The workflow must already be running on the handler, otherwise you will // get an error saying the workflow has already terminated. NexusGreetingService.GetLanguagesOutput languagesOutput = greetingService.getLanguages(new NexusGreetingService.GetLanguagesInput(false, userId)); log.add("Supported languages: " + languagesOutput.getLanguages()); logger.info("Supported languages: {}", languagesOutput.getLanguages()); // Following are examples for each of the three messaging types - // update, query, then signal. // Call a Nexus operation backed by an update against the entity workflow. Language previousLanguage = greetingService.setLanguage( new NexusGreetingService.SetLanguageInput(Language.ARABIC, userId)); // Call a Nexus operation backed by a query to confirm the language change. Language currentLanguage = greetingService.getLanguage(new NexusGreetingService.GetLanguageInput(userId)); if (currentLanguage != Language.ARABIC) { throw ApplicationFailure.newFailure( "Expected language ARABIC, got " + currentLanguage, "AssertionError"); } log.add("Language changed: " + previousLanguage.name() + " -> " + Language.ARABIC.name()); logger.info("Language changed from {} to {}", previousLanguage, Language.ARABIC); // Call a Nexus operation backed by a signal against the entity workflow. greetingService.approve(new NexusGreetingService.ApproveInput("caller", userId)); log.add("Workflow approved"); logger.info("Workflow approved"); return log; } } ================================================ FILE: core/src/main/java/io/temporal/samples/nexusmessaging/callerpattern/handler/GreetingActivity.java ================================================ package io.temporal.samples.nexusmessaging.callerpattern.handler; import io.temporal.activity.ActivityInterface; import io.temporal.activity.ActivityMethod; import io.temporal.samples.nexusmessaging.callerpattern.service.Language; @ActivityInterface public interface GreetingActivity { // Simulates a call to a remote greeting service. Returns null if the language is not supported. @ActivityMethod String callGreetingService(Language language); } ================================================ FILE: core/src/main/java/io/temporal/samples/nexusmessaging/callerpattern/handler/GreetingActivityImpl.java ================================================ package io.temporal.samples.nexusmessaging.callerpattern.handler; import io.temporal.samples.nexusmessaging.callerpattern.service.Language; import java.util.EnumMap; import java.util.Map; public class GreetingActivityImpl implements GreetingActivity { private static final Map GREETINGS = new EnumMap<>(Language.class); static { GREETINGS.put(Language.ARABIC, "مرحبا بالعالم"); GREETINGS.put(Language.CHINESE, "你好,世界"); GREETINGS.put(Language.ENGLISH, "Hello, world"); GREETINGS.put(Language.FRENCH, "Bonjour, monde"); GREETINGS.put(Language.HINDI, "नमस्ते दुनिया"); GREETINGS.put(Language.PORTUGUESE, "Olá mundo"); GREETINGS.put(Language.SPANISH, "Hola mundo"); } @Override public String callGreetingService(Language language) { return GREETINGS.get(language); } } ================================================ FILE: core/src/main/java/io/temporal/samples/nexusmessaging/callerpattern/handler/GreetingWorkflow.java ================================================ package io.temporal.samples.nexusmessaging.callerpattern.handler; import io.temporal.samples.nexusmessaging.callerpattern.service.Language; import io.temporal.samples.nexusmessaging.callerpattern.service.NexusGreetingService; import io.temporal.workflow.QueryMethod; import io.temporal.workflow.SignalMethod; import io.temporal.workflow.UpdateMethod; import io.temporal.workflow.UpdateValidatorMethod; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; /** * A long-running "entity" workflow that backs the NexusGreetingService Nexus operations. The * workflow exposes queries, an update, and a signal. These are private implementation details of * the Nexus service: the caller only interacts via Nexus operations. */ @WorkflowInterface public interface GreetingWorkflow { @WorkflowMethod String run(); // Returns the languages currently supported by the workflow. @QueryMethod NexusGreetingService.GetLanguagesOutput getLanguages( NexusGreetingService.GetLanguagesInput input); // Returns the currently active language. @QueryMethod Language getLanguage(); // Approves the workflow, allowing it to complete. @SignalMethod void approve(NexusGreetingService.ApproveInput input); // Changes the active language synchronously (only supports languages already in the greetings // map). @UpdateMethod Language setLanguage(NexusGreetingService.SetLanguageInput input); @UpdateValidatorMethod(updateName = "setLanguage") void validateSetLanguage(NexusGreetingService.SetLanguageInput input); // Changes the active language, calling an activity to fetch a greeting for new languages. @UpdateMethod Language setLanguageUsingActivity(NexusGreetingService.SetLanguageInput input); } ================================================ FILE: core/src/main/java/io/temporal/samples/nexusmessaging/callerpattern/handler/GreetingWorkflowImpl.java ================================================ package io.temporal.samples.nexusmessaging.callerpattern.handler; import io.temporal.activity.ActivityOptions; import io.temporal.failure.ApplicationFailure; import io.temporal.samples.nexusmessaging.callerpattern.service.Language; import io.temporal.samples.nexusmessaging.callerpattern.service.NexusGreetingService; import io.temporal.workflow.Workflow; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.EnumMap; import java.util.List; import java.util.Map; import org.slf4j.Logger; public class GreetingWorkflowImpl implements GreetingWorkflow { private boolean approvedForRelease = false; private final Map greetings = new EnumMap<>(Language.class); private Language language = Language.ENGLISH; private static final Logger logger = Workflow.getLogger(GreetingWorkflowImpl.class); private final GreetingActivity greetingActivity = Workflow.newActivityStub( GreetingActivity.class, ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(10)).build()); public GreetingWorkflowImpl() { greetings.put(Language.CHINESE, "你好,世界"); greetings.put(Language.ENGLISH, "Hello, world"); } @Override public String run() { // Wait until approved and all in-flight update handlers have finished. Workflow.await(() -> approvedForRelease && Workflow.isEveryHandlerFinished()); return greetings.get(language); } @Override public NexusGreetingService.GetLanguagesOutput getLanguages( NexusGreetingService.GetLanguagesInput input) { List result; if (input.isIncludeUnsupported()) { result = new ArrayList<>(Arrays.asList(Language.values())); } else { result = new ArrayList<>(greetings.keySet()); } Collections.sort(result); return new NexusGreetingService.GetLanguagesOutput(result); } @Override public Language getLanguage() { return language; } @Override public void approve(NexusGreetingService.ApproveInput input) { logger.info( "Approval signal received for workflow {}", NexusGreetingServiceImpl.getWorkflowId(input.getUserId())); approvedForRelease = true; } @Override public Language setLanguage(NexusGreetingService.SetLanguageInput input) { logger.info( "setLanguage update received for workflow {}", NexusGreetingServiceImpl.getWorkflowId(input.getUserId())); Language previous = language; language = input.getLanguage(); return previous; } @Override public void validateSetLanguage(NexusGreetingService.SetLanguageInput input) { logger.info( "validateSetLanguage called for workflow {}", NexusGreetingServiceImpl.getWorkflowId(input.getUserId())); if (!greetings.containsKey(input.getLanguage())) { throw new IllegalArgumentException(input.getLanguage().name() + " is not supported"); } } @Override public Language setLanguageUsingActivity(NexusGreetingService.SetLanguageInput input) { if (!greetings.containsKey(input.getLanguage())) { String greeting = greetingActivity.callGreetingService(input.getLanguage()); if (greeting == null) { throw ApplicationFailure.newFailure( "Greeting service does not support " + input.getLanguage().name(), "UnsupportedLanguage"); } greetings.put(input.getLanguage(), greeting); } Language previous = language; language = input.getLanguage(); return previous; } } ================================================ FILE: core/src/main/java/io/temporal/samples/nexusmessaging/callerpattern/handler/HandlerWorker.java ================================================ package io.temporal.samples.nexusmessaging.callerpattern.handler; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowExecutionAlreadyStarted; import io.temporal.client.WorkflowOptions; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.envconfig.LoadClientConfigProfileOptions; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import java.nio.file.Paths; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class HandlerWorker { private static final Logger logger = LoggerFactory.getLogger(HandlerWorker.class); static final String CONFIG_PROFILE = "nexus-messaging-handler"; public static final String TASK_QUEUE = "nexus-messaging-handler-task-queue"; static final String USER_ID = "user-1"; public static void main(String[] args) throws InterruptedException { ClientConfigProfile profile; try { String configFilePath = Paths.get(HandlerWorker.class.getResource("/config.toml").toURI()).toString(); profile = ClientConfigProfile.load( LoadClientConfigProfileOptions.newBuilder() .setConfigFilePath(configFilePath) .setConfigFileProfile(CONFIG_PROFILE) .build()); } catch (Exception e) { throw new RuntimeException("Failed to load client configuration", e); } WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); // Start the long-running entity workflow that backs the Nexus service, if not already running. // Create a workflow ID derived from the given user ID. // This would be for a process that would create a workflow for each UserID, // if you had a single long running workflow for all users then you could // remove all the USER_IDs from the inputs and just make everything refer // to a single workflow ID. String workflowId = NexusGreetingServiceImpl.getWorkflowId(USER_ID); GreetingWorkflow greetingWorkflow = client.newWorkflowStub( GreetingWorkflow.class, WorkflowOptions.newBuilder() .setWorkflowId(workflowId) .setTaskQueue(TASK_QUEUE) .build()); try { WorkflowClient.start(greetingWorkflow::run); logger.info("Started greeting workflow: {}", workflowId); } catch (WorkflowExecutionAlreadyStarted e) { logger.info("Greeting workflow already running: {}", workflowId); } WorkerFactory factory = WorkerFactory.newInstance(client); Worker worker = factory.newWorker(TASK_QUEUE); worker.registerWorkflowImplementationTypes(GreetingWorkflowImpl.class); worker.registerActivitiesImplementations(new GreetingActivityImpl()); worker.registerNexusServiceImplementation(new NexusGreetingServiceImpl()); factory.start(); logger.info("Handler worker started, ctrl+c to exit"); Thread.currentThread().join(); } } ================================================ FILE: core/src/main/java/io/temporal/samples/nexusmessaging/callerpattern/handler/NexusGreetingServiceImpl.java ================================================ package io.temporal.samples.nexusmessaging.callerpattern.handler; import io.nexusrpc.handler.OperationHandler; import io.nexusrpc.handler.OperationImpl; import io.nexusrpc.handler.ServiceImpl; import io.temporal.nexus.Nexus; import io.temporal.samples.nexusmessaging.callerpattern.service.Language; import io.temporal.samples.nexusmessaging.callerpattern.service.NexusGreetingService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Nexus operation handler implementation. Each operation receives a userId, which is mapped to a * workflow ID using {@link #WORKFLOW_ID_PREFIX}. The operations are synchronous because queries and * updates against a running workflow complete quickly. */ @ServiceImpl(service = NexusGreetingService.class) public class NexusGreetingServiceImpl { private static final Logger logger = LoggerFactory.getLogger(NexusGreetingServiceImpl.class); static final String WORKFLOW_ID_PREFIX = "GreetingWorkflow_for_"; // This example assumes you might have multiple workflows, one for each user. // If you had a single workflow for all users, then you could remove the // getWorkflowId method, remove the user ID from each input, and just // use the single workflow ID in the getWorkflowStub method below. public static String getWorkflowId(String userId) { return WORKFLOW_ID_PREFIX + userId; } private GreetingWorkflow getWorkflowStub(String userId) { return Nexus.getOperationContext() .getWorkflowClient() .newWorkflowStub(GreetingWorkflow.class, getWorkflowId(userId)); } @OperationImpl public OperationHandler< NexusGreetingService.GetLanguagesInput, NexusGreetingService.GetLanguagesOutput> getLanguages() { return OperationHandler.sync( (ctx, details, input) -> { logger.info("Query for GetLanguages was received for user {}", input.getUserId()); return getWorkflowStub(input.getUserId()).getLanguages(input); }); } @OperationImpl public OperationHandler getLanguage() { return OperationHandler.sync( (ctx, details, input) -> { logger.info("Query for GetLanguage was received for user {}", input.getUserId()); return getWorkflowStub(input.getUserId()).getLanguage(); }); } // Routes to setLanguageUsingActivity (not setLanguage) so that new languages not already in the // greetings map can be fetched via an activity. @OperationImpl public OperationHandler setLanguage() { return OperationHandler.sync( (ctx, details, input) -> { logger.info("Update for SetLanguage was received for user {}", input.getUserId()); return getWorkflowStub(input.getUserId()).setLanguageUsingActivity(input); }); } @OperationImpl public OperationHandler approve() { return OperationHandler.sync( (ctx, details, input) -> { logger.info("Signal for Approve was received for user {}", input.getUserId()); getWorkflowStub(input.getUserId()).approve(input); return new NexusGreetingService.ApproveOutput(); }); } } ================================================ FILE: core/src/main/java/io/temporal/samples/nexusmessaging/callerpattern/service/Language.java ================================================ package io.temporal.samples.nexusmessaging.callerpattern.service; public enum Language { ARABIC, CHINESE, ENGLISH, FRENCH, HINDI, PORTUGUESE, SPANISH } ================================================ FILE: core/src/main/java/io/temporal/samples/nexusmessaging/callerpattern/service/NexusGreetingService.java ================================================ package io.temporal.samples.nexusmessaging.callerpattern.service; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import io.nexusrpc.Operation; import io.nexusrpc.Service; import java.util.List; /** * Nexus service definition. Shared between the handler and caller. The caller uses this to create a * type-safe Nexus client stub; the handler implements the operations. */ @Service public interface NexusGreetingService { class GetLanguagesInput { private final boolean includeUnsupported; private final String userId; @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) public GetLanguagesInput( @JsonProperty("includeUnsupported") boolean includeUnsupported, @JsonProperty("userId") String userId) { this.includeUnsupported = includeUnsupported; this.userId = userId; } @JsonProperty("includeUnsupported") public boolean isIncludeUnsupported() { return includeUnsupported; } @JsonProperty("userId") public String getUserId() { return userId; } } class GetLanguagesOutput { private final List languages; @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) public GetLanguagesOutput(@JsonProperty("languages") List languages) { this.languages = languages; } @JsonProperty("languages") public List getLanguages() { return languages; } } class GetLanguageInput { private final String userId; @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) public GetLanguageInput(@JsonProperty("userId") String userId) { this.userId = userId; } @JsonProperty("userId") public String getUserId() { return userId; } } class ApproveInput { private final String name; private final String userId; @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) public ApproveInput(@JsonProperty("name") String name, @JsonProperty("userId") String userId) { this.name = name; this.userId = userId; } @JsonProperty("name") public String getName() { return name; } @JsonProperty("userId") public String getUserId() { return userId; } } @JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY) class ApproveOutput { @JsonCreator public ApproveOutput() {} } class SetLanguageInput { private final Language language; private final String userId; @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) public SetLanguageInput( @JsonProperty("language") Language language, @JsonProperty("userId") String userId) { this.language = language; this.userId = userId; } @JsonProperty("language") public Language getLanguage() { return language; } @JsonProperty("userId") public String getUserId() { return userId; } } // Returns the languages supported by the greeting workflow. @Operation GetLanguagesOutput getLanguages(GetLanguagesInput input); // Returns the currently active language. @Operation Language getLanguage(GetLanguageInput input); // Changes the active language, returning the previous one. @Operation Language setLanguage(SetLanguageInput input); // Approves the workflow, allowing it to complete. @Operation ApproveOutput approve(ApproveInput input); } ================================================ FILE: core/src/main/java/io/temporal/samples/nexusmessaging/ondemandpattern/README.md ================================================ ## On-demand pattern No Workflow is pre-started. The caller creates and controls Workflow instances through Nexus operations. `NexusRemoteGreetingService` adds a `runFromRemote` operation that starts a new `GreetingWorkflow`, and every other operation includes a `workflowId` so the handler knows which instance to target. The caller Workflow: 1. Starts two remote `GreetingWorkflow` instances via `runFromRemote` (backed by `WorkflowRunOperation`) 2. Queries each for supported languages 3. Changes the language on each (Arabic and Hindi) 4. Confirms the changes via queries 5. Approves both Workflows 6. Waits for each to complete and returns their results ### Running Start a Temporal server: ```bash temporal server start-dev ``` Create the namespaces and Nexus endpoint: ```bash temporal operator namespace create --namespace nexus-messaging-handler-namespace temporal operator namespace create --namespace nexus-messaging-caller-namespace temporal operator nexus endpoint create \ --name nexus-messaging-nexus-endpoint \ --target-namespace nexus-messaging-handler-namespace \ --target-task-queue nexus-messaging-handler-task-queue ``` This sample loads connection settings from `ClientConfigProfile`. The `nexus-messaging-handler` and `nexus-messaging-caller` profiles are defined in `core/src/main/resources/config.toml`. You can override settings with environment variables or by editing the TOML file (see the `envconfig` sample for details). In one terminal, start the handler worker: ```bash ./gradlew -q :core:execute -PmainClass=io.temporal.samples.nexusmessaging.ondemandpattern.handler.HandlerWorker ``` In a second terminal, start the caller worker: ```bash ./gradlew -q :core:execute -PmainClass=io.temporal.samples.nexusmessaging.ondemandpattern.caller.CallerRemoteWorker ``` In a third terminal, run the following command to start the example: ```bash ./gradlew -q :core:execute -PmainClass=io.temporal.samples.nexusmessaging.ondemandpattern.caller.CallerRemoteStarter ``` Expected output: ``` started remote greeting workflow: UserId One started remote greeting workflow: UserId Two Supported languages for UserId One: [CHINESE, ENGLISH] Supported languages for UserId Two: [CHINESE, ENGLISH] UserId One changed language: ENGLISH -> ARABIC UserId Two changed language: ENGLISH -> HINDI Workflows approved Workflow one result: مرحبا بالعالم Workflow two result: नमस्ते दुनिया ``` ================================================ FILE: core/src/main/java/io/temporal/samples/nexusmessaging/ondemandpattern/caller/CallerRemoteStarter.java ================================================ package io.temporal.samples.nexusmessaging.ondemandpattern.caller; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.envconfig.LoadClientConfigProfileOptions; import io.temporal.serviceclient.WorkflowServiceStubs; import java.nio.file.Paths; import java.util.List; import java.util.UUID; public class CallerRemoteStarter { public static void main(String[] args) { ClientConfigProfile profile; try { String configFilePath = Paths.get(CallerRemoteStarter.class.getResource("/config.toml").toURI()).toString(); profile = ClientConfigProfile.load( LoadClientConfigProfileOptions.newBuilder() .setConfigFilePath(configFilePath) .setConfigFileProfile(CallerRemoteWorker.CONFIG_PROFILE) .build()); } catch (Exception e) { throw new RuntimeException("Failed to load client configuration", e); } WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); CallerRemoteWorkflow workflow = client.newWorkflowStub( CallerRemoteWorkflow.class, WorkflowOptions.newBuilder() .setWorkflowId("nexus-messaging-remote-caller-" + UUID.randomUUID()) .setTaskQueue(CallerRemoteWorker.TASK_QUEUE) .build()); List log = workflow.run(); log.forEach(System.out::println); } } ================================================ FILE: core/src/main/java/io/temporal/samples/nexusmessaging/ondemandpattern/caller/CallerRemoteWorker.java ================================================ package io.temporal.samples.nexusmessaging.ondemandpattern.caller; import io.temporal.client.WorkflowClient; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.envconfig.LoadClientConfigProfileOptions; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import io.temporal.worker.WorkflowImplementationOptions; import io.temporal.workflow.NexusServiceOptions; import java.nio.file.Paths; import java.util.Collections; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CallerRemoteWorker { private static final Logger logger = LoggerFactory.getLogger(CallerRemoteWorker.class); static final String CONFIG_PROFILE = "nexus-messaging-caller"; public static final String TASK_QUEUE = "nexus-messaging-caller-remote-task-queue"; static final String NEXUS_ENDPOINT = "nexus-messaging-nexus-endpoint"; public static void main(String[] args) throws InterruptedException { ClientConfigProfile profile; try { String configFilePath = Paths.get(CallerRemoteWorker.class.getResource("/config.toml").toURI()).toString(); profile = ClientConfigProfile.load( LoadClientConfigProfileOptions.newBuilder() .setConfigFilePath(configFilePath) .setConfigFileProfile(CONFIG_PROFILE) .build()); } catch (Exception e) { throw new RuntimeException("Failed to load client configuration", e); } WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); WorkerFactory factory = WorkerFactory.newInstance(client); Worker worker = factory.newWorker(TASK_QUEUE); worker.registerWorkflowImplementationTypes( WorkflowImplementationOptions.newBuilder() .setNexusServiceOptions( // The key must match the @Service-annotated interface name. Collections.singletonMap( "NexusRemoteGreetingService", NexusServiceOptions.newBuilder().setEndpoint(NEXUS_ENDPOINT).build())) .build(), CallerRemoteWorkflowImpl.class); factory.start(); logger.info("Caller remote worker started, ctrl+c to exit"); Thread.currentThread().join(); } } ================================================ FILE: core/src/main/java/io/temporal/samples/nexusmessaging/ondemandpattern/caller/CallerRemoteWorkflow.java ================================================ package io.temporal.samples.nexusmessaging.ondemandpattern.caller; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; import java.util.List; @WorkflowInterface public interface CallerRemoteWorkflow { @WorkflowMethod List run(); } ================================================ FILE: core/src/main/java/io/temporal/samples/nexusmessaging/ondemandpattern/caller/CallerRemoteWorkflowImpl.java ================================================ package io.temporal.samples.nexusmessaging.ondemandpattern.caller; import io.temporal.samples.nexusmessaging.ondemandpattern.service.Language; import io.temporal.samples.nexusmessaging.ondemandpattern.service.NexusRemoteGreetingService; import io.temporal.workflow.NexusOperationHandle; import io.temporal.workflow.NexusOperationOptions; import io.temporal.workflow.NexusServiceOptions; import io.temporal.workflow.Workflow; import java.time.Duration; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; public class CallerRemoteWorkflowImpl implements CallerRemoteWorkflow { private static final Logger logger = Workflow.getLogger(CallerRemoteWorkflowImpl.class); // This is going to create two workflows and send messages to them. // We need to have an ID to differentiate so that Nexus knows how to name // a workflow and then how to know the correct destination workflow. private static final String REMOTE_WORKFLOW_ONE = "UserId One"; private static final String REMOTE_WORKFLOW_TWO = "UserId Two"; NexusRemoteGreetingService greetingRemoteServiceOne = Workflow.newNexusServiceStub( NexusRemoteGreetingService.class, NexusServiceOptions.newBuilder() .setOperationOptions( NexusOperationOptions.newBuilder() .setScheduleToCloseTimeout(Duration.ofSeconds(10)) .build()) .build()); NexusRemoteGreetingService greetingRemoteServiceTwo = Workflow.newNexusServiceStub( NexusRemoteGreetingService.class, NexusServiceOptions.newBuilder() .setOperationOptions( NexusOperationOptions.newBuilder() .setScheduleToCloseTimeout(Duration.ofSeconds(10)) .build()) .build()); @Override public List run() { // Messages in the log array are passed back to the caller who will then log them to report what // is happening. // The same message is also logged for demo purposes, so that things are visible in the caller // workflow output. List log = new ArrayList<>(); // Each call is performed twice in this example. This assumes there are two users we want // to process. The first call starts two workflows, one for each user. // Subsequent calls perform different actions between the two users. // There are examples for each of the three messaging types - // update, query, then signal. // This is an Async Nexus operation — starts a workflow on the handler and returns a handle. // Unlike the sync operations below (getLanguages, setLanguage, etc.), this does not block // until the workflow completes. It is backed by WorkflowRunOperation on the handler side. NexusOperationHandle handleOne = Workflow.startNexusOperation( greetingRemoteServiceOne::runFromRemote, new NexusRemoteGreetingService.RunFromRemoteInput(REMOTE_WORKFLOW_ONE)); // Wait for the operation to be started (workflow is now running on the handler). handleOne.getExecution().get(); log.add("started remote greeting workflow: " + REMOTE_WORKFLOW_ONE); logger.info("started remote greeting workflow {}", REMOTE_WORKFLOW_ONE); NexusOperationHandle handleTwo = Workflow.startNexusOperation( greetingRemoteServiceTwo::runFromRemote, new NexusRemoteGreetingService.RunFromRemoteInput(REMOTE_WORKFLOW_TWO)); // Wait for the operation to be started (workflow is now running on the handler). handleTwo.getExecution().get(); log.add("started remote greeting workflow: " + REMOTE_WORKFLOW_TWO); logger.info("started remote greeting workflow {}", REMOTE_WORKFLOW_TWO); // Query the remote workflow for supported languages. NexusRemoteGreetingService.GetLanguagesOutput languagesOutput = greetingRemoteServiceOne.getLanguages( new NexusRemoteGreetingService.GetLanguagesInput(false, REMOTE_WORKFLOW_ONE)); log.add( "Supported languages for " + REMOTE_WORKFLOW_ONE + ": " + languagesOutput.getLanguages()); logger.info( "supported languages are {} for workflow {}", languagesOutput.getLanguages(), REMOTE_WORKFLOW_ONE); languagesOutput = greetingRemoteServiceTwo.getLanguages( new NexusRemoteGreetingService.GetLanguagesInput(false, REMOTE_WORKFLOW_TWO)); log.add( "Supported languages for " + REMOTE_WORKFLOW_TWO + ": " + languagesOutput.getLanguages()); logger.info( "supported languages are {} for workflow {}", languagesOutput.getLanguages(), REMOTE_WORKFLOW_TWO); // Update the language on the remote workflow. Language previousLanguageOne = greetingRemoteServiceOne.setLanguage( new NexusRemoteGreetingService.SetLanguageInput(Language.ARABIC, REMOTE_WORKFLOW_ONE)); Language previousLanguageTwo = greetingRemoteServiceTwo.setLanguage( new NexusRemoteGreetingService.SetLanguageInput(Language.HINDI, REMOTE_WORKFLOW_TWO)); // Confirm the change by querying. Language currentLanguage = greetingRemoteServiceOne.getLanguage( new NexusRemoteGreetingService.GetLanguageInput(REMOTE_WORKFLOW_ONE)); log.add( REMOTE_WORKFLOW_ONE + " changed language: " + previousLanguageOne.name() + " -> " + currentLanguage.name()); logger.info( "Language changed from {} to {} for workflow {}", previousLanguageOne, currentLanguage, REMOTE_WORKFLOW_ONE); currentLanguage = greetingRemoteServiceTwo.getLanguage( new NexusRemoteGreetingService.GetLanguageInput(REMOTE_WORKFLOW_TWO)); log.add( REMOTE_WORKFLOW_TWO + " changed language: " + previousLanguageTwo.name() + " -> " + currentLanguage.name()); logger.info( "Language changed from {} to {} for workflow {}", previousLanguageTwo, currentLanguage, REMOTE_WORKFLOW_TWO); // Approve the remote workflow so it can complete. greetingRemoteServiceOne.approve( new NexusRemoteGreetingService.ApproveInput("remote-caller", REMOTE_WORKFLOW_ONE)); greetingRemoteServiceTwo.approve( new NexusRemoteGreetingService.ApproveInput("remote-caller", REMOTE_WORKFLOW_TWO)); log.add("Workflows approved"); // Wait for the remote workflow to finish and return its result. String result = handleOne.getResult().get(); log.add("Workflow one result: " + result); result = handleTwo.getResult().get(); log.add("Workflow two result: " + result); return log; } } ================================================ FILE: core/src/main/java/io/temporal/samples/nexusmessaging/ondemandpattern/handler/GreetingActivity.java ================================================ package io.temporal.samples.nexusmessaging.ondemandpattern.handler; import io.temporal.activity.ActivityInterface; import io.temporal.activity.ActivityMethod; import io.temporal.samples.nexusmessaging.ondemandpattern.service.Language; @ActivityInterface public interface GreetingActivity { // Simulates a call to a remote greeting service. Returns null if the language is not supported. @ActivityMethod String callGreetingService(Language language); } ================================================ FILE: core/src/main/java/io/temporal/samples/nexusmessaging/ondemandpattern/handler/GreetingActivityImpl.java ================================================ package io.temporal.samples.nexusmessaging.ondemandpattern.handler; import io.temporal.samples.nexusmessaging.ondemandpattern.service.Language; import java.util.EnumMap; import java.util.Map; public class GreetingActivityImpl implements GreetingActivity { private static final Map GREETINGS = new EnumMap<>(Language.class); static { GREETINGS.put(Language.ARABIC, "مرحبا بالعالم"); GREETINGS.put(Language.CHINESE, "你好,世界"); GREETINGS.put(Language.ENGLISH, "Hello, world"); GREETINGS.put(Language.FRENCH, "Bonjour, monde"); GREETINGS.put(Language.HINDI, "नमस्ते दुनिया"); GREETINGS.put(Language.PORTUGUESE, "Olá mundo"); GREETINGS.put(Language.SPANISH, "Hola mundo"); } @Override public String callGreetingService(Language language) { return GREETINGS.get(language); } } ================================================ FILE: core/src/main/java/io/temporal/samples/nexusmessaging/ondemandpattern/handler/GreetingWorkflow.java ================================================ package io.temporal.samples.nexusmessaging.ondemandpattern.handler; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import io.temporal.samples.nexusmessaging.ondemandpattern.service.Language; import io.temporal.samples.nexusmessaging.ondemandpattern.service.NexusRemoteGreetingService; import io.temporal.workflow.QueryMethod; import io.temporal.workflow.SignalMethod; import io.temporal.workflow.UpdateMethod; import io.temporal.workflow.UpdateValidatorMethod; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; /** * A long-running "entity" workflow that backs the NexusRemoteGreetingService Nexus operations. The * workflow exposes queries, an update, and a signal. These are private implementation details of * the Nexus service: the caller only interacts via Nexus operations. */ @WorkflowInterface public interface GreetingWorkflow { class ApproveInput { private final String name; @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) public ApproveInput(@JsonProperty("name") String name) { this.name = name; } @JsonProperty("name") public String getName() { return name; } } class GetLanguagesInput { private final boolean includeUnsupported; @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) public GetLanguagesInput(@JsonProperty("includeUnsupported") boolean includeUnsupported) { this.includeUnsupported = includeUnsupported; } @JsonProperty("includeUnsupported") public boolean isIncludeUnsupported() { return includeUnsupported; } } class SetLanguageInput { private final Language language; @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) public SetLanguageInput(@JsonProperty("language") Language language) { this.language = language; } @JsonProperty("language") public Language getLanguage() { return language; } } @WorkflowMethod String run(); // Returns the languages currently supported by the workflow. @QueryMethod NexusRemoteGreetingService.GetLanguagesOutput getLanguages(GetLanguagesInput input); // Returns the currently active language. @QueryMethod Language getLanguage(); // Approves the workflow, allowing it to complete. @SignalMethod void approve(ApproveInput input); // Changes the active language synchronously (only supports languages already in the greetings // map). @UpdateMethod Language setLanguage(SetLanguageInput input); @UpdateValidatorMethod(updateName = "setLanguage") void validateSetLanguage(SetLanguageInput input); // Changes the active language, calling an activity to fetch a greeting for new languages. @UpdateMethod Language setLanguageUsingActivity(SetLanguageInput input); } ================================================ FILE: core/src/main/java/io/temporal/samples/nexusmessaging/ondemandpattern/handler/GreetingWorkflowImpl.java ================================================ package io.temporal.samples.nexusmessaging.ondemandpattern.handler; import io.temporal.activity.ActivityOptions; import io.temporal.failure.ApplicationFailure; import io.temporal.samples.nexusmessaging.ondemandpattern.service.Language; import io.temporal.samples.nexusmessaging.ondemandpattern.service.NexusRemoteGreetingService; import io.temporal.workflow.Workflow; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.EnumMap; import java.util.List; import java.util.Map; import org.slf4j.Logger; public class GreetingWorkflowImpl implements GreetingWorkflow { private static final Logger logger = Workflow.getLogger(GreetingWorkflowImpl.class); private boolean approvedForRelease = false; private final Map greetings = new EnumMap<>(Language.class); private Language language = Language.ENGLISH; private final GreetingActivity greetingActivity = Workflow.newActivityStub( GreetingActivity.class, ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(10)).build()); public GreetingWorkflowImpl() { greetings.put(Language.CHINESE, "你好,世界"); greetings.put(Language.ENGLISH, "Hello, world"); } @Override public String run() { // Wait until approved and all in-flight update handlers have finished. Workflow.await(() -> approvedForRelease && Workflow.isEveryHandlerFinished()); return greetings.get(language); } @Override public NexusRemoteGreetingService.GetLanguagesOutput getLanguages( GreetingWorkflow.GetLanguagesInput input) { List result; if (input.isIncludeUnsupported()) { result = new ArrayList<>(Arrays.asList(Language.values())); } else { result = new ArrayList<>(greetings.keySet()); } Collections.sort(result); return new NexusRemoteGreetingService.GetLanguagesOutput(result); } @Override public Language getLanguage() { return language; } @Override public void approve(ApproveInput input) { logger.info("Approval signal received"); approvedForRelease = true; } @Override public Language setLanguage(GreetingWorkflow.SetLanguageInput input) { logger.info("setLanguage update received"); Language previous = language; language = input.getLanguage(); return previous; } @Override public void validateSetLanguage(GreetingWorkflow.SetLanguageInput input) { logger.info("validateSetLanguage called"); if (!greetings.containsKey(input.getLanguage())) { throw new IllegalArgumentException(input.getLanguage().name() + " is not supported"); } } @Override public Language setLanguageUsingActivity(GreetingWorkflow.SetLanguageInput input) { if (!greetings.containsKey(input.getLanguage())) { String greeting = greetingActivity.callGreetingService(input.getLanguage()); if (greeting == null) { throw ApplicationFailure.newFailure( "Greeting service does not support " + input.getLanguage().name(), "UnsupportedLanguage"); } greetings.put(input.getLanguage(), greeting); } Language previous = language; language = input.getLanguage(); return previous; } } ================================================ FILE: core/src/main/java/io/temporal/samples/nexusmessaging/ondemandpattern/handler/HandlerWorker.java ================================================ package io.temporal.samples.nexusmessaging.ondemandpattern.handler; import io.temporal.client.WorkflowClient; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.envconfig.LoadClientConfigProfileOptions; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import java.nio.file.Paths; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class HandlerWorker { private static final Logger logger = LoggerFactory.getLogger(HandlerWorker.class); static final String CONFIG_PROFILE = "nexus-messaging-handler"; public static final String TASK_QUEUE = "nexus-messaging-handler-task-queue"; public static void main(String[] args) throws InterruptedException { ClientConfigProfile profile; try { String configFilePath = Paths.get(HandlerWorker.class.getResource("/config.toml").toURI()).toString(); profile = ClientConfigProfile.load( LoadClientConfigProfileOptions.newBuilder() .setConfigFilePath(configFilePath) .setConfigFileProfile(CONFIG_PROFILE) .build()); } catch (Exception e) { throw new RuntimeException("Failed to load client configuration", e); } WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); WorkerFactory factory = WorkerFactory.newInstance(client); Worker worker = factory.newWorker(TASK_QUEUE); worker.registerWorkflowImplementationTypes(GreetingWorkflowImpl.class); worker.registerActivitiesImplementations(new GreetingActivityImpl()); worker.registerNexusServiceImplementation(new NexusRemoteGreetingServiceImpl()); factory.start(); logger.info("Handler worker started, ctrl+c to exit"); Thread.currentThread().join(); } } ================================================ FILE: core/src/main/java/io/temporal/samples/nexusmessaging/ondemandpattern/handler/NexusRemoteGreetingServiceImpl.java ================================================ package io.temporal.samples.nexusmessaging.ondemandpattern.handler; import io.nexusrpc.handler.OperationHandler; import io.nexusrpc.handler.OperationImpl; import io.nexusrpc.handler.ServiceImpl; import io.temporal.client.WorkflowOptions; import io.temporal.nexus.Nexus; import io.temporal.nexus.WorkflowHandle; import io.temporal.nexus.WorkflowRunOperation; import io.temporal.samples.nexusmessaging.ondemandpattern.service.Language; import io.temporal.samples.nexusmessaging.ondemandpattern.service.NexusRemoteGreetingService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Nexus operation handler for the on-demand pattern. Each operation receives the target workflow ID * in its input, and {@code runFromRemote} starts a brand-new GreetingWorkflow. */ @ServiceImpl(service = NexusRemoteGreetingService.class) public class NexusRemoteGreetingServiceImpl { private static final Logger logger = LoggerFactory.getLogger(NexusRemoteGreetingServiceImpl.class); static final String WORKFLOW_ID_PREFIX = "GreetingWorkflow_for_"; // This example assumes you might have multiple workflows, one for each user. // If you had a single workflow for all users, then you could remove the // getWorkflowId method, remove the user ID from each input, and just // use the single workflow ID in the getWorkflowStub method below. public static String getWorkflowId(String userId) { return WORKFLOW_ID_PREFIX + userId; } private GreetingWorkflow getWorkflowStub(String userId) { return Nexus.getOperationContext() .getWorkflowClient() .newWorkflowStub(GreetingWorkflow.class, getWorkflowId(userId)); } // Starts a new GreetingWorkflow with the caller-specified workflow ID. This is an async // Nexus operation backed by WorkflowRunOperation. @OperationImpl public OperationHandler runFromRemote() { return WorkflowRunOperation.fromWorkflowHandle( (ctx, details, input) -> { logger.info("RunFromRemote was received for userID {}", input.getUserId()); return WorkflowHandle.fromWorkflowMethod( Nexus.getOperationContext() .getWorkflowClient() .newWorkflowStub( GreetingWorkflow.class, WorkflowOptions.newBuilder() .setWorkflowId(getWorkflowId(input.getUserId())) .setTaskQueue(HandlerWorker.TASK_QUEUE) .build()) ::run); }); } @OperationImpl public OperationHandler< NexusRemoteGreetingService.GetLanguagesInput, NexusRemoteGreetingService.GetLanguagesOutput> getLanguages() { return OperationHandler.sync( (ctx, details, input) -> { logger.info("Query for GetLanguages was received for userId {}", input.getUserId()); return getWorkflowStub(input.getUserId()) .getLanguages(new GreetingWorkflow.GetLanguagesInput(input.isIncludeUnsupported())); }); } @OperationImpl public OperationHandler getLanguage() { return OperationHandler.sync( (ctx, details, input) -> { logger.info("Query for GetLanguage was received for userId {}", input.getUserId()); return getWorkflowStub(input.getUserId()).getLanguage(); }); } // Uses setLanguageUsingActivity so that new languages are fetched via an activity. @OperationImpl public OperationHandler setLanguage() { return OperationHandler.sync( (ctx, details, input) -> { logger.info("Update for SetLanguage was received for userId {}", input.getUserId()); return getWorkflowStub(input.getUserId()) .setLanguageUsingActivity(new GreetingWorkflow.SetLanguageInput(input.getLanguage())); }); } @OperationImpl public OperationHandler< NexusRemoteGreetingService.ApproveInput, NexusRemoteGreetingService.ApproveOutput> approve() { return OperationHandler.sync( (ctx, details, input) -> { logger.info("Signal for Approve was received for userId {}", input.getUserId()); getWorkflowStub(input.getUserId()) .approve(new GreetingWorkflow.ApproveInput(input.getName())); return new NexusRemoteGreetingService.ApproveOutput(); }); } } ================================================ FILE: core/src/main/java/io/temporal/samples/nexusmessaging/ondemandpattern/service/Language.java ================================================ package io.temporal.samples.nexusmessaging.ondemandpattern.service; public enum Language { ARABIC, CHINESE, ENGLISH, FRENCH, HINDI, PORTUGUESE, SPANISH } ================================================ FILE: core/src/main/java/io/temporal/samples/nexusmessaging/ondemandpattern/service/NexusRemoteGreetingService.java ================================================ package io.temporal.samples.nexusmessaging.ondemandpattern.service; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import io.nexusrpc.Operation; import io.nexusrpc.Service; import java.util.List; /** * Nexus service definition for the on-demand pattern. Every operation includes a {@code userId} so * the caller controls which workflow instance is targeted though that, while the Nexus service * converts that UserId into a WorkflowId. This also exposes a {@code runFromRemote} operation that * starts a new GreetingWorkflow. */ @Service public interface NexusRemoteGreetingService { class RunFromRemoteInput { private final String userId; @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) public RunFromRemoteInput(@JsonProperty("userId") String userId) { this.userId = userId; } @JsonProperty("userId") public String getUserId() { return userId; } } class GetLanguagesInput { private final boolean includeUnsupported; private final String userId; @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) public GetLanguagesInput( @JsonProperty("includeUnsupported") boolean includeUnsupported, @JsonProperty("userId") String userId) { this.includeUnsupported = includeUnsupported; this.userId = userId; } @JsonProperty("includeUnsupported") public boolean isIncludeUnsupported() { return includeUnsupported; } @JsonProperty("userId") public String getUserId() { return userId; } } @JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY) class GetLanguageInput { private final String userId; @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) public GetLanguageInput(@JsonProperty("userId") String userId) { this.userId = userId; } @JsonProperty("userId") public String getUserId() { return userId; } } class SetLanguageInput { private final Language language; private final String userId; @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) public SetLanguageInput( @JsonProperty("language") Language language, @JsonProperty("userId") String userId) { this.language = language; this.userId = userId; } @JsonProperty("language") public Language getLanguage() { return language; } @JsonProperty("userId") public String getUserId() { return userId; } } class ApproveInput { private final String name; private final String userId; @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) public ApproveInput(@JsonProperty("name") String name, @JsonProperty("userId") String userId) { this.name = name; this.userId = userId; } @JsonProperty("name") public String getName() { return name; } @JsonProperty("userId") public String getUserId() { return userId; } } class GetLanguagesOutput { private final List languages; @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) public GetLanguagesOutput(@JsonProperty("languages") List languages) { this.languages = languages; } @JsonProperty("languages") public List getLanguages() { return languages; } } @JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY) class ApproveOutput { @JsonCreator public ApproveOutput() {} } // Starts a new GreetingWorkflow for the given user ID. This is an asynchronous Nexus // operation: the caller receives a handle and can wait for the workflow to complete. @Operation String runFromRemote(RunFromRemoteInput input); // Returns the languages supported by the specified workflow. @Operation GetLanguagesOutput getLanguages(GetLanguagesInput input); // Returns the currently active language of the specified workflow. @Operation Language getLanguage(GetLanguageInput input); // Changes the active language on the specified workflow, returning the previous one. @Operation Language setLanguage(SetLanguageInput input); // Approves the specified workflow, allowing it to complete. @Operation ApproveOutput approve(ApproveInput input); } ================================================ FILE: core/src/main/java/io/temporal/samples/nexusmultipleargs/README.MD ================================================ # Nexus Multiple Arguments Sample This sample shows how to map a Nexus operation to a caller workflow that takes multiple input arguments using [WorkflowRunOperation.fromWorkflowHandle](https://javadoc.io/doc/io.temporal/temporal-sdk/latest/io/temporal/nexus/WorkflowRunOperation.html#fromWorkflowHandle(io.temporal.nexus.WorkflowHandleFactory)). To run this sample, set up your environment following the instructions in the main [Nexus Sample](../nexus/README.md). In separate terminal windows: ### Nexus handler worker ``` ./gradlew -q execute -PmainClass=io.temporal.samples.nexusmultipleargs.handler.HandlerWorker \ --args="-target-host localhost:7233 -namespace my-target-namespace" ``` ### Nexus caller worker ``` ./gradlew -q execute -PmainClass=io.temporal.samples.nexusmultipleargs.caller.CallerWorker \ --args="-target-host localhost:7233 -namespace my-caller-namespace" ``` ### Start caller workflow ``` ./gradlew -q execute -PmainClass=io.temporal.samples.nexusmultipleargs.caller.CallerStarter \ --args="-target-host localhost:7233 -namespace my-caller-namespace" ``` ### Output which should result in: ``` [main] INFO i.t.s.nexus.caller.CallerStarter - Workflow result: Nexus Echo 👋 [main] INFO i.t.s.nexus.caller.CallerStarter - Workflow result: ¡Hola! Nexus 👋 ``` ================================================ FILE: core/src/main/java/io/temporal/samples/nexusmultipleargs/caller/CallerStarter.java ================================================ package io.temporal.samples.nexusmultipleargs.caller; import io.temporal.api.common.v1.WorkflowExecution; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.samples.nexus.caller.CallerWorker; import io.temporal.samples.nexus.caller.EchoCallerWorkflow; import io.temporal.samples.nexus.caller.HelloCallerWorkflow; import io.temporal.samples.nexus.options.ClientOptions; import io.temporal.samples.nexus.service.SampleNexusService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CallerStarter { private static final Logger logger = LoggerFactory.getLogger(CallerStarter.class); public static void main(String[] args) { WorkflowClient client = ClientOptions.getWorkflowClient(args); WorkflowOptions workflowOptions = WorkflowOptions.newBuilder().setTaskQueue(CallerWorker.DEFAULT_TASK_QUEUE_NAME).build(); EchoCallerWorkflow echoWorkflow = client.newWorkflowStub(EchoCallerWorkflow.class, workflowOptions); WorkflowExecution execution = WorkflowClient.start(echoWorkflow::echo, "Nexus Echo 👋"); logger.info( "Started EchoCallerWorkflow workflowId: {} runId: {}", execution.getWorkflowId(), execution.getRunId()); logger.info("Workflow result: {}", echoWorkflow.echo("Nexus Echo 👋")); HelloCallerWorkflow helloWorkflow = client.newWorkflowStub(HelloCallerWorkflow.class, workflowOptions); execution = WorkflowClient.start(helloWorkflow::hello, "Nexus", SampleNexusService.Language.EN); logger.info( "Started HelloCallerWorkflow workflowId: {} runId: {}", execution.getWorkflowId(), execution.getRunId()); logger.info( "Workflow result: {}", helloWorkflow.hello("Nexus", SampleNexusService.Language.ES)); } } ================================================ FILE: core/src/main/java/io/temporal/samples/nexusmultipleargs/caller/CallerWorker.java ================================================ package io.temporal.samples.nexusmultipleargs.caller; import io.temporal.client.WorkflowClient; import io.temporal.samples.nexus.options.ClientOptions; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import io.temporal.worker.WorkflowImplementationOptions; import io.temporal.workflow.NexusServiceOptions; import java.util.Collections; public class CallerWorker { public static final String DEFAULT_TASK_QUEUE_NAME = "my-caller-workflow-task-queue"; public static void main(String[] args) { WorkflowClient client = ClientOptions.getWorkflowClient(args); WorkerFactory factory = WorkerFactory.newInstance(client); Worker worker = factory.newWorker(DEFAULT_TASK_QUEUE_NAME); worker.registerWorkflowImplementationTypes( WorkflowImplementationOptions.newBuilder() .setNexusServiceOptions( Collections.singletonMap( "SampleNexusService", NexusServiceOptions.newBuilder().setEndpoint("my-nexus-endpoint-name").build())) .build(), EchoCallerWorkflowImpl.class, HelloCallerWorkflowImpl.class); factory.start(); } } ================================================ FILE: core/src/main/java/io/temporal/samples/nexusmultipleargs/caller/EchoCallerWorkflow.java ================================================ package io.temporal.samples.nexusmultipleargs.caller; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; @WorkflowInterface public interface EchoCallerWorkflow { @WorkflowMethod String echo(String message); } ================================================ FILE: core/src/main/java/io/temporal/samples/nexusmultipleargs/caller/EchoCallerWorkflowImpl.java ================================================ package io.temporal.samples.nexusmultipleargs.caller; import io.temporal.samples.nexus.caller.EchoCallerWorkflow; import io.temporal.samples.nexus.service.SampleNexusService; import io.temporal.workflow.NexusOperationOptions; import io.temporal.workflow.NexusServiceOptions; import io.temporal.workflow.Workflow; import java.time.Duration; public class EchoCallerWorkflowImpl implements EchoCallerWorkflow { SampleNexusService sampleNexusService = Workflow.newNexusServiceStub( SampleNexusService.class, NexusServiceOptions.newBuilder() .setOperationOptions( NexusOperationOptions.newBuilder() .setScheduleToCloseTimeout(Duration.ofSeconds(10)) .build()) .build()); @Override public String echo(String message) { return sampleNexusService.echo(new SampleNexusService.EchoInput(message)).getMessage(); } } ================================================ FILE: core/src/main/java/io/temporal/samples/nexusmultipleargs/caller/HelloCallerWorkflow.java ================================================ package io.temporal.samples.nexusmultipleargs.caller; import io.temporal.samples.nexus.service.SampleNexusService; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; @WorkflowInterface public interface HelloCallerWorkflow { @WorkflowMethod String hello(String message, SampleNexusService.Language language); } ================================================ FILE: core/src/main/java/io/temporal/samples/nexusmultipleargs/caller/HelloCallerWorkflowImpl.java ================================================ package io.temporal.samples.nexusmultipleargs.caller; import io.temporal.samples.nexus.caller.HelloCallerWorkflow; import io.temporal.samples.nexus.service.SampleNexusService; import io.temporal.workflow.NexusOperationHandle; import io.temporal.workflow.NexusOperationOptions; import io.temporal.workflow.NexusServiceOptions; import io.temporal.workflow.Workflow; import java.time.Duration; public class HelloCallerWorkflowImpl implements HelloCallerWorkflow { SampleNexusService sampleNexusService = Workflow.newNexusServiceStub( SampleNexusService.class, NexusServiceOptions.newBuilder() .setOperationOptions( NexusOperationOptions.newBuilder() .setScheduleToCloseTimeout(Duration.ofSeconds(10)) .build()) .build()); @Override public String hello(String message, SampleNexusService.Language language) { NexusOperationHandle handle = Workflow.startNexusOperation( sampleNexusService::hello, new SampleNexusService.HelloInput(message, language)); // Optionally wait for the operation to be started. NexusOperationExecution will contain the // operation token in case this operation is asynchronous. handle.getExecution().get(); return handle.getResult().get().getMessage(); } } ================================================ FILE: core/src/main/java/io/temporal/samples/nexusmultipleargs/handler/HandlerWorker.java ================================================ package io.temporal.samples.nexusmultipleargs.handler; import io.temporal.client.WorkflowClient; import io.temporal.samples.nexus.options.ClientOptions; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; public class HandlerWorker { public static final String DEFAULT_TASK_QUEUE_NAME = "my-handler-task-queue"; public static void main(String[] args) { WorkflowClient client = ClientOptions.getWorkflowClient(args); WorkerFactory factory = WorkerFactory.newInstance(client); Worker worker = factory.newWorker(DEFAULT_TASK_QUEUE_NAME); worker.registerWorkflowImplementationTypes(HelloHandlerWorkflowImpl.class); worker.registerNexusServiceImplementation(new SampleNexusServiceImpl()); factory.start(); } } ================================================ FILE: core/src/main/java/io/temporal/samples/nexusmultipleargs/handler/HelloHandlerWorkflow.java ================================================ package io.temporal.samples.nexusmultipleargs.handler; import io.temporal.samples.nexus.service.SampleNexusService; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; @WorkflowInterface public interface HelloHandlerWorkflow { @WorkflowMethod SampleNexusService.HelloOutput hello(String name, SampleNexusService.Language language); } ================================================ FILE: core/src/main/java/io/temporal/samples/nexusmultipleargs/handler/HelloHandlerWorkflowImpl.java ================================================ package io.temporal.samples.nexusmultipleargs.handler; import io.temporal.failure.ApplicationFailure; import io.temporal.samples.nexus.service.SampleNexusService; public class HelloHandlerWorkflowImpl implements HelloHandlerWorkflow { @Override public SampleNexusService.HelloOutput hello(String name, SampleNexusService.Language language) { switch (language) { case EN: return new SampleNexusService.HelloOutput("Hello " + name + " 👋"); case FR: return new SampleNexusService.HelloOutput("Bonjour " + name + " 👋"); case DE: return new SampleNexusService.HelloOutput("Hallo " + name + " 👋"); case ES: return new SampleNexusService.HelloOutput("¡Hola! " + name + " 👋"); case TR: return new SampleNexusService.HelloOutput("Merhaba " + name + " 👋"); } throw ApplicationFailure.newFailure( "Unsupported language: " + language, "UNSUPPORTED_LANGUAGE"); } } ================================================ FILE: core/src/main/java/io/temporal/samples/nexusmultipleargs/handler/SampleNexusServiceImpl.java ================================================ package io.temporal.samples.nexusmultipleargs.handler; import io.nexusrpc.handler.OperationHandler; import io.nexusrpc.handler.OperationImpl; import io.nexusrpc.handler.ServiceImpl; import io.temporal.client.WorkflowOptions; import io.temporal.nexus.Nexus; import io.temporal.nexus.WorkflowHandle; import io.temporal.nexus.WorkflowRunOperation; import io.temporal.samples.nexus.service.SampleNexusService; // To create a service implementation, annotate the class with @ServiceImpl and provide the // interface that the service implements. The service implementation class should have methods that // return OperationHandler that correspond to the operations defined in the service interface. @ServiceImpl(service = SampleNexusService.class) public class SampleNexusServiceImpl { @OperationImpl public OperationHandler echo() { // OperationHandler.sync is a meant for exposing simple RPC handlers. return OperationHandler.sync( // The method is for making arbitrary short calls to other services or databases, or // perform simple computations such as this one. Users can also access a workflow client by // calling // Nexus.getOperationContext().getWorkflowClient(ctx) to make arbitrary calls such as // signaling, querying, or listing workflows. (ctx, details, input) -> new SampleNexusService.EchoOutput(input.getMessage())); } @OperationImpl public OperationHandler hello() { // If the operation input parameters are different from the workflow input parameters, // use the WorkflowRunOperation.fromWorkflowHandler constructor and the appropriate constructor // method on WorkflowHandle to map the Nexus input to the workflow parameters. return WorkflowRunOperation.fromWorkflowHandle( (ctx, details, input) -> WorkflowHandle.fromWorkflowMethod( Nexus.getOperationContext() .getWorkflowClient() .newWorkflowStub( HelloHandlerWorkflow.class, // Workflow IDs should typically be business meaningful IDs and are used // to // dedupe workflow starts. // For this example, we're using the request ID allocated by Temporal // when // the // caller workflow schedules // the operation, this ID is guaranteed to be stable across retries of // this // operation. // // Task queue defaults to the task queue this operation is handled on. WorkflowOptions.newBuilder() .setWorkflowId(details.getRequestId()) .build()) ::hello, input.getName(), input.getLanguage())); } } ================================================ FILE: core/src/main/java/io/temporal/samples/packetdelivery/Packet.java ================================================ package io.temporal.samples.packetdelivery; public class Packet { private int id; private String content; public Packet() {} public Packet(int id, String content) { this.id = id; this.content = content; } public int getId() { return id; } public String getContent() { return content; } } ================================================ FILE: core/src/main/java/io/temporal/samples/packetdelivery/PacketDelivery.java ================================================ package io.temporal.samples.packetdelivery; import io.temporal.activity.ActivityOptions; import io.temporal.failure.ActivityFailure; import io.temporal.failure.CanceledFailure; import io.temporal.workflow.*; import java.time.Duration; import org.slf4j.Logger; public class PacketDelivery { private Packet packet; private boolean deliveryConfirmation = false; private boolean needDeliveryConfirmation = false; private CompletablePromise delivered = Workflow.newPromise(); private CancellationScope cancellationScope; private Logger logger = Workflow.getLogger(this.getClass().getName()); private final PacketDeliveryActivities activities = Workflow.newActivityStub( PacketDeliveryActivities.class, ActivityOptions.newBuilder() .setStartToCloseTimeout(Duration.ofSeconds(5)) .setHeartbeatTimeout(Duration.ofSeconds(2)) .build()); private final PacketDeliveryActivities compensationActivities = Workflow.newActivityStub( PacketDeliveryActivities.class, ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(3)).build()); public PacketDelivery(Packet packet) { this.packet = packet; processDeliveryAsync(); } public Promise getDelivered() { return delivered; } public void processDeliveryAsync() { delivered.completeFrom(Async.procedure(this::processDelivery)); } public void processDelivery() { cancellationScope = Workflow.newCancellationScope( () -> { String deliveryConfirmationResult = ""; while (!deliveryConfirmationResult.equals(PacketUtils.COMPLETION_SUCCESS)) { // Step 1 perform delivery logger.info( "** Performing delivery for packet: " + packet.getId() + " - " + packet.getContent()); activities.performDelivery(packet); // Step 2 wait for delivery confirmation logger.info( "** Delivery for packet: " + packet.getId() + " - " + packet.getContent() + " awaiting delivery confirmation"); needDeliveryConfirmation = true; Workflow.await(() -> deliveryConfirmation); logger.info( "** Delivery for packet: " + packet.getId() + " - " + packet.getContent() + " received confirmation"); // Step 3 complete delivery processing logger.info( "** Completing delivery for packet: " + packet.getId() + " - " + packet.getContent()); deliveryConfirmationResult = activities.completeDelivery(packet); // Reset deliveryConfirmation and needDeliveryConfirmation deliveryConfirmation = false; needDeliveryConfirmation = false; } }); try { cancellationScope.run(); } catch (Exception e) { if (e instanceof ActivityFailure) { ActivityFailure activityFailure = (ActivityFailure) e; if (activityFailure.getCause() instanceof CanceledFailure) { // Run compensation activity and complete compensationActivities.compensateDelivery(packet); } } // Just for show for example that cancel could come in while we are waiting on approval signal // too else if (e instanceof CanceledFailure) { needDeliveryConfirmation = false; // Run compensation activity and complete compensationActivities.compensateDelivery(packet); } return; } } public void confirmDelivery() { this.deliveryConfirmation = true; } public void cancelDelivery(String reason) { if (cancellationScope != null) { cancellationScope.cancel(reason); } } public boolean isNeedDeliveryConfirmation() { return needDeliveryConfirmation; } public Packet getPacket() { return packet; } } ================================================ FILE: core/src/main/java/io/temporal/samples/packetdelivery/PacketDeliveryActivities.java ================================================ package io.temporal.samples.packetdelivery; import io.temporal.activity.ActivityInterface; import java.util.List; @ActivityInterface public interface PacketDeliveryActivities { List generatePackets(); void performDelivery(Packet packet); String completeDelivery(Packet packet); String compensateDelivery(Packet packet); } ================================================ FILE: core/src/main/java/io/temporal/samples/packetdelivery/PacketDeliveryActivitiesImpl.java ================================================ package io.temporal.samples.packetdelivery; import io.temporal.activity.Activity; import io.temporal.activity.ActivityExecutionContext; import io.temporal.client.ActivityCompletionException; import io.temporal.client.WorkflowClient; import java.util.*; public class PacketDeliveryActivitiesImpl implements PacketDeliveryActivities { private List packets = Arrays.asList( new Packet(1, "books"), new Packet(2, "jewelry"), new Packet(3, "furniture"), new Packet(4, "food"), new Packet(5, "electronics")); private WorkflowClient client; public PacketDeliveryActivitiesImpl(WorkflowClient client) { this.client = client; } @Override public List generatePackets() { return packets; } @Override public void performDelivery(Packet packet) { ActivityExecutionContext context = Activity.getExecutionContext(); System.out.println( "** Activity - Performing delivery for packet: " + packet.getId() + " with content: " + packet.getContent()); for (int i = 0; i < 4; i++) { try { // Perform the heartbeat. Used to notify the workflow that activity execution is alive context.heartbeat(i); } catch (ActivityCompletionException e) { System.out.println( "** Activity - Canceling delivery activity for packet: " + packet.getId() + " with content: " + packet.getContent()); throw e; } } } @Override public String completeDelivery(Packet packet) { ActivityExecutionContext context = Activity.getExecutionContext(); System.out.println( "** Activity - Completing delivery for package: " + packet.getId() + " with content: " + packet.getContent()); for (int i = 0; i < 4; i++) { try { // Perform the heartbeat. Used to notify the workflow that activity execution is alive context.heartbeat(i); } catch (ActivityCompletionException e) { System.out.println( "** Activity - Canceling complete delivery activity for packet: " + packet.getId() + " with content: " + packet.getContent()); throw e; } } // For sample we just confirm return randomCompletionDeliveryResult(packet); } @Override public String compensateDelivery(Packet packet) { System.out.println( "** Activity - Compensating delivery for package: " + packet.getId() + " with content: " + packet.getContent()); sleep(1); return PacketUtils.COMPENSATION_COMPLETED; } /** * For this sample activity completion result can drive if 1. Delivery confirmation is completed, * in which case we complete delivery 2. Delivery confirmation is failed, in which case we run the * delivery again 3. Delivery confirmation is cancelled, in which case we want to cancel delivery * and perform "cleanup activity" Note that any delivery can cancel itself OR another delivery, so * for example Furniure delivery can cancel the Food delivery. For sample we have some specific * rules Which delivery can cancel which */ private String randomCompletionDeliveryResult(Packet packet) { Random random = new Random(); double randomValue = random.nextDouble(); if (randomValue < 0.10) { // 10% chance for delivery completion to be canceled int toCancelDelivery = determineCancelRules(packet); System.out.println( "** Activity - Delivery completion result for package: " + packet.getId() + " with content: " + packet.getContent() + ": " + "Cancelling delivery: " + toCancelDelivery); // send cancellation signal for packet to be canceled PacketDeliveryWorkflow packetWorkflow = client.newWorkflowStub( PacketDeliveryWorkflow.class, Activity.getExecutionContext().getInfo().getWorkflowId()); packetWorkflow.cancelDelivery(toCancelDelivery, "canceled from delivery " + packet.getId()); return PacketUtils.COMPLETION_CANCELLED; } if (randomValue < 0.20) { // 20% chance for delivery completion to fail System.out.println( "** Activity - Delivery completion result for package: " + packet.getId() + " with content: " + packet.getContent() + ": " + "Failed"); return PacketUtils.COMPLETION_FAILURE; } System.out.println( "** Activity - Delivery completion result for package: " + packet.getId() + " with content: " + packet.getContent() + ": " + "Successful"); return PacketUtils.COMPLETION_SUCCESS; } private void sleep(int seconds) { try { Thread.sleep(seconds * 1000L); } catch (Exception e) { System.out.println(e.getMessage()); } } /** * Sample rules for canceling different deliveries We just rotate the list 1-5 (packet ids) by * packet id and return first result */ private int determineCancelRules(Packet packet) { List list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5)); Collections.rotate(list, packet.getId()); System.out.println( "** Activity - Package delivery : " + packet.getId() + " canceling package delivery: " + list.get(0)); return list.get(0); } } ================================================ FILE: core/src/main/java/io/temporal/samples/packetdelivery/PacketDeliveryWorkflow.java ================================================ package io.temporal.samples.packetdelivery; import io.temporal.workflow.QueryMethod; import io.temporal.workflow.SignalMethod; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; import java.util.List; @WorkflowInterface public interface PacketDeliveryWorkflow { @WorkflowMethod String execute(); @SignalMethod void confirmDelivery(int deliveryId); @SignalMethod void cancelDelivery(int deliveryId, String reason); @QueryMethod List deliveryConfirmationPackets(); } ================================================ FILE: core/src/main/java/io/temporal/samples/packetdelivery/PacketDeliveryWorkflowImpl.java ================================================ package io.temporal.samples.packetdelivery; import io.temporal.activity.ActivityOptions; import io.temporal.workflow.Promise; import io.temporal.workflow.Workflow; import java.time.Duration; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.slf4j.Logger; public class PacketDeliveryWorkflowImpl implements PacketDeliveryWorkflow { private final Map packetDeliveries = new HashMap<>(); private final Logger logger = Workflow.getLogger(this.getClass().getName()); private final PacketDeliveryActivities activities = Workflow.newActivityStub( PacketDeliveryActivities.class, ActivityOptions.newBuilder() .setStartToCloseTimeout(Duration.ofSeconds(5)) .setHeartbeatTimeout(Duration.ofSeconds(2)) .build()); @Override public String execute() { List> packetsDelivered = new ArrayList<>(); // Step 1 - upload initial packets to deliver List initialPackets = activities.generatePackets(); // Step 2 - set up delivery processing for (Packet packet : initialPackets) { PacketDelivery delivery = new PacketDelivery(packet); packetDeliveries.put(packet.getId(), delivery); packetsDelivered.add(delivery.getDelivered()); } // Wait for all packet deliveries to complete Promise.allOf(packetsDelivered).get(); return "completed"; } @Override public void confirmDelivery(int deliveryId) { if (packetDeliveries.containsKey(deliveryId)) { packetDeliveries.get(deliveryId).confirmDelivery(); } } @Override public void cancelDelivery(int deliveryId, String reason) { if (packetDeliveries.containsKey(deliveryId)) { // Only makes sense to cancel if delivery is not done yet if (!packetDeliveries.get(deliveryId).getDelivered().isCompleted()) { logger.info("Sending cancellation for delivery : " + deliveryId + " and reason: " + reason); packetDeliveries.get(deliveryId).cancelDelivery(reason); } logger.info( "Bypassing sending cancellation for delivery : " + deliveryId + " and reason: " + reason + " because delivery already completed"); } } @Override public List deliveryConfirmationPackets() { List confirmationPackets = new ArrayList<>(); packetDeliveries .values() .forEach( p -> { if (p.isNeedDeliveryConfirmation()) { confirmationPackets.add(p.getPacket()); } }); return confirmationPackets; } } ================================================ FILE: core/src/main/java/io/temporal/samples/packetdelivery/PacketUtils.java ================================================ package io.temporal.samples.packetdelivery; public class PacketUtils { public static String COMPLETION_SUCCESS = "Delivery Completion Successful"; public static String COMPLETION_FAILURE = "Delivery Completion Failed"; public static String COMPLETION_CANCELLED = "Delivery Completion Cancelled"; public static String COMPENSATION_COMPLETED = "Delivery Compensation Completed"; } ================================================ FILE: core/src/main/java/io/temporal/samples/packetdelivery/README.md ================================================ # Async Package Delivery Sample This sample show how to run multiple "paths" of execution async within single workflow. Sample starts deliveries of 5 items in parallel. Each item performs an activity and then waits for a confirmation signal, then performs second activity. Workflow waits until all packets have been delivered. Each packet delivery path can choose to also "cancel" delivery of another item. This is done via signal and cancellation of the CancellationScope. ## Notes 1. In this sample we do not handle event history count and size partitioning via ContinueAsNew. It is assumed that the total number of paths and path lengths (in terms of activity executions) would not exceed it. For your use case you might need to add ContinueAsNew checks to deal with this situation. 2. Use this sample as all other ones as reference for your implementation. It was not tested on high scale so using it as-is without load testing is not recommended. ## Start the Sample: ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.packetdelivery.Starter ``` Run sample multiple times to see different scenarios (delivery failure and retry and delivery cancelation) There is a 10% chance delivery is going to be canceled and 20% chane it will fail. ================================================ FILE: core/src/main/java/io/temporal/samples/packetdelivery/Starter.java ================================================ package io.temporal.samples.packetdelivery; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowNotFoundException; import io.temporal.client.WorkflowOptions; import io.temporal.client.WorkflowStub; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import java.io.IOException; import java.util.Collections; import java.util.List; public class Starter { public static void main(String[] args) { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); WorkerFactory factory = WorkerFactory.newInstance(client); Worker worker = factory.newWorker("packet-delivery-taskqueue"); worker.registerWorkflowImplementationTypes(PacketDeliveryWorkflowImpl.class); worker.registerActivitiesImplementations(new PacketDeliveryActivitiesImpl(client)); factory.start(); PacketDeliveryWorkflow workflow = client.newWorkflowStub( PacketDeliveryWorkflow.class, WorkflowOptions.newBuilder() .setWorkflowId("packet-delivery-workflow") .setTaskQueue("packet-delivery-taskqueue") .build()); WorkflowClient.start(workflow::execute); // start completing package deliveries (send confirmations) // Query workflow for packets that need confirmation, confirm until none need confirmation any // more while (true) { sleep(3); List packets = workflow.deliveryConfirmationPackets(); if (packets.isEmpty()) { break; } // for "fun", reverse the list we get from delivery confirmation list Collections.reverse(packets); for (Packet p : packets) { try { workflow.confirmDelivery(p.getId()); } catch (WorkflowNotFoundException e) { // In some cases with cancellations happening, workflow could be completed by now // We just ignore and exit out of loop break; } } } // wait for workflow to complete String result = WorkflowStub.fromTyped(workflow).getResult(String.class); System.out.println("** Workflow Result: " + result); } private static void sleep(int seconds) { try { Thread.sleep(seconds * 1000L); } catch (Exception e) { System.out.println(e.getMessage()); } } } ================================================ FILE: core/src/main/java/io/temporal/samples/payloadconverter/cloudevents/CEWorkflow.java ================================================ package io.temporal.samples.payloadconverter.cloudevents; import io.cloudevents.CloudEvent; import io.temporal.workflow.QueryMethod; import io.temporal.workflow.SignalMethod; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; @WorkflowInterface public interface CEWorkflow { @WorkflowMethod void exec(CloudEvent cloudEvent); @SignalMethod void addEvent(CloudEvent cloudEvent); @QueryMethod CloudEvent getLastEvent(); } ================================================ FILE: core/src/main/java/io/temporal/samples/payloadconverter/cloudevents/CEWorkflowImpl.java ================================================ package io.temporal.samples.payloadconverter.cloudevents; import io.cloudevents.CloudEvent; import io.temporal.workflow.Workflow; import java.util.ArrayList; import java.util.List; public class CEWorkflowImpl implements CEWorkflow { private List eventList = new ArrayList<>(); @Override public void exec(CloudEvent cloudEvent) { eventList.add(cloudEvent); Workflow.await(() -> eventList.size() == 10); } @Override public void addEvent(CloudEvent cloudEvent) { eventList.add(cloudEvent); } @Override public CloudEvent getLastEvent() { return eventList.get(eventList.size() - 1); } } ================================================ FILE: core/src/main/java/io/temporal/samples/payloadconverter/cloudevents/CloudEventsPayloadConverter.java ================================================ package io.temporal.samples.payloadconverter.cloudevents; import com.google.protobuf.ByteString; import io.cloudevents.CloudEvent; import io.cloudevents.core.format.EventFormat; import io.cloudevents.core.format.EventSerializationException; import io.cloudevents.core.provider.EventFormatProvider; import io.cloudevents.jackson.JsonFormat; import io.temporal.api.common.v1.Payload; import io.temporal.common.converter.DataConverterException; import io.temporal.common.converter.PayloadConverter; import java.lang.reflect.Type; import java.nio.charset.StandardCharsets; import java.util.Optional; /** Payload converter specific to CloudEvents format */ public class CloudEventsPayloadConverter implements PayloadConverter { private EventFormat CEFormat = EventFormatProvider.getInstance().resolveFormat(JsonFormat.CONTENT_TYPE); @Override public String getEncodingType() { return "json/plain"; } @Override public Optional toData(Object value) throws DataConverterException { try { CloudEvent cloudEvent = (CloudEvent) value; byte[] serialized = CEFormat.serialize(cloudEvent); return Optional.of( Payload.newBuilder() .putMetadata( "encoding", ByteString.copyFrom(getEncodingType(), StandardCharsets.UTF_8)) .setData(ByteString.copyFrom(serialized)) .build()); } catch (EventSerializationException | ClassCastException e) { throw new DataConverterException(e); } } @Override public T fromData(Payload content, Class valueClass, Type valueType) throws DataConverterException { try { return (T) CEFormat.deserialize(content.getData().toByteArray()); } catch (ClassCastException e) { throw new DataConverterException(e); } } } ================================================ FILE: core/src/main/java/io/temporal/samples/payloadconverter/cloudevents/README.md ================================================ # Custom Payload Converter (CloudEvents) The sample demonstrates creating and setting a custom Payload Converter. ## Running 1. Start Temporal Server with "default" namespace enabled. For example using local Docker: ```bash git clone https://github.com/temporalio/docker-compose.git cd docker-compose docker-compose up ``` 2. Run the following command to start the sample: ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.payloadconverter.cloudevents.Starter ``` ================================================ FILE: core/src/main/java/io/temporal/samples/payloadconverter/cloudevents/Starter.java ================================================ package io.temporal.samples.payloadconverter.cloudevents; import io.cloudevents.CloudEvent; import io.cloudevents.core.builder.CloudEventBuilder; import io.cloudevents.jackson.JsonCloudEventData; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowClientOptions; import io.temporal.client.WorkflowOptions; import io.temporal.common.converter.DefaultDataConverter; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import java.io.IOException; import java.net.URI; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; public class Starter { private static final String TASK_QUEUE = "CloudEventsConverterQueue"; public static void main(String[] args) { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); // Add CloudEventsPayloadConverter // It has the same encoding type as JacksonJsonPayloadConverter DefaultDataConverter ddc = DefaultDataConverter.newDefaultInstance() .withPayloadConverterOverrides(new CloudEventsPayloadConverter()); WorkflowClientOptions workflowClientOptions = WorkflowClientOptions.newBuilder().setDataConverter(ddc).build(); WorkflowClient client = WorkflowClient.newInstance(service, workflowClientOptions); WorkerFactory factory = WorkerFactory.newInstance(client); Worker worker = factory.newWorker(TASK_QUEUE); worker.registerWorkflowImplementationTypes(CEWorkflowImpl.class); factory.start(); WorkflowOptions newCustomerWorkflowOptions = WorkflowOptions.newBuilder().setTaskQueue(TASK_QUEUE).build(); CEWorkflow workflow = client.newWorkflowStub(CEWorkflow.class, newCustomerWorkflowOptions); // Create 10 cloud events List cloudEventList = new ArrayList<>(); for (int i = 0; i < 10; i++) { cloudEventList.add( CloudEventBuilder.v1() .withId(String.valueOf(100 + i)) .withType("example.demo") .withSource(URI.create("http://temporal.io")) .withData( "application/json", ("{\n" + "\"greeting\": \"hello " + i + "\"\n" + "}") .getBytes(Charset.defaultCharset())) .build()); } WorkflowClient.start(workflow::exec, cloudEventList.get(0)); // Send signals (cloud event data) for (int j = 1; j < 10; j++) { workflow.addEvent(cloudEventList.get(j)); } // Get the CE result and get its data (JSON) String result = ((JsonCloudEventData) workflow.getLastEvent().getData()).getNode().get("greeting").asText(); System.out.println("Last event body: " + result); System.exit(0); } } ================================================ FILE: core/src/main/java/io/temporal/samples/payloadconverter/crypto/CryptoWorkflow.java ================================================ package io.temporal.samples.payloadconverter.crypto; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; @WorkflowInterface public interface CryptoWorkflow { @WorkflowMethod MyCustomer exec(MyCustomer customer); } ================================================ FILE: core/src/main/java/io/temporal/samples/payloadconverter/crypto/CryptoWorkflowImpl.java ================================================ package io.temporal.samples.payloadconverter.crypto; public class CryptoWorkflowImpl implements CryptoWorkflow { @Override public MyCustomer exec(MyCustomer customer) { // if > 18 "approve" otherwise deny if (customer.getAge() > 18) { customer.setApproved(true); } else { customer.setApproved(false); } return customer; } } ================================================ FILE: core/src/main/java/io/temporal/samples/payloadconverter/crypto/MyCustomer.java ================================================ package io.temporal.samples.payloadconverter.crypto; import com.codingrodent.jackson.crypto.Encrypt; public class MyCustomer { private String name; private int age; private boolean approved; public MyCustomer() {} public MyCustomer(String name, int age) { this.name = name; this.age = age; } @Encrypt public String getName() { return name; } public void setName(String name) { this.name = name; } @Encrypt public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Encrypt public boolean isApproved() { return approved; } public void setApproved(boolean approved) { this.approved = approved; } } ================================================ FILE: core/src/main/java/io/temporal/samples/payloadconverter/crypto/README.md ================================================ # Custom Payload Converter (Crypto converter) The sample demonstrates how you can override the default Json Converter to encrypt/decrypt payloads using [jackson-json-crypto](https://github.com/codesqueak/jackson-json-crypto). ## Running 1. Start Temporal Server with "default" namespace enabled. For example using local Docker: ```bash git clone https://github.com/temporalio/docker-compose.git cd docker-compose docker-compose up ``` 2. Run the following command to start the sample: ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.payloadconverter.crypto.Starter ``` 3. View the history in [Temporal Web UI](http://localhost:8088/) You will see your workflow inputs fields that were set to be encrypted in the MyCustomer model class are indeed encrypted, for example: ```json [ { "name": { "salt": "uZnKfjmFzwYsH6ncZBVgvvmAPTw=", "iv": "0nK++kg8IgtOJFs+gQ/U0A==", "value": "cvXFWXfU8RFKdlWgjrHaog==" }, "age": { "salt": "uZnKfjmFzwYsH6ncZBVgvvmAPTw=", "iv": "0nK++kg8IgtOJFs+gQ/U0A==", "value": "OFA/XDiwep153xZHOECqJA==" }, "approved": { "salt": "uZnKfjmFzwYsH6ncZBVgvvmAPTw=", "iv": "0nK++kg8IgtOJFs+gQ/U0A==", "value": "Tm23RaHHKz2wM56G2Bn6Vw==" } } ] ``` ================================================ FILE: core/src/main/java/io/temporal/samples/payloadconverter/crypto/Starter.java ================================================ package io.temporal.samples.payloadconverter.crypto; import com.codingrodent.jackson.crypto.CryptoModule; import com.codingrodent.jackson.crypto.EncryptionService; import com.codingrodent.jackson.crypto.PasswordCryptoContext; import com.fasterxml.jackson.databind.ObjectMapper; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowClientOptions; import io.temporal.client.WorkflowOptions; import io.temporal.common.converter.DefaultDataConverter; import io.temporal.common.converter.JacksonJsonPayloadConverter; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import java.io.IOException; public class Starter { private static final String TASK_QUEUE = "CryptoConverterQueue"; private static final String encryptDecryptPassword = "encryptDecryptPassword"; public static void main(String[] args) { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); // Set crypto data converter in client options WorkflowClient client = WorkflowClient.newInstance( service, WorkflowClientOptions.newBuilder() .setDataConverter( DefaultDataConverter.newDefaultInstance() .withPayloadConverterOverrides(getCryptoJacksonJsonPayloadConverter())) .build()); // Create worker and start Worker factory createWorker(client); // Create typed workflow stub CryptoWorkflow workflow = client.newWorkflowStub( CryptoWorkflow.class, WorkflowOptions.newBuilder() .setWorkflowId("cryptoWorkflow") .setTaskQueue(TASK_QUEUE) .build()); // Start workflow exec and wait for results (sync) MyCustomer customer = workflow.exec(new MyCustomer("John", 22)); System.out.println("Approved: " + customer.isApproved()); System.exit(0); } private static JacksonJsonPayloadConverter getCryptoJacksonJsonPayloadConverter() { ObjectMapper objectMapper = new ObjectMapper(); // Create the Crypto Context (password based) PasswordCryptoContext cryptoContext = new PasswordCryptoContext( encryptDecryptPassword, // decrypt password encryptDecryptPassword, // encrypt password PasswordCryptoContext.CIPHER_NAME, // cipher name PasswordCryptoContext.KEY_NAME); // key generator names EncryptionService encryptionService = new EncryptionService(objectMapper, cryptoContext); objectMapper.registerModule(new CryptoModule().addEncryptionService(encryptionService)); return new JacksonJsonPayloadConverter(objectMapper); } private static void createWorker(WorkflowClient client) { WorkerFactory factory = WorkerFactory.newInstance(client); Worker worker = factory.newWorker(TASK_QUEUE); worker.registerWorkflowImplementationTypes(CryptoWorkflowImpl.class); factory.start(); } } ================================================ FILE: core/src/main/java/io/temporal/samples/peractivityoptions/FailingActivities.java ================================================ package io.temporal.samples.peractivityoptions; import io.temporal.activity.ActivityInterface; @ActivityInterface public interface FailingActivities { void activityTypeA(); void activityTypeB(); } ================================================ FILE: core/src/main/java/io/temporal/samples/peractivityoptions/FailingActivitiesImpl.java ================================================ package io.temporal.samples.peractivityoptions; import io.temporal.activity.Activity; public class FailingActivitiesImpl implements FailingActivities { @Override public void activityTypeA() { // Get the activity type String type = Activity.getExecutionContext().getInfo().getActivityType(); // Get the retry attempt int attempt = Activity.getExecutionContext().getInfo().getAttempt(); // Wrap checked exception and throw throw Activity.wrap( new NullPointerException("Activity type: " + type + " attempt times: " + attempt)); } @Override public void activityTypeB() { // Get the activity type String type = Activity.getExecutionContext().getInfo().getActivityType(); // Get the retry attempt int attempt = Activity.getExecutionContext().getInfo().getAttempt(); // Wrap checked exception and throw throw Activity.wrap( new NullPointerException("Activity type: " + type + " attempt times: " + attempt)); } } ================================================ FILE: core/src/main/java/io/temporal/samples/peractivityoptions/PerActivityOptionsWorkflow.java ================================================ package io.temporal.samples.peractivityoptions; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; @WorkflowInterface public interface PerActivityOptionsWorkflow { @WorkflowMethod void execute(); } ================================================ FILE: core/src/main/java/io/temporal/samples/peractivityoptions/PerActivityOptionsWorkflowImpl.java ================================================ package io.temporal.samples.peractivityoptions; import io.temporal.failure.ActivityFailure; import io.temporal.failure.ApplicationFailure; import io.temporal.workflow.Workflow; import org.slf4j.Logger; public class PerActivityOptionsWorkflowImpl implements PerActivityOptionsWorkflow { // Create activity stub that will inherit activity options set in WorkflowImplementationOptions // Note that you can overwrite the per-activity options by setting specific ActivityOptions // when creating activity stub here (Workflow.newActivityStub(FailingActivities.class, options) private FailingActivities activities = Workflow.newActivityStub(FailingActivities.class); private Logger logger = Workflow.getLogger(this.getClass().getName()); @Override public void execute() { // Execute first activity try { activities.activityTypeA(); } catch (ActivityFailure af) { // Activity invocations always throw ActivityFailure // Our activity was retried up to its set setStartToCloseTimeout // We exhausted our retries so cause of our failure is ApplicationFailure // From ApplicationFailure we can get our original NPE message logger.info("ActivityFailure cause: " + af.getCause().getClass().getName()); logger.info("ApplicationFailure type: " + ((ApplicationFailure) af.getCause()).getType()); // Original message should include a retry attempt number > 1 logger.info( "Application Failure orig message: " + ((ApplicationFailure) af.getCause()).getOriginalMessage()); } // Execute second activity try { activities.activityTypeB(); } catch (ActivityFailure af) { logger.info("ActivityFailure cause: " + af.getCause().getClass().getName()); logger.info("ApplicationFailure type: " + ((ApplicationFailure) af.getCause()).getType()); // Original message should include a retry attempt number == 1 since we threw the doNotRetry // NPE // Set in the per activity type options logger.info( "Application Failure orig message: " + ((ApplicationFailure) af.getCause()).getOriginalMessage()); } } } ================================================ FILE: core/src/main/java/io/temporal/samples/peractivityoptions/README.md ================================================ # Per Activity Type Options Sample This sample shows how to set per Activity type options via WorkflowImplementationOptions ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.peractivityoptions.Starter ``` ================================================ FILE: core/src/main/java/io/temporal/samples/peractivityoptions/Starter.java ================================================ package io.temporal.samples.peractivityoptions; import com.google.common.collect.ImmutableMap; import io.temporal.activity.ActivityOptions; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.common.RetryOptions; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import io.temporal.worker.WorkflowImplementationOptions; import java.io.IOException; import java.time.Duration; public class Starter { public static final String TASK_QUEUE = "perActivityTaskQueue"; public static void main(String[] args) { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); WorkerFactory factory = WorkerFactory.newInstance(client); // Create Worker Worker worker = factory.newWorker(TASK_QUEUE); // Register workflow impl and set the per-activity options WorkflowImplementationOptions options = WorkflowImplementationOptions.newBuilder() // setActivityOptions allows you to set different ActivityOption per activity type // By default activity type is the name of activity method (with first letter upper // cased) .setActivityOptions( ImmutableMap.of( "ActivityTypeA", ActivityOptions.newBuilder() // Set activity exec timeout (including retries) .setScheduleToCloseTimeout(Duration.ofSeconds(5)) // Set activity type specific retries if needed .build(), "ActivityTypeB", ActivityOptions.newBuilder() // Set activity exec timeout (single run) .setStartToCloseTimeout(Duration.ofSeconds(2)) .setRetryOptions( RetryOptions.newBuilder() // ActivityTypeB activity type shouldn't retry on NPE .setDoNotRetry(NullPointerException.class.getName()) .build()) .build())) .build(); // Register our workflow impl and give the per-activity options // Note you can register multiple workflow impls with worker using these activity options worker.registerWorkflowImplementationTypes(options, PerActivityOptionsWorkflowImpl.class); // Register activity impl with worker worker.registerActivitiesImplementations(new FailingActivitiesImpl()); factory.start(); // Create typed workflow stub PerActivityOptionsWorkflow workflow = client.newWorkflowStub( PerActivityOptionsWorkflow.class, WorkflowOptions.newBuilder() // set business level id .setWorkflowId("PerActivityOptionsWorkflow") // set same task queue as our worker .setTaskQueue(TASK_QUEUE) .build()); // Call our workflow method sync (wait for results) workflow.execute(); System.exit(0); } } ================================================ FILE: core/src/main/java/io/temporal/samples/polling/PollingActivities.java ================================================ package io.temporal.samples.polling; import io.temporal.activity.ActivityInterface; @ActivityInterface public interface PollingActivities { String doPoll(); } ================================================ FILE: core/src/main/java/io/temporal/samples/polling/PollingWorkflow.java ================================================ package io.temporal.samples.polling; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; @WorkflowInterface public interface PollingWorkflow { @WorkflowMethod String exec(); } ================================================ FILE: core/src/main/java/io/temporal/samples/polling/README.md ================================================ # Polling These samples show three different best practices for polling. 1. [Frequently Polling Activity](frequent/README.md) 2. [Infrequently Polling Activity](infrequent/README.md) 3. [Periodic Polling of a sequence of activities](periodicsequence/README.md) The samples are based on [this](https://community.temporal.io/t/what-is-the-best-practice-for-a-polling-activity/328/2) community forum thread. ================================================ FILE: core/src/main/java/io/temporal/samples/polling/TestService.java ================================================ package io.temporal.samples.polling; import java.util.concurrent.ThreadLocalRandom; /** * Test service that we want to poll. It simulates a service being down and then returning a result * after 5 attempts */ public class TestService { private int tryAttempt = 0; private int errorAttempts = 5; // default to 5 attempts before returning result private boolean doRetryAfter = false; private int minRetryAfter = 1; private int maxRetryAfter = 3; public TestService() {} public TestService(int errorAttempts) { this.errorAttempts = errorAttempts; } public TestService(int errorAttempts, boolean doRetryAfter) { this.errorAttempts = errorAttempts; this.doRetryAfter = doRetryAfter; } public String getServiceResult() throws TestServiceException { tryAttempt++; if (tryAttempt % errorAttempts == 0) { return "OK"; } else { if (!doRetryAfter) { throw new TestServiceException("Service is down"); } else { throw new TestServiceException( "Service is down", ThreadLocalRandom.current().nextInt(minRetryAfter, maxRetryAfter + 1)); } } } public static class TestServiceException extends Exception { private int retryAfterInMinutes = 1; public TestServiceException(String message) { super(message); } public TestServiceException(String message, int retryAfterInMinutes) { super(message); this.retryAfterInMinutes = retryAfterInMinutes; } public int getRetryAfterInMinutes() { return retryAfterInMinutes; } } } ================================================ FILE: core/src/main/java/io/temporal/samples/polling/frequent/FrequentPollingActivityImpl.java ================================================ package io.temporal.samples.polling.frequent; import io.temporal.activity.Activity; import io.temporal.activity.ActivityExecutionContext; import io.temporal.client.ActivityCompletionException; import io.temporal.samples.polling.PollingActivities; import io.temporal.samples.polling.TestService; import java.util.concurrent.TimeUnit; public class FrequentPollingActivityImpl implements PollingActivities { private final TestService service; private static final int POLL_DURATION_SECONDS = 1; public FrequentPollingActivityImpl(TestService service) { this.service = service; } @Override public String doPoll() { ActivityExecutionContext context = Activity.getExecutionContext(); // Here we implement our polling inside the activity impl while (true) { try { return service.getServiceResult(); } catch (TestService.TestServiceException e) { // service "down" we can log } // heart beat and sleep for the poll duration try { context.heartbeat(null); } catch (ActivityCompletionException e) { // activity was either cancelled or workflow was completed or worker shut down throw e; } sleep(POLL_DURATION_SECONDS); } } private void sleep(int seconds) { try { Thread.sleep(TimeUnit.SECONDS.toMillis(seconds)); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } } } ================================================ FILE: core/src/main/java/io/temporal/samples/polling/frequent/FrequentPollingStarter.java ================================================ package io.temporal.samples.polling.frequent; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.samples.polling.PollingWorkflow; import io.temporal.samples.polling.TestService; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import java.io.IOException; public class FrequentPollingStarter { private static WorkflowServiceStubs service; private static WorkflowClient client; static { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); } private static final String taskQueue = "pollingSampleQueue"; private static final String workflowId = "FrequentPollingSampleWorkflow"; public static void main(String[] args) { // Create our worker and register workflow and activities createWorker(); // Create typed workflow stub and start execution (sync, wait for results) PollingWorkflow workflow = client.newWorkflowStub( PollingWorkflow.class, WorkflowOptions.newBuilder().setTaskQueue(taskQueue).setWorkflowId(workflowId).build()); String result = workflow.exec(); System.out.println("Result: " + result); System.exit(0); } private static void createWorker() { WorkerFactory workerFactory = WorkerFactory.newInstance(client); Worker worker = workerFactory.newWorker(taskQueue); // Register workflow and activities worker.registerWorkflowImplementationTypes(FrequentPollingWorkflowImpl.class); worker.registerActivitiesImplementations(new FrequentPollingActivityImpl(new TestService())); workerFactory.start(); } } ================================================ FILE: core/src/main/java/io/temporal/samples/polling/frequent/FrequentPollingWorkflowImpl.java ================================================ package io.temporal.samples.polling.frequent; import io.temporal.activity.ActivityOptions; import io.temporal.samples.polling.PollingActivities; import io.temporal.samples.polling.PollingWorkflow; import io.temporal.workflow.Workflow; import java.time.Duration; public class FrequentPollingWorkflowImpl implements PollingWorkflow { @Override public String exec() { /* * Frequent polling (1 second or faster) should be done inside the activity itself. Note that * the activity has to heart beat on each iteration. Note that we need to set our * HeartbeatTimeout in ActivityOptions shorter than the StartToClose timeout. You can use an * appropriate activity retry policy for your activity. */ ActivityOptions options = ActivityOptions.newBuilder() // Set activity StartToClose timeout (single activity exec), does not include retries .setStartToCloseTimeout(Duration.ofSeconds(60)) .setHeartbeatTimeout(Duration.ofSeconds(2)) // For sample we just use the default retry policy (do not set explicitly) .build(); // create our activities stub and start activity execution PollingActivities activities = Workflow.newActivityStub(PollingActivities.class, options); return activities.doPoll(); } } ================================================ FILE: core/src/main/java/io/temporal/samples/polling/frequent/README.md ================================================ ## Frequent polling This sample shows how we can implement frequent polling (1 second or faster) inside our Activity. The implementation is a loop that polls our service and then sleeps for the poll interval (1 second in the sample). To ensure that polling activity is restarted in a timely manner, we make sure that it heartbeats on every iteration. Note that heartbeating only works if we set the HeartBeatTimeout to a shorter value than the activity StartToClose timeout. To run this sample: ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.polling.frequent.FrequentPollingStarter ``` ================================================ FILE: core/src/main/java/io/temporal/samples/polling/infrequent/InfrequentPollingActivityImpl.java ================================================ package io.temporal.samples.polling.infrequent; import io.temporal.failure.ApplicationErrorCategory; import io.temporal.failure.ApplicationFailure; import io.temporal.samples.polling.PollingActivities; import io.temporal.samples.polling.TestService; public class InfrequentPollingActivityImpl implements PollingActivities { private final TestService service; public InfrequentPollingActivityImpl(TestService service) { this.service = service; } @Override public String doPoll() { try { return service.getServiceResult(); } catch (TestService.TestServiceException e) { // We want to rethrow the service exception so we can poll via activity retries throw ApplicationFailure.newBuilder() .setMessage(e.getMessage()) .setType(e.getClass().getName()) .setCause(e) // This failure is expected so we set it as benign to avoid excessive logging .setCategory(ApplicationErrorCategory.BENIGN) .build(); } } } ================================================ FILE: core/src/main/java/io/temporal/samples/polling/infrequent/InfrequentPollingStarter.java ================================================ package io.temporal.samples.polling.infrequent; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.samples.polling.PollingWorkflow; import io.temporal.samples.polling.TestService; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import java.io.IOException; public class InfrequentPollingStarter { private static WorkflowServiceStubs service; private static WorkflowClient client; static { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); } private static final String taskQueue = "pollingSampleQueue"; private static final String workflowId = "InfrequentPollingSampleWorkflow"; public static void main(String[] args) { // Create our worker and register workflow and activities createWorker(); // Create typed workflow stub and start execution (sync, wait for results) PollingWorkflow workflow = client.newWorkflowStub( PollingWorkflow.class, WorkflowOptions.newBuilder().setTaskQueue(taskQueue).setWorkflowId(workflowId).build()); String result = workflow.exec(); System.out.println("Result: " + result); System.exit(0); } private static void createWorker() { WorkerFactory workerFactory = WorkerFactory.newInstance(client); Worker worker = workerFactory.newWorker(taskQueue); // Register workflow and activities worker.registerWorkflowImplementationTypes(InfrequentPollingWorkflowImpl.class); worker.registerActivitiesImplementations(new InfrequentPollingActivityImpl(new TestService())); workerFactory.start(); } } ================================================ FILE: core/src/main/java/io/temporal/samples/polling/infrequent/InfrequentPollingWorkflowImpl.java ================================================ package io.temporal.samples.polling.infrequent; import io.temporal.activity.ActivityOptions; import io.temporal.common.RetryOptions; import io.temporal.samples.polling.PollingActivities; import io.temporal.samples.polling.PollingWorkflow; import io.temporal.workflow.Workflow; import java.time.Duration; public class InfrequentPollingWorkflowImpl implements PollingWorkflow { @Override public String exec() { /* * Infrequent polling via activity can be implemented via activity retries. For this sample we * want to poll the test service every 60 seconds. Here we: * *

    *
  1. Set RetryPolicy backoff coefficient of 1 *
  2. Set initial interval to the poll frequency (since coefficient is 1, same interval will * be used for all retries) *
* *

With this in case our test service is "down" we can fail our activity and it will be * retried based on our 60 second retry interval until poll is successful and we can return a * result from the activity. */ ActivityOptions options = ActivityOptions.newBuilder() // Set activity StartToClose timeout (single activity exec), does not include retries .setStartToCloseTimeout(Duration.ofSeconds(2)) .setRetryOptions( RetryOptions.newBuilder() .setBackoffCoefficient(1) .setInitialInterval(Duration.ofSeconds(60)) .build()) .build(); // create our activities stub and start activity execution PollingActivities activities = Workflow.newActivityStub(PollingActivities.class, options); return activities.doPoll(); } } ================================================ FILE: core/src/main/java/io/temporal/samples/polling/infrequent/README.md ================================================ ## Infrequent polling This sample shows how we can use Activity retries for infrequent polling of a third-party service (for example via REST). This method can be used for infrequent polls of one minute or slower. We utilize activity retries for this option, setting Retries options: * setBackoffCoefficient to 1 * setInitialInterval to the polling interval (in this sample set to 60 seconds) This will allow us to retry our Activity exactly on the set interval. To run this sample: ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.polling.infrequent.InfrequentPollingStarter ``` Since our test service simulates it being "down" for 4 polling attempts and then returns "OK" on the 5th poll attempt, our Workflow is going to perform 4 activity retries with a 60 second poll interval, and then return the service result on the successful 5th attempt. Note that individual Activity retries are not recorded in Workflow History, so we this approach we can poll for a very long time without affecting the history size. ================================================ FILE: core/src/main/java/io/temporal/samples/polling/infrequentwithretryafter/InfrequentPollingWithRetryAfterActivityImpl.java ================================================ package io.temporal.samples.polling.infrequentwithretryafter; import io.temporal.activity.Activity; import io.temporal.failure.ApplicationErrorCategory; import io.temporal.failure.ApplicationFailure; import io.temporal.samples.polling.PollingActivities; import io.temporal.samples.polling.TestService; import java.time.Duration; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; public class InfrequentPollingWithRetryAfterActivityImpl implements PollingActivities { private final TestService service; final DateTimeFormatter ISO_FORMATTER = DateTimeFormatter.ISO_DATE_TIME; public InfrequentPollingWithRetryAfterActivityImpl(TestService service) { this.service = service; } @Override public String doPoll() { System.out.println( "Attempt: " + Activity.getExecutionContext().getInfo().getAttempt() + " Poll time: " + LocalDateTime.now(ZoneId.systemDefault()).format(ISO_FORMATTER)); try { return service.getServiceResult(); } catch (TestService.TestServiceException e) { // we throw application failure that includes cause // which is the test service exception // and delay which is the interval to next retry based on test service retry-after directive System.out.println("Activity next retry in: " + e.getRetryAfterInMinutes() + " minutes"); throw ApplicationFailure.newBuilder() .setMessage(e.getMessage()) .setType(e.getClass().getName()) .setCause(e) // Here we set the next retry interval based on Retry-After duration given to us by our // service .setNextRetryDelay(Duration.ofMinutes(e.getRetryAfterInMinutes())) // This failure is expected so we set it as benign to avoid excessive logging .setCategory(ApplicationErrorCategory.BENIGN) .build(); } } } ================================================ FILE: core/src/main/java/io/temporal/samples/polling/infrequentwithretryafter/InfrequentPollingWithRetryAfterStarter.java ================================================ package io.temporal.samples.polling.infrequentwithretryafter; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.samples.polling.PollingWorkflow; import io.temporal.samples.polling.TestService; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import java.io.IOException; public class InfrequentPollingWithRetryAfterStarter { private static WorkflowServiceStubs service; private static WorkflowClient client; static { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); } private static final String taskQueue = "pollingSampleQueue"; private static final String workflowId = "InfrequentPollingWithRetryAfterWorkflow"; public static void main(String[] args) { // Create our worker and register workflow and activities createWorker(); // Create typed workflow stub and start execution (sync, wait for results) PollingWorkflow workflow = client.newWorkflowStub( PollingWorkflow.class, WorkflowOptions.newBuilder().setTaskQueue(taskQueue).setWorkflowId(workflowId).build()); String result = workflow.exec(); System.out.println("Result: " + result); System.exit(0); } private static void createWorker() { WorkerFactory workerFactory = WorkerFactory.newInstance(client); Worker worker = workerFactory.newWorker(taskQueue); // Register workflow and activities worker.registerWorkflowImplementationTypes(InfrequentPollingWithRetryAfterWorkflowImpl.class); worker.registerActivitiesImplementations( new InfrequentPollingWithRetryAfterActivityImpl(new TestService(4, true))); workerFactory.start(); } } ================================================ FILE: core/src/main/java/io/temporal/samples/polling/infrequentwithretryafter/InfrequentPollingWithRetryAfterWorkflowImpl.java ================================================ package io.temporal.samples.polling.infrequentwithretryafter; import io.temporal.activity.ActivityOptions; import io.temporal.common.RetryOptions; import io.temporal.samples.polling.PollingActivities; import io.temporal.samples.polling.PollingWorkflow; import io.temporal.workflow.Workflow; import java.time.Duration; public class InfrequentPollingWithRetryAfterWorkflowImpl implements PollingWorkflow { @Override public String exec() { /* * Infrequent polling via activity can be implemented via activity retries. For this sample we * want to poll the test service initially 60 seconds. After that we want to retry it based on * the Retry-After directive from the downstream servie we are invoking from the activity. * *

    *
  1. Set RetryPolicy backoff coefficient of 1 *
  2. Set initial interval to the poll frequency (since coefficient is 1, same interval will * be used as default retry attempt) *
*/ ActivityOptions options = ActivityOptions.newBuilder() // Set activity StartToClose timeout (single activity exec), does not include retries .setStartToCloseTimeout(Duration.ofSeconds(2)) .setRetryOptions( RetryOptions.newBuilder() .setBackoffCoefficient(1) // note we don't set initial interval here .build()) .build(); // create our activities stub and start activity execution PollingActivities activities = Workflow.newActivityStub(PollingActivities.class, options); return activities.doPoll(); } } ================================================ FILE: core/src/main/java/io/temporal/samples/polling/infrequentwithretryafter/README.md ================================================ ## Infrequent polling with Service returning Retry-After time * Note - for this sample to work you should use Temporal Service version 1.24.2 or Temporal Cloud * Note - for sample we assume that our downstream service returns a retry-after duration that is longer than 1 minute This sample shows how we can use Activity retries for infrequent polling of a third-party service (for example via REST). This method can be used for infrequent polls of one minute or slower. For this sample our test service also returns a Retry-After time (typically its done via response header but for sample its just done in service exception) We utilize activity retries for this option, setting Retries options: * setBackoffCoefficient to 1 * here we do not set initial interval as its changed by the Retry-After duration sent to us by the downstream service our activity invokes * This will allow us to retry our Activity based on the Retry-After duration our downstream service tells us. To run this sample: ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.polling.infrequent.InfrequentPollingWithRetryAfterStarter ``` Since our test service simulates it being "down" for 3 polling attempts and then returns "OK" on the 4th poll attempt, our Workflow is going to perform 3 activity retries with different intervals based on the Retry-After time our serviec gives us, and then return the service result on the successful 4th attempt. Note that individual Activity retries are not recorded in Workflow History, so we this approach we can poll for a very long time without affecting the history size. ### Sample result If you run this sample you can see following in the logs for example: ``` Attempt: 1 Poll time: 2024-07-14T22:03:03.750506 Activity next retry in: 2 minutes Attempt: 2 Poll time: 2024-07-14T22:05:03.780079 Activity next retry in: 3 minutes Attempt: 3 Poll time: 2024-07-14T22:08:03.799703 Activity next retry in: 1 minutes Attempt: 4 Poll time: 2024-07-14T22:09:03.817751 Result: OK ``` ================================================ FILE: core/src/main/java/io/temporal/samples/polling/periodicsequence/PeriodicPollingActivityImpl.java ================================================ package io.temporal.samples.polling.periodicsequence; import io.temporal.activity.Activity; import io.temporal.samples.polling.PollingActivities; import io.temporal.samples.polling.TestService; public class PeriodicPollingActivityImpl implements PollingActivities { private TestService service; public PeriodicPollingActivityImpl(TestService service) { this.service = service; } @Override public String doPoll() { try { return service.getServiceResult(); } catch (TestService.TestServiceException e) { // We want to rethrow the service exception so we can poll via activity retries throw Activity.wrap(e); } } } ================================================ FILE: core/src/main/java/io/temporal/samples/polling/periodicsequence/PeriodicPollingChildWorkflowImpl.java ================================================ package io.temporal.samples.polling.periodicsequence; import io.temporal.activity.ActivityOptions; import io.temporal.common.RetryOptions; import io.temporal.failure.ActivityFailure; import io.temporal.samples.polling.PollingActivities; import io.temporal.workflow.Workflow; import java.time.Duration; public class PeriodicPollingChildWorkflowImpl implements PollingChildWorkflow { private int singleWorkflowPollAttempts = 10; @Override public String exec(int pollingIntervalInSeconds) { PollingActivities activities = Workflow.newActivityStub( PollingActivities.class, ActivityOptions.newBuilder() .setStartToCloseTimeout(Duration.ofSeconds(4)) // Explicitly disable default retries for activities // as activity retries are handled with business logic in this case .setRetryOptions(RetryOptions.newBuilder().setMaximumAttempts(1).build()) .build()); for (int i = 0; i < singleWorkflowPollAttempts; i++) { // Here we would invoke a sequence of activities // For sample we just use a single one try { return activities.doPoll(); } catch (ActivityFailure e) { // Log error after retries exhausted } // Sleep for a second Workflow.sleep(Duration.ofSeconds(1)); } // Request that the new child workflow run is invoked PollingChildWorkflow continueAsNew = Workflow.newContinueAsNewStub(PollingChildWorkflow.class); continueAsNew.exec(pollingIntervalInSeconds); // unreachable return null; } } ================================================ FILE: core/src/main/java/io/temporal/samples/polling/periodicsequence/PeriodicPollingStarter.java ================================================ package io.temporal.samples.polling.periodicsequence; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.samples.polling.PollingWorkflow; import io.temporal.samples.polling.TestService; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import java.io.IOException; public class PeriodicPollingStarter { private static WorkflowServiceStubs service; private static WorkflowClient client; static { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); } private static final String taskQueue = "pollingSampleQueue"; private static final String workflowId = "PeriodicPollingSampleWorkflow"; public static void main(String[] args) { // Create our worker and register workflow and activities createWorker(); // Create typed workflow stub and start execution (sync, wait for results) PollingWorkflow workflow = client.newWorkflowStub( PollingWorkflow.class, WorkflowOptions.newBuilder().setTaskQueue(taskQueue).setWorkflowId(workflowId).build()); String result = workflow.exec(); System.out.println("Result: " + result); System.exit(0); } private static void createWorker() { WorkerFactory workerFactory = WorkerFactory.newInstance(client); Worker worker = workerFactory.newWorker(taskQueue); // Register workflow and activities worker.registerWorkflowImplementationTypes( PeriodicPollingWorkflowImpl.class, PeriodicPollingChildWorkflowImpl.class); worker.registerActivitiesImplementations(new PeriodicPollingActivityImpl(new TestService(50))); workerFactory.start(); } } ================================================ FILE: core/src/main/java/io/temporal/samples/polling/periodicsequence/PeriodicPollingWorkflowImpl.java ================================================ package io.temporal.samples.polling.periodicsequence; import io.temporal.samples.polling.PollingWorkflow; import io.temporal.workflow.ChildWorkflowOptions; import io.temporal.workflow.Workflow; public class PeriodicPollingWorkflowImpl implements PollingWorkflow { // Set some periodic poll interval, for sample we set 5 seconds private int pollingIntervalInSeconds = 5; @Override public String exec() { PollingChildWorkflow childWorkflow = Workflow.newChildWorkflowStub( PollingChildWorkflow.class, ChildWorkflowOptions.newBuilder().setWorkflowId("ChildWorkflowPoll").build()); return childWorkflow.exec(pollingIntervalInSeconds); } } ================================================ FILE: core/src/main/java/io/temporal/samples/polling/periodicsequence/PollingChildWorkflow.java ================================================ package io.temporal.samples.polling.periodicsequence; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; @WorkflowInterface public interface PollingChildWorkflow { @WorkflowMethod String exec(int pollingIntervalInSeconds); } ================================================ FILE: core/src/main/java/io/temporal/samples/polling/periodicsequence/README.md ================================================ ## Periodic sequence This samples shows periodic polling via Child Workflow. This is a rare scenario where polling requires execution of a sequence of Activities, or Activity arguments need to change between polling retries. For this case we use a Child Workflow to call polling Activities a set number of times in a loop and then periodically calls continue-as-new. The Parent Workflow is not aware about the Child Workflow calling continue-as-new and it gets notified when it completes (or fails). To run this sample: ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.polling.periodicsequence.PeriodicPollingStarter ``` ================================================ FILE: core/src/main/java/io/temporal/samples/retryonsignalinterceptor/FailureRequester.java ================================================ package io.temporal.samples.retryonsignalinterceptor; import static io.temporal.samples.retryonsignalinterceptor.MyWorkflowWorker.WORKFLOW_ID; import io.temporal.client.WorkflowClient; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import java.io.IOException; /** * Send signal requesting that an exception thrown from the activity is propagated to the workflow. */ public class FailureRequester { public static void main(String[] args) { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); // Note that we use the listener interface that the interceptor registered dynamically, not the // workflow interface. RetryOnSignalInterceptorListener workflow = client.newWorkflowStub(RetryOnSignalInterceptorListener.class, WORKFLOW_ID); // Sends "Fail" signal to the workflow. workflow.fail(); System.out.println("\"Fail\" signal sent"); System.exit(0); } } ================================================ FILE: core/src/main/java/io/temporal/samples/retryonsignalinterceptor/MyActivity.java ================================================ package io.temporal.samples.retryonsignalinterceptor; import io.temporal.activity.ActivityInterface; @ActivityInterface public interface MyActivity { void execute(); } ================================================ FILE: core/src/main/java/io/temporal/samples/retryonsignalinterceptor/MyActivityImpl.java ================================================ package io.temporal.samples.retryonsignalinterceptor; import io.temporal.failure.ApplicationFailure; import java.util.concurrent.atomic.AtomicInteger; public class MyActivityImpl implements MyActivity { /** * WARNING! Never rely on such shared state in real applications. The activity variables are per * process and in almost all cases multiple worker processes are used. */ private final AtomicInteger count = new AtomicInteger(); /** Sleeps 5 seconds. Fails for 4 first invocations, and then completes. */ @Override public void execute() { try { Thread.sleep(5000); } catch (InterruptedException e) { throw new RuntimeException(e); } if (count.incrementAndGet() < 5) { throw ApplicationFailure.newFailure("simulated", "type1"); } } } ================================================ FILE: core/src/main/java/io/temporal/samples/retryonsignalinterceptor/MyWorkflow.java ================================================ package io.temporal.samples.retryonsignalinterceptor; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; @WorkflowInterface public interface MyWorkflow { @WorkflowMethod void execute(); } ================================================ FILE: core/src/main/java/io/temporal/samples/retryonsignalinterceptor/MyWorkflowImpl.java ================================================ package io.temporal.samples.retryonsignalinterceptor; import io.temporal.activity.ActivityOptions; import io.temporal.common.RetryOptions; import io.temporal.workflow.Workflow; import java.time.Duration; public class MyWorkflowImpl implements MyWorkflow { private final MyActivity activity = Workflow.newActivityStub( MyActivity.class, ActivityOptions.newBuilder() .setStartToCloseTimeout(Duration.ofSeconds(30)) // disable server side retries. In most production applications the retries should be // done for a while before requiring an external operator signal. .setRetryOptions(RetryOptions.newBuilder().setMaximumAttempts(1).build()) .build()); @Override public void execute() { activity.execute(); } } ================================================ FILE: core/src/main/java/io/temporal/samples/retryonsignalinterceptor/MyWorkflowWorker.java ================================================ package io.temporal.samples.retryonsignalinterceptor; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import io.temporal.worker.WorkerFactoryOptions; import java.io.IOException; public class MyWorkflowWorker { static final String TASK_QUEUE = "RetryOnSignalInterceptor"; static final String WORKFLOW_ID = "RetryOnSignalInterceptor1"; public static void main(String[] args) { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); // Register interceptor with the factory. WorkerFactoryOptions factoryOptions = WorkerFactoryOptions.newBuilder() .setWorkerInterceptors(new RetryOnSignalWorkerInterceptor()) .validateAndBuildWithDefaults(); WorkerFactory factory = WorkerFactory.newInstance(client, factoryOptions); Worker worker = factory.newWorker(TASK_QUEUE); worker.registerWorkflowImplementationTypes(MyWorkflowImpl.class); worker.registerActivitiesImplementations(new MyActivityImpl()); factory.start(); // Create the workflow client stub. It is used to start our workflow execution. MyWorkflow workflow = client.newWorkflowStub( MyWorkflow.class, WorkflowOptions.newBuilder() .setWorkflowId(WORKFLOW_ID) .setTaskQueue(TASK_QUEUE) .build()); // Execute workflow waiting for it to complete. System.out.println("Starting workflow " + WORKFLOW_ID); workflow.execute(); System.out.println("Workflow completed"); System.exit(0); } } ================================================ FILE: core/src/main/java/io/temporal/samples/retryonsignalinterceptor/QueryRequester.java ================================================ package io.temporal.samples.retryonsignalinterceptor; import static io.temporal.samples.retryonsignalinterceptor.MyWorkflowWorker.WORKFLOW_ID; import io.temporal.client.WorkflowClient; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import java.io.IOException; public class QueryRequester { public static void main(String[] args) { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); // Note that we use the listener interface that the interceptor registered dynamically, not the // workflow interface. RetryOnSignalInterceptorListener workflow = client.newWorkflowStub(RetryOnSignalInterceptorListener.class, WORKFLOW_ID); // Queries workflow. String status = workflow.getPendingActivitiesStatus(); System.out.println("Workflow Pending Activities Status:\n\n" + status); System.exit(0); } } ================================================ FILE: core/src/main/java/io/temporal/samples/retryonsignalinterceptor/README.MD ================================================ # The Retry On Signal Interceptor Demonstrates an interceptor that upon activity failure waits for an external signal that indicates if activity should fail or retry. Starts Worker. The worker upon start initiates a workflow that has an activity that fails on the fist invocation. ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.retryonsignalinterceptor.MyWorkflowWorker ``` Sends Signal to indicate that the activity should be retried. ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.retryonsignalinterceptor.RetryRequester ``` Sends a signal to propagate the activity failure to the workflow instead of retrying. ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.retryonsignalinterceptor.FailureRequester ``` ================================================ FILE: core/src/main/java/io/temporal/samples/retryonsignalinterceptor/RetryOnSignalInterceptorListener.java ================================================ package io.temporal.samples.retryonsignalinterceptor; import io.temporal.workflow.QueryMethod; import io.temporal.workflow.SignalMethod; /** Interface used to dynamically register signal and query handlers from the interceptor. */ public interface RetryOnSignalInterceptorListener { /** Requests retry of the activities waiting after failure. */ @SignalMethod void retry(); /** Requests no more retries of the activities waiting after failure. */ @SignalMethod void fail(); /** Returns human status of the pending activities. */ @QueryMethod String getPendingActivitiesStatus(); } ================================================ FILE: core/src/main/java/io/temporal/samples/retryonsignalinterceptor/RetryOnSignalWorkerInterceptor.java ================================================ package io.temporal.samples.retryonsignalinterceptor; import io.temporal.common.interceptors.*; /** Should be registered through WorkerFactoryOptions. */ public class RetryOnSignalWorkerInterceptor extends WorkerInterceptorBase { @Override public WorkflowInboundCallsInterceptor interceptWorkflow(WorkflowInboundCallsInterceptor next) { return new RetryOnSignalWorkflowInboundCallsInterceptor(next); } @Override public ActivityInboundCallsInterceptor interceptActivity(ActivityInboundCallsInterceptor next) { return next; } } ================================================ FILE: core/src/main/java/io/temporal/samples/retryonsignalinterceptor/RetryOnSignalWorkflowInboundCallsInterceptor.java ================================================ package io.temporal.samples.retryonsignalinterceptor; import io.temporal.common.interceptors.WorkflowInboundCallsInterceptor; import io.temporal.common.interceptors.WorkflowInboundCallsInterceptorBase; import io.temporal.common.interceptors.WorkflowOutboundCallsInterceptor; public class RetryOnSignalWorkflowInboundCallsInterceptor extends WorkflowInboundCallsInterceptorBase { public RetryOnSignalWorkflowInboundCallsInterceptor(WorkflowInboundCallsInterceptor next) { super(next); } @Override public void init(WorkflowOutboundCallsInterceptor outboundCalls) { super.init(new RetryOnSignalWorkflowOutboundCallsInterceptor(outboundCalls)); } } ================================================ FILE: core/src/main/java/io/temporal/samples/retryonsignalinterceptor/RetryOnSignalWorkflowOutboundCallsInterceptor.java ================================================ package io.temporal.samples.retryonsignalinterceptor; import com.google.common.base.Throwables; import io.temporal.common.interceptors.WorkflowOutboundCallsInterceptor; import io.temporal.common.interceptors.WorkflowOutboundCallsInterceptorBase; import io.temporal.workflow.*; import java.util.ArrayList; import java.util.List; /** * Most of the complexity of the implementation is due to the asynchronous nature of the activity * invocation at the interceptor level. */ public class RetryOnSignalWorkflowOutboundCallsInterceptor extends WorkflowOutboundCallsInterceptorBase { private enum Action { RETRY, FAIL } private class ActivityRetryState { private final ActivityInput input; private final CompletablePromise asyncResult = Workflow.newPromise(); private CompletablePromise action; private Exception lastFailure; private int attempt; private ActivityRetryState(ActivityInput input) { this.input = input; } ActivityOutput execute() { return executeWithAsyncRetry(); } // Executes activity with retry based on signaled action asynchronously private ActivityOutput executeWithAsyncRetry() { attempt++; lastFailure = null; action = null; ActivityOutput result = RetryOnSignalWorkflowOutboundCallsInterceptor.super.executeActivity(input); result .getResult() .handle( (r, failure) -> { // No failure complete if (failure == null) { pendingActivities.remove(this); asyncResult.complete(r); return null; } // Asynchronously executes requested action when signal is received. lastFailure = failure; action = Workflow.newPromise(); return action.thenApply( a -> { if (a == Action.FAIL) { asyncResult.completeExceptionally(failure); } else { // Retries recursively. executeWithAsyncRetry(); } return null; }); }); return new ActivityOutput<>(result.getActivityId(), asyncResult); } public void retry() { if (action == null) { return; } action.complete(Action.RETRY); } public void fail() { if (action == null) { return; } action.complete(Action.FAIL); } public String getStatus() { String activityName = input.getActivityName(); if (lastFailure == null) { return "Executing activity \"" + activityName + "\". Attempt=" + attempt; } if (!action.isCompleted()) { return "Last \"" + activityName + "\" activity failure:\n" + Throwables.getStackTraceAsString(lastFailure) + "\n\nretry or fail ?"; } return (action.get() == Action.RETRY ? "Going to retry" : "Going to fail") + " activity \"" + activityName + "\""; } } /** * For the example brevity the interceptor fails or retries all activities that are waiting for an * action. The production version might implement retry and failure of specific activities by * their type. */ private final List> pendingActivities = new ArrayList<>(); public RetryOnSignalWorkflowOutboundCallsInterceptor(WorkflowOutboundCallsInterceptor next) { super(next); // Registers the listener for retry and fail signals as well as getPendingActivitiesStatus // query. Register in the constructor to do it once per workflow instance. Workflow.registerListener( new RetryOnSignalInterceptorListener() { @Override public void retry() { for (ActivityRetryState pending : pendingActivities) { pending.retry(); } } @Override public void fail() { for (ActivityRetryState pending : pendingActivities) { pending.fail(); } } @Override public String getPendingActivitiesStatus() { StringBuilder result = new StringBuilder(); for (ActivityRetryState pending : pendingActivities) { if (result.length() > 0) { result.append('\n'); } result.append(pending.getStatus()); } return result.toString(); } }); } @Override public ActivityOutput executeActivity(ActivityInput input) { ActivityRetryState retryState = new ActivityRetryState(input); pendingActivities.add(retryState); return retryState.execute(); } } ================================================ FILE: core/src/main/java/io/temporal/samples/retryonsignalinterceptor/RetryRequester.java ================================================ package io.temporal.samples.retryonsignalinterceptor; import static io.temporal.samples.retryonsignalinterceptor.MyWorkflowWorker.WORKFLOW_ID; import io.temporal.client.WorkflowClient; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import java.io.IOException; public class RetryRequester { public static void main(String[] args) { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); // Note that we use the listener interface that the interceptor registered dynamically, not the // workflow interface. RetryOnSignalInterceptorListener workflow = client.newWorkflowStub(RetryOnSignalInterceptorListener.class, WORKFLOW_ID); // Sends "Retry" signal to the workflow. workflow.retry(); System.out.println("\"Retry\" signal sent"); System.exit(0); } } ================================================ FILE: core/src/main/java/io/temporal/samples/safemessagepassing/ClusterManagerActivities.java ================================================ package io.temporal.samples.safemessagepassing; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import io.temporal.activity.ActivityInterface; import io.temporal.activity.ActivityMethod; import java.util.List; import java.util.Set; @ActivityInterface public interface ClusterManagerActivities { class AssignNodesToJobInput { private final List nodes; private final String jobName; @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) public AssignNodesToJobInput( @JsonProperty("nodes_to_assign") Set nodesToAssign, @JsonProperty("job_name") String jobName) { this.nodes = List.copyOf(nodesToAssign); this.jobName = jobName; } @JsonProperty("nodes_to_assign") public List getNodes() { return nodes; } @JsonProperty("job_name") public String getJobName() { return jobName; } } @ActivityMethod void assignNodesToJob(AssignNodesToJobInput input); class UnassignNodesForJobInput { private final List nodes; private final String jobName; @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) public UnassignNodesForJobInput( @JsonProperty("nodes") Set nodes, @JsonProperty("job_name") String jobName) { this.nodes = List.copyOf(nodes); this.jobName = jobName; } @JsonProperty("nodes") public List getNodes() { return nodes; } @JsonProperty("job_name") public String getJobName() { return jobName; } } @ActivityMethod void unassignNodesForJob(UnassignNodesForJobInput input); class FindBadNodesInput { private final Set nodesToCheck; @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) public FindBadNodesInput(@JsonProperty("assigned_nodes") Set assignedNodes) { this.nodesToCheck = assignedNodes; } @JsonProperty("assigned_nodes") public Set getNodesToCheck() { return nodesToCheck; } } @ActivityMethod Set findBadNodes(FindBadNodesInput input); @ActivityMethod void shutdown(); } ================================================ FILE: core/src/main/java/io/temporal/samples/safemessagepassing/ClusterManagerActivitiesImpl.java ================================================ package io.temporal.samples.safemessagepassing; import java.util.Set; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ClusterManagerActivitiesImpl implements ClusterManagerActivities { private static final Logger log = LoggerFactory.getLogger(ClusterManagerActivitiesImpl.class); @Override public void assignNodesToJob(AssignNodesToJobInput input) { for (String node : input.getNodes()) { log.info("Assigned node " + node + " to job " + input.getJobName()); } try { Thread.sleep(100); } catch (InterruptedException e) { throw new RuntimeException(e); } } @Override public void unassignNodesForJob(UnassignNodesForJobInput input) { for (String node : input.getNodes()) { log.info("Unassigned node " + node + " from job " + input.getJobName()); } try { Thread.sleep(100); } catch (InterruptedException e) { throw new RuntimeException(e); } } @Override public Set findBadNodes(FindBadNodesInput input) { try { Thread.sleep(100); } catch (InterruptedException e) { throw new RuntimeException(e); } Set badNodes = input.getNodesToCheck().stream() .filter(n -> Integer.parseInt(n) % 5 == 0) .collect(Collectors.toSet()); if (!badNodes.isEmpty()) { log.info("Found bad nodes: " + badNodes); } else { log.info("No bad nodes found"); } return badNodes; } @Override public void shutdown() { log.info("Shutting down cluster"); try { Thread.sleep(100); } catch (InterruptedException e) { throw new RuntimeException(e); } } } ================================================ FILE: core/src/main/java/io/temporal/samples/safemessagepassing/ClusterManagerWorkflow.java ================================================ package io.temporal.samples.safemessagepassing; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import io.temporal.workflow.SignalMethod; import io.temporal.workflow.UpdateMethod; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; import java.util.*; /** * ClusterManagerWorkflow keeps track of the assignments of a cluster of nodes. Via signals, the * cluster can be started and shutdown. Via updates, clients can also assign jobs to nodes and * delete jobs. These updates must run atomically. */ @WorkflowInterface public interface ClusterManagerWorkflow { enum ClusterState { NOT_STARTED, STARTED, SHUTTING_DOWN } // In workflows that continue-as-new, it's convenient to store all your state in one serializable // structure to make it easier to pass between runs class ClusterManagerState { public ClusterState workflowState = ClusterState.NOT_STARTED; public Map> nodes = new HashMap<>(); public Set jobAssigned = new HashSet<>(); } class ClusterManagerInput { private final Optional state; private final boolean testContinueAsNew; @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) public ClusterManagerInput( @JsonProperty("state") Optional state, @JsonProperty("test_continue_as_new") boolean testContinueAsNew) { this.state = state; this.testContinueAsNew = testContinueAsNew; } @JsonProperty("state") public Optional getState() { return state; } @JsonProperty("test_continue_as_new") public boolean isTestContinueAsNew() { return testContinueAsNew; } } class ClusterManagerResult { private final int numCurrentlyAssignedNodes; private final int numBadNodes; @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) public ClusterManagerResult( @JsonProperty("num_currently_assigned_nodes") int numCurrentlyAssignedNodes, @JsonProperty("num_bad_nodes") int numBadNodes) { this.numCurrentlyAssignedNodes = numCurrentlyAssignedNodes; this.numBadNodes = numBadNodes; } @JsonProperty("num_currently_assigned_nodes") public int getNumCurrentlyAssignedNodes() { return numCurrentlyAssignedNodes; } @JsonProperty("num_bad_nodes") public int getNumBadNodes() { return numBadNodes; } } // Be in the habit of storing message inputs and outputs in serializable structures. // This makes it easier to add more overtime in a backward-compatible way. class ClusterManagerAssignNodesToJobInput { // If larger or smaller than previous amounts, will resize the job. private final int totalNumNodes; private final String jobName; @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) public ClusterManagerAssignNodesToJobInput( @JsonProperty("total_num_nodes") int totalNumNodes, @JsonProperty("job_name") String jobName) { this.totalNumNodes = totalNumNodes; this.jobName = jobName; } @JsonProperty("total_num_nodes") public int getTotalNumNodes() { return totalNumNodes; } @JsonProperty("job_name") public String getJobName() { return jobName; } } class ClusterManagerDeleteJobInput { private final String jobName; @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) public ClusterManagerDeleteJobInput(@JsonProperty("job_name") String jobName) { this.jobName = jobName; } @JsonProperty("job_name") public String getJobName() { return jobName; } } class ClusterManagerAssignNodesToJobResult { private final Set nodesAssigned; @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) public ClusterManagerAssignNodesToJobResult( @JsonProperty("assigned_nodes") Set assignedNodes) { this.nodesAssigned = assignedNodes; } @JsonProperty("assigned_nodes") public Set getNodesAssigned() { return nodesAssigned; } } @WorkflowMethod ClusterManagerResult run(ClusterManagerInput input); @SignalMethod void startCluster(); @UpdateMethod boolean stopCluster(); // This is an update as opposed to a signal because the client may want to wait for nodes to be // allocated before sending work to those nodes. Returns the list of node names that were // allocated to the job. @UpdateMethod ClusterManagerAssignNodesToJobResult assignNodesToJobs(ClusterManagerAssignNodesToJobInput input); // Even though it returns nothing, this is an update because the client may want to track it, for // example to wait for nodes to be unassigned before reassigning them. @UpdateMethod void deleteJob(ClusterManagerDeleteJobInput input); } ================================================ FILE: core/src/main/java/io/temporal/samples/safemessagepassing/ClusterManagerWorkflowImpl.java ================================================ package io.temporal.samples.safemessagepassing; import io.temporal.activity.ActivityOptions; import io.temporal.common.RetryOptions; import io.temporal.failure.ApplicationFailure; import io.temporal.workflow.Workflow; import io.temporal.workflow.WorkflowInit; import io.temporal.workflow.WorkflowLock; import java.time.Duration; import java.util.Collections; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ClusterManagerWorkflowImpl implements ClusterManagerWorkflow { private static final Logger logger = LoggerFactory.getLogger(ClusterManagerWorkflowImpl.class); private final ClusterManagerState state; private final WorkflowLock nodeLock; private final Duration sleepInterval; private final int maxHistoryLength; private ClusterManagerActivities activities = Workflow.newActivityStub( ClusterManagerActivities.class, ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(10)).build(), Collections.singletonMap( "findBadNodes", ActivityOptions.newBuilder() .setRetryOptions(RetryOptions.newBuilder().setMaximumAttempts(1).build()) .build())); @WorkflowInit public ClusterManagerWorkflowImpl(ClusterManagerInput input) { nodeLock = Workflow.newWorkflowLock(); if (input.getState().isPresent()) { state = input.getState().get(); } else { state = new ClusterManagerState(); } if (input.isTestContinueAsNew()) { maxHistoryLength = 120; sleepInterval = Duration.ofSeconds(1); } else { sleepInterval = Duration.ofSeconds(10); maxHistoryLength = 0; } } @Override public ClusterManagerResult run(ClusterManagerInput input) { Workflow.await(() -> state.workflowState != ClusterState.NOT_STARTED); // The cluster manager is a long-running "entity" workflow so we need to periodically checkpoint // its state and // continue-as-new. while (true) { performHealthChecks(); if (!Workflow.await( sleepInterval, () -> state.workflowState == ClusterState.SHUTTING_DOWN || shouldContinueAsNew())) { } else if (state.workflowState == ClusterState.SHUTTING_DOWN) { break; } else if (shouldContinueAsNew()) { // We don't want to leave any job assignment or deletion handlers half-finished when we // continue as new. Workflow.await(() -> Workflow.isEveryHandlerFinished()); logger.info("Continuing as new"); Workflow.continueAsNew( new ClusterManagerInput(Optional.of(state), input.isTestContinueAsNew())); } } // Make sure we finish off handlers such as deleting jobs before we complete the workflow. Workflow.await(() -> Workflow.isEveryHandlerFinished()); return new ClusterManagerResult(getAssignedNodes(null).size(), getBadNodes().size()); } @Override public void startCluster() { if (state.workflowState != ClusterState.NOT_STARTED) { logger.warn("Cannot start cluster in state {}", state.workflowState); return; } state.workflowState = ClusterState.STARTED; for (int i = 0; i < 25; i++) { state.nodes.put(String.valueOf(i), Optional.empty()); } logger.info("Cluster started"); } @Override public boolean stopCluster() { if (state.workflowState != ClusterState.STARTED) { // This is used as an Update handler so that we can return an error to the caller. throw ApplicationFailure.newFailure( "Cannot shutdown cluster in state " + state.workflowState, "IllegalState"); } activities.shutdown(); state.workflowState = ClusterState.SHUTTING_DOWN; logger.info("Cluster shut down"); return true; } @Override public ClusterManagerAssignNodesToJobResult assignNodesToJobs( ClusterManagerAssignNodesToJobInput input) { Workflow.await(() -> state.workflowState != ClusterState.NOT_STARTED); if (state.workflowState == ClusterState.SHUTTING_DOWN) { throw ApplicationFailure.newFailure( "Cannot assign nodes to a job: Cluster is already shut down", "IllegalState"); } nodeLock.lock(); try { // Idempotency guard. if (state.jobAssigned.contains(input.getJobName())) { return new ClusterManagerAssignNodesToJobResult(getAssignedNodes(input.getJobName())); } Set unassignedNodes = getUnassignedNodes(); if (unassignedNodes.size() < input.getTotalNumNodes()) { // If you want the client to receive a failure, either add an update validator and throw the // exception from there, or raise an ApplicationFailure. Other exceptions in the main // handler will cause the workflow to keep retrying and get it stuck. throw ApplicationFailure.newFailure( "Cannot assign nodes to a job: Not enough nodes available", "IllegalState"); } Set nodesToAssign = unassignedNodes.stream().limit(input.getTotalNumNodes()).collect(Collectors.toSet()); // This call would be dangerous without nodesLock because it yields control and allows // interleaving with deleteJob and performHealthChecks, which both touch this.state.nodes. activities.assignNodesToJob( new ClusterManagerActivities.AssignNodesToJobInput(nodesToAssign, input.getJobName())); for (String node : nodesToAssign) { state.nodes.put(node, Optional.of(input.getJobName())); } state.jobAssigned.add(input.getJobName()); return new ClusterManagerAssignNodesToJobResult(nodesToAssign); } finally { nodeLock.unlock(); } } @Override public void deleteJob(ClusterManagerDeleteJobInput input) { Workflow.await(() -> state.workflowState != ClusterState.NOT_STARTED); if (state.workflowState == ClusterState.SHUTTING_DOWN) { // If you want the client to receive a failure, either add an update validator and throw the // exception from there, or raise an ApplicationFailure. Other exceptions in the main handler // will cause the workflow to keep retrying and get it stuck. throw ApplicationFailure.newFailure( "Cannot delete a job: Cluster is already shut down", "IllegalState"); } nodeLock.lock(); try { Set nodesToUnassign = getAssignedNodes(input.getJobName()); // This call would be dangerous without nodesLock because it yields control and allows // interleaving // with assignNodesToJob and performHealthChecks, which all touch this.state.nodes. activities.unassignNodesForJob( new ClusterManagerActivities.UnassignNodesForJobInput( nodesToUnassign, input.getJobName())); for (String node : nodesToUnassign) { state.nodes.put(node, Optional.empty()); } } finally { nodeLock.unlock(); } } private Set getAssignedNodes(String jobName) { if (jobName != null) { return state.nodes.entrySet().stream() .filter(e -> e.getValue().isPresent() && e.getValue().get().equals(jobName)) .map(e -> e.getKey()) .collect(Collectors.toSet()); } else { return state.nodes.entrySet().stream() .filter(e -> e.getValue().isPresent() && !e.getValue().get().equals("BAD!")) .map(e -> e.getKey()) .collect(Collectors.toSet()); } } private Set getUnassignedNodes() { return state.nodes.entrySet().stream() .filter(e -> !e.getValue().isPresent()) .map(e -> e.getKey()) .collect(Collectors.toSet()); } private Set getBadNodes() { return state.nodes.entrySet().stream() .filter(e -> e.getValue().isPresent() && e.getValue().get().equals("BAD!")) .map(e -> e.getKey()) .collect(Collectors.toSet()); } private void performHealthChecks() { nodeLock.lock(); try { Set assignedNodes = getAssignedNodes(null); Set badNodes = activities.findBadNodes(new ClusterManagerActivities.FindBadNodesInput(assignedNodes)); for (String badNode : badNodes) { state.nodes.put(badNode, Optional.of("BAD!")); } } catch (Exception e) { logger.error("Health check failed", e); } finally { nodeLock.unlock(); } } private boolean shouldContinueAsNew() { if (Workflow.getInfo().isContinueAsNewSuggested()) { return true; } // This is just for ease-of-testing. In production, we trust temporal to tell us when to // continue as new. if (maxHistoryLength > 0 && Workflow.getInfo().getHistoryLength() > maxHistoryLength) { return true; } return false; } } ================================================ FILE: core/src/main/java/io/temporal/samples/safemessagepassing/ClusterManagerWorkflowStarter.java ================================================ package io.temporal.samples.safemessagepassing; import static io.temporal.samples.safemessagepassing.ClusterManagerWorkflowWorker.CLUSTER_MANAGER_WORKFLOW_ID; import static io.temporal.samples.safemessagepassing.ClusterManagerWorkflowWorker.TASK_QUEUE; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.client.WorkflowStub; import io.temporal.client.WorkflowUpdateStage; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import java.io.IOException; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.UUID; import java.util.concurrent.CompletableFuture; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ClusterManagerWorkflowStarter { private static final Logger logger = LoggerFactory.getLogger(ClusterManagerWorkflowStarter.class); public static void main(String[] args) { if (args.length > 1) { System.err.println( "Usage: java " + ClusterManagerWorkflowStarter.class.getName() + " "); System.exit(1); } // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); boolean shouldTestContinueAsNew = args.length > 0 ? Boolean.parseBoolean(args[0]) : false; ClusterManagerWorkflow cluster = client.newWorkflowStub( ClusterManagerWorkflow.class, WorkflowOptions.newBuilder() .setTaskQueue(TASK_QUEUE) .setWorkflowId(CLUSTER_MANAGER_WORKFLOW_ID + "-" + UUID.randomUUID()) .build()); logger.info("Starting cluster"); WorkflowClient.start( cluster::run, new ClusterManagerWorkflow.ClusterManagerInput(Optional.empty(), shouldTestContinueAsNew)); Duration delay = shouldTestContinueAsNew ? Duration.ofSeconds(10) : Duration.ofSeconds(1); cluster.startCluster(); logger.info("Assigning jobs to nodes..."); List> assignJobs = new ArrayList<>(); for (int i = 0; i < 6; i++) { assignJobs.add( WorkflowStub.fromTyped(cluster) .startUpdate( "assignNodesToJobs", WorkflowUpdateStage.ACCEPTED, ClusterManagerWorkflow.ClusterManagerAssignNodesToJobResult.class, new ClusterManagerWorkflow.ClusterManagerAssignNodesToJobInput(2, "job" + i)) .getResultAsync()); } assignJobs.forEach(CompletableFuture::join); logger.info("Sleeping for " + delay.getSeconds() + " seconds"); try { Thread.sleep(delay.toMillis()); } catch (InterruptedException e) { throw new RuntimeException(e); } logger.info("Deleting jobs..."); List> deleteJobs = new ArrayList<>(); for (int i = 0; i < 6; i++) { deleteJobs.add( WorkflowStub.fromTyped(cluster) .startUpdate( "deleteJob", WorkflowUpdateStage.ACCEPTED, Void.class, new ClusterManagerWorkflow.ClusterManagerDeleteJobInput("job" + i)) .getResultAsync()); } deleteJobs.forEach(CompletableFuture::join); logger.info("Stopping cluster..."); cluster.stopCluster(); ClusterManagerWorkflow.ClusterManagerResult result = cluster.run(new ClusterManagerWorkflow.ClusterManagerInput(Optional.empty(), false)); logger.info( "Cluster shut down successfully. It had " + result.getNumCurrentlyAssignedNodes() + " nodes assigned at the end."); System.exit(0); } } ================================================ FILE: core/src/main/java/io/temporal/samples/safemessagepassing/ClusterManagerWorkflowWorker.java ================================================ package io.temporal.samples.safemessagepassing; import io.temporal.client.WorkflowClient; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ClusterManagerWorkflowWorker { private static final Logger logger = LoggerFactory.getLogger(ClusterManagerWorkflowWorker.class); static final String TASK_QUEUE = "ClusterManagerWorkflowTaskQueue"; static final String CLUSTER_MANAGER_WORKFLOW_ID = "ClusterManagerWorkflow"; public static void main(String[] args) { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); WorkerFactory factory = WorkerFactory.newInstance(client); final Worker worker = factory.newWorker(TASK_QUEUE); worker.registerWorkflowImplementationTypes(ClusterManagerWorkflowImpl.class); worker.registerActivitiesImplementations(new ClusterManagerActivitiesImpl()); factory.start(); logger.info("Worker started for task queue: " + TASK_QUEUE); } } ================================================ FILE: core/src/main/java/io/temporal/samples/safemessagepassing/README.md ================================================ # Safe Message Passing This sample shows off important techniques for handling signals and updates, aka messages. In particular, it illustrates how message handlers can interleave or not be completed before the workflow completes, and how you can manage that. * Here, using Workflow.await, signal and update handlers will only operate when the workflow is within a certain state--between clusterStarted and clusterShutdown. * You can run start_workflow with an initializer signal that you want to run before anything else other than the workflow's constructor. This pattern is known as "signal-with-start." * Message handlers can block and their actions can be interleaved with one another and with the main workflow. This can easily cause bugs, so you can use a lock to protect shared state from interleaved access. * An "Entity" workflow, i.e. a long-lived workflow, periodically "continues as new". It must do this to prevent its history from growing too large, and it passes its state to the next workflow. You can check `Workflow.getInfo().isContinueAsNewSuggested()` to see when it's time. * Most people want their message handlers to finish before the workflow run completes or continues as new. Use `Workflow.await(() -> Workflow.isEveryHandlerFinished())` to achieve this. * Message handlers can be made idempotent. See update `ClusterManagerWorkflow.assignNodesToJobs`. First start the Worker: ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.safemessagepassing.ClusterManagerWorkflowWorker ``` Then in a different terminal window start the Workflow Execution: ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.safemessagepassing.ClusterManagerWorkflowStarter ``` ================================================ FILE: core/src/main/java/io/temporal/samples/sleepfordays/README.md ================================================ # Sleep for days This sample demonstrates how to use Temporal to run a workflow that periodically sleeps for a number of days. ## Run the sample 1. Start the Worker: ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.sleepfordays.Worker ``` 2. Start the Starter ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.sleepfordays.Starter ``` ================================================ FILE: core/src/main/java/io/temporal/samples/sleepfordays/SendEmailActivity.java ================================================ package io.temporal.samples.sleepfordays; import io.temporal.activity.ActivityInterface; @ActivityInterface public interface SendEmailActivity { void sendEmail(String email); } ================================================ FILE: core/src/main/java/io/temporal/samples/sleepfordays/SendEmailActivityImpl.java ================================================ package io.temporal.samples.sleepfordays; public class SendEmailActivityImpl implements SendEmailActivity { @Override public void sendEmail(String email) { System.out.println(email); } } ================================================ FILE: core/src/main/java/io/temporal/samples/sleepfordays/SleepForDaysImpl.java ================================================ package io.temporal.samples.sleepfordays; import io.temporal.activity.ActivityOptions; import io.temporal.workflow.Promise; import io.temporal.workflow.Workflow; import java.time.Duration; public class SleepForDaysImpl implements SleepForDaysWorkflow { private final SendEmailActivity activity; private boolean complete = false; public SleepForDaysImpl() { this.activity = Workflow.newActivityStub( SendEmailActivity.class, ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(10)).build()); } @Override public String sleepForDays() { while (!this.complete) { activity.sendEmail(String.format("Sleeping for 30 days")); Promise timer = Workflow.newTimer(Duration.ofDays(30)); Workflow.await(() -> timer.isCompleted() || this.complete); } return "done!"; } @Override public void complete() { this.complete = true; } } ================================================ FILE: core/src/main/java/io/temporal/samples/sleepfordays/SleepForDaysWorkflow.java ================================================ package io.temporal.samples.sleepfordays; import io.temporal.workflow.SignalMethod; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; @WorkflowInterface public interface SleepForDaysWorkflow { @WorkflowMethod String sleepForDays(); @SignalMethod void complete(); } ================================================ FILE: core/src/main/java/io/temporal/samples/sleepfordays/Starter.java ================================================ package io.temporal.samples.sleepfordays; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.client.WorkflowStub; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import java.io.IOException; public class Starter { public static final String TASK_QUEUE = "SleepForDaysTaskQueue"; public static void main(String[] args) { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); // Start a workflow execution. SleepForDaysWorkflow workflow = client.newWorkflowStub( SleepForDaysWorkflow.class, WorkflowOptions.newBuilder().setTaskQueue(TASK_QUEUE).build()); // Start the workflow. WorkflowClient.start(workflow::sleepForDays); WorkflowStub stub = WorkflowStub.fromTyped(workflow); // Wait for workflow to complete. This will wait indefinitely until a 'complete' signal is sent. stub.getResult(String.class); System.exit(0); } } ================================================ FILE: core/src/main/java/io/temporal/samples/sleepfordays/Worker.java ================================================ package io.temporal.samples.sleepfordays; import io.temporal.client.WorkflowClient; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.WorkerFactory; import java.io.IOException; public class Worker { public static final String TASK_QUEUE = "SleepForDaysTaskQueue"; public static void main(String[] args) { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); WorkerFactory factory = WorkerFactory.newInstance(client); io.temporal.worker.Worker worker = factory.newWorker(TASK_QUEUE); worker.registerWorkflowImplementationTypes(SleepForDaysImpl.class); worker.registerActivitiesImplementations(new SendEmailActivityImpl()); factory.start(); System.out.println("Worker started for task queue: " + TASK_QUEUE); } } ================================================ FILE: core/src/main/java/io/temporal/samples/ssl/MyWorkflow.java ================================================ package io.temporal.samples.ssl; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; @WorkflowInterface public interface MyWorkflow { @WorkflowMethod String execute(); } ================================================ FILE: core/src/main/java/io/temporal/samples/ssl/MyWorkflowImpl.java ================================================ package io.temporal.samples.ssl; public class MyWorkflowImpl implements MyWorkflow { @Override public String execute() { return "done"; } } ================================================ FILE: core/src/main/java/io/temporal/samples/ssl/README.md ================================================ # Workflow execution with mTLS This example shows how to secure your Temporal application with [mTLS](https://docs.temporal.io/security/#encryption-in-transit-with-mtls). This is required to connect with Temporal Cloud or any production Temporal deployment. ## Export env variables Before running the example you need to export the following env variables: - TEMPORAL_ENDPOINT: grpc endpoint, for Temporal Cloud would like `${namespace}.tmprl.cloud:7233`. - TEMPORAL_NAMESPACE: Namespace. - TEMPORAL_CLIENT_CERT: For Temporal Cloud see requirements [here](https://docs.temporal.io/cloud/how-to-manage-certificates-in-temporal-cloud#end-entity-certificates). - TEMPORAL_CLIENT_KEY: For Temporal Cloud see requirements [here](https://docs.temporal.io/cloud/how-to-manage-certificates-in-temporal-cloud#end-entity-certificates). ## Running this sample ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.ssl.Starter ``` ## Refreshing credentials - TEMPORAL_CREDENTIAL_REFRESH_PERIOD: The period in seconds to refresh the credentials in minutes. Setting this env variable will cause the worker to periodically update its credentials. For the full documentation see [here](https://grpc.github.io/grpc-java/javadoc/io/grpc/util/AdvancedTlsX509KeyManager.html). # Workflow execution with mTLS and custom Certificate Authority This sample shows how to start a worker that connects to a temporal cluster with mTLS enabled; created by ([tls-simple sample](https://github.com/temporalio/samples-server/tree/main/tls/tls-simple)); SslEnabledWorkerCustomCA demonstrates: - Passing a custom CA certificate file as parameter - Overriding the authority name used for TLS handshakes (if needed) This can be useful when connecting to Temporal Cloud through [AWS Privatelink](https://docs.temporal.io/cloud/security#privatelink) 1.Start a temporal cluster with tls Please follow the temporal server-sample to start simple Temporal mTLS cluster locally: [tls-simple](https://github.com/temporalio/samples-server/tree/main/tls/tls-simple) 2.Set environment variables ```bash # Environment variables # paths to ca cert, client cert and client key come from the previous step export TEMPORAL_CLIENT_CERT="" export TEMPORAL_CLIENT_KEY="" export TEMPORAL_CA_CERT="" export TEMPORAL_ENDPOINT="localhost:7233" # Temporal grpc endpoint export TEMPORAL_NAMESPACE="default" # Temporal namespace export TEMPORAL_SERVER_HOSTNAME="tls-sample" # Temporal server host name ``` 3.Start the Worker ```bash ./gradlew -q execute -PmainClass="io.temporal.samples.ssl.SslEnabledWorkerCustomCA" ``` 4.Expected result ```text [main] INFO i.t.s.WorkflowServiceStubsImpl - Created WorkflowServiceStubs for channel: ManagedChannelOrphanWrapper{delegate=ManagedChannelImpl{logId=1, target=localhost:7233}} [main] INFO io.temporal.internal.worker.Poller - start: Poller{name=Workflow Poller taskQueue="MyTaskQueue", namespace="default"} Workflow completed:done ``` ================================================ FILE: core/src/main/java/io/temporal/samples/ssl/SslEnabledWorkerCustomCA.java ================================================ package io.temporal.samples.ssl; import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; import io.grpc.netty.shaded.io.netty.handler.ssl.SslContext; import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowClientOptions; import io.temporal.client.WorkflowOptions; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.serviceclient.WorkflowServiceStubsOptions; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import java.io.FileInputStream; import java.io.InputStream; public class SslEnabledWorkerCustomCA { static final String TASK_QUEUE = "MyTaskQueue"; public static void main(String[] args) throws Exception { // Load your client certificate, which should look like: // -----BEGIN CERTIFICATE----- // ... // -----END CERTIFICATE----- InputStream clientCert = new FileInputStream(System.getenv("TEMPORAL_CLIENT_CERT")); // PKCS8 client key, which should look like: // -----BEGIN PRIVATE KEY----- // ... // -----END PRIVATE KEY----- InputStream clientKey = new FileInputStream(System.getenv("TEMPORAL_CLIENT_KEY")); // Load your Certification Authority certificate, which should look like: // -----BEGIN CERTIFICATE----- // ... // -----END CERTIFICATE----- InputStream caCert = new FileInputStream(System.getenv("TEMPORAL_CA_CERT")); // For temporal cloud this would likely be ${namespace}.tmprl.cloud:7233 String targetEndpoint = System.getenv("TEMPORAL_ENDPOINT"); // Your registered namespace. String namespace = System.getenv("TEMPORAL_NAMESPACE"); // Create an SSL Context using the client certificate and key based on the implementation // SimpleSslContextBuilder // https://github.com/temporalio/sdk-java/blob/master/temporal-serviceclient/src/main/java/io/temporal/serviceclient/SimpleSslContextBuilder.java SslContext sslContext = GrpcSslContexts.configure( SslContextBuilder.forClient() .keyManager(clientCert, clientKey) .trustManager(caCert)) .build(); // Create SSL enabled client by passing SslContext, created by // SimpleSslContextBuilder. WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs( WorkflowServiceStubsOptions.newBuilder() .setSslContext(sslContext) .setTarget(targetEndpoint) // Override the authority name used for TLS handshakes .setChannelInitializer( c -> c.overrideAuthority(System.getenv("TEMPORAL_SERVER_HOSTNAME"))) .build()); // Now setup and start workflow worker, which uses SSL enabled gRPC service to // communicate with backend. client that can be used to start and signal workflows. WorkflowClient client = WorkflowClient.newInstance( service, WorkflowClientOptions.newBuilder().setNamespace(namespace).build()); // worker factory that can be used to create workers for specific task queues WorkerFactory factory = WorkerFactory.newInstance(client); /* * Define the workflow worker. Workflow workers listen to a defined task queue and process * workflows and activities. */ Worker worker = factory.newWorker(TASK_QUEUE); /* * Register our workflow implementation with the worker. * Workflow implementations must be known to the worker at runtime in * order to dispatch workflow tasks. */ worker.registerWorkflowImplementationTypes(MyWorkflowImpl.class); /* * Start all the workers registered for a specific task queue. * The started workers then start polling for workflows and activities. */ factory.start(); // Create the workflow client stub. It is used to start our workflow execution. MyWorkflow workflow = client.newWorkflowStub( MyWorkflow.class, WorkflowOptions.newBuilder() .setWorkflowId("WORKFLOW_ID") .setTaskQueue(TASK_QUEUE) .build()); /* * Execute our workflow and wait for it to complete. The call to our execute method is * synchronous. */ String greeting = workflow.execute(); // Display workflow execution results System.out.println("Workflow completed:" + greeting); System.exit(0); } } ================================================ FILE: core/src/main/java/io/temporal/samples/ssl/Starter.java ================================================ package io.temporal.samples.ssl; import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; import io.grpc.netty.shaded.io.netty.handler.ssl.SslContext; import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; import io.grpc.util.AdvancedTlsX509KeyManager; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowClientOptions; import io.temporal.client.WorkflowOptions; import io.temporal.serviceclient.SimpleSslContextBuilder; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.serviceclient.WorkflowServiceStubsOptions; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import java.io.File; import java.io.FileInputStream; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; public class Starter { static final String TASK_QUEUE = "MyTaskQueue"; static final String WORKFLOW_ID = "HelloSSLWorkflow"; public static void main(String[] args) throws Exception { // Load your client certificate, which should look like: // -----BEGIN CERTIFICATE----- // ... // -----END CERTIFICATE----- File clientCertFile = new File(System.getenv("TEMPORAL_CLIENT_CERT")); // PKCS8 client key, which should look like: // -----BEGIN PRIVATE KEY----- // ... // -----END PRIVATE KEY----- File clientKeyFile = new File(System.getenv("TEMPORAL_CLIENT_KEY")); // For temporal cloud this would likely be ${namespace}.tmprl.cloud:7233 String targetEndpoint = System.getenv("TEMPORAL_ENDPOINT"); // Your registered namespace. String namespace = System.getenv("TEMPORAL_NAMESPACE"); // How often to refresh the client key and certificate String refreshPeriodString = System.getenv("TEMPORAL_CREDENTIAL_REFRESH_PERIOD"); long refreshPeriod = refreshPeriodString != null ? Integer.parseInt(refreshPeriodString) : 0; // Create SSL context from SimpleSslContextBuilder SslContext sslContext = SimpleSslContextBuilder.forPKCS8( new FileInputStream(clientCertFile), new FileInputStream(clientKeyFile)) .build(); // To refresh the client key and certificate, create an AdvancedTlsX509KeyManager and manually // configure the SSL context. if (refreshPeriod > 0) { AdvancedTlsX509KeyManager clientKeyManager = new AdvancedTlsX509KeyManager(); // Reload credentials every minute clientKeyManager.updateIdentityCredentials( clientCertFile, clientKeyFile, refreshPeriod, TimeUnit.MINUTES, Executors.newScheduledThreadPool(1)); sslContext = GrpcSslContexts.configure(SslContextBuilder.forClient().keyManager(clientKeyManager)) .build(); } // Create SSL enabled client by passing SslContext WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs( WorkflowServiceStubsOptions.newBuilder() .setSslContext(sslContext) .setTarget(targetEndpoint) .build()); // Now setup and start workflow worker, which uses SSL enabled gRPC service to communicate with // backend. // client that can be used to start and signal workflows. WorkflowClient client = WorkflowClient.newInstance( service, WorkflowClientOptions.newBuilder().setNamespace(namespace).build()); // worker factory that can be used to create workers for specific task queues WorkerFactory factory = WorkerFactory.newInstance(client); /* * Define the workflow worker. Workflow workers listen to a defined task queue and process * workflows and activities. */ Worker worker = factory.newWorker(TASK_QUEUE); /* * Register our workflow implementation with the worker. * Workflow implementations must be known to the worker at runtime in * order to dispatch workflow tasks. */ worker.registerWorkflowImplementationTypes(MyWorkflowImpl.class); /* * Register our Activity Types with the Worker. Since Activities are stateless and thread-safe, * the Activity Type is a shared instance. */ // worker.registerActivitiesImplementations(...); /* * Start all the workers registered for a specific task queue. * The started workers then start polling for workflows and activities. */ factory.start(); // Create the workflow client stub. It is used to start our workflow execution. MyWorkflow workflow = client.newWorkflowStub( MyWorkflow.class, WorkflowOptions.newBuilder() .setWorkflowId(WORKFLOW_ID) .setTaskQueue(TASK_QUEUE) .build()); /* * Execute our workflow and wait for it to complete. The call to our execute method is * synchronous. */ String greeting = workflow.execute(); // Display workflow execution results System.out.println(greeting); // System.exit(0); } } ================================================ FILE: core/src/main/java/io/temporal/samples/standaloneactivities/CountActivities.java ================================================ package io.temporal.samples.standaloneactivities; import static io.temporal.samples.standaloneactivities.StandaloneActivityWorker.TASK_QUEUE; import io.temporal.client.ActivityClient; import io.temporal.client.ActivityClientOptions; import io.temporal.client.ActivityExecutionCount; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import java.io.IOException; /** Counts standalone activity executions on the task queue. */ public class CountActivities { public static void main(String[] args) throws IOException { ClientConfigProfile profile = ClientConfigProfile.load(); WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); ActivityClient client = ActivityClient.newInstance( service, ActivityClientOptions.newBuilder().setNamespace(profile.getNamespace()).build()); try { ActivityExecutionCount resp = client.countExecutions("TaskQueue = '" + TASK_QUEUE + "'"); System.out.println("Total activities: " + resp.getCount()); resp.getGroups() .forEach( group -> System.out.println("Group " + group.getGroupValues() + ": " + group.getCount())); } finally { service.shutdown(); } } } ================================================ FILE: core/src/main/java/io/temporal/samples/standaloneactivities/ExecuteActivity.java ================================================ package io.temporal.samples.standaloneactivities; import static io.temporal.samples.standaloneactivities.StandaloneActivityWorker.TASK_QUEUE; import io.temporal.client.ActivityClient; import io.temporal.client.ActivityClientOptions; import io.temporal.client.StartActivityOptions; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import java.io.IOException; import java.time.Duration; /** * Executes a standalone activity and waits for the result. Requires a Worker running * StandaloneActivityWorker. */ public class ExecuteActivity { static final String ACTIVITY_ID = "standalone-activity-id"; public static void main(String[] args) throws IOException { ClientConfigProfile profile = ClientConfigProfile.load(); WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); ActivityClient client = ActivityClient.newInstance( service, ActivityClientOptions.newBuilder().setNamespace(profile.getNamespace()).build()); StartActivityOptions options = StartActivityOptions.newBuilder() .setId(ACTIVITY_ID) .setTaskQueue(TASK_QUEUE) .setStartToCloseTimeout(Duration.ofSeconds(10)) .build(); try { String result = client.execute( GreetingActivities.class, GreetingActivities::composeGreeting, options, "Hello", "World"); System.out.println("Activity result: " + result); } finally { service.shutdown(); } } } ================================================ FILE: core/src/main/java/io/temporal/samples/standaloneactivities/GreetingActivities.java ================================================ package io.temporal.samples.standaloneactivities; import io.temporal.activity.ActivityInterface; import io.temporal.activity.ActivityMethod; /** Activity interface shared by all programs in this sample. */ @ActivityInterface public interface GreetingActivities { @ActivityMethod String composeGreeting(String greeting, String name); } ================================================ FILE: core/src/main/java/io/temporal/samples/standaloneactivities/GreetingActivitiesImpl.java ================================================ package io.temporal.samples.standaloneactivities; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** Activity implementation. */ public class GreetingActivitiesImpl implements GreetingActivities { private static final Logger log = LoggerFactory.getLogger(GreetingActivitiesImpl.class); @Override public String composeGreeting(String greeting, String name) { log.info("Composing greeting..."); return greeting + ", " + name + "!"; } } ================================================ FILE: core/src/main/java/io/temporal/samples/standaloneactivities/ListActivities.java ================================================ package io.temporal.samples.standaloneactivities; import static io.temporal.samples.standaloneactivities.StandaloneActivityWorker.TASK_QUEUE; import io.temporal.client.ActivityClient; import io.temporal.client.ActivityClientOptions; import io.temporal.client.ActivityExecutionMetadata; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import java.io.IOException; import java.util.stream.Stream; /** Lists standalone activity executions on the task queue. */ public class ListActivities { public static void main(String[] args) throws IOException { ClientConfigProfile profile = ClientConfigProfile.load(); WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); ActivityClient client = ActivityClient.newInstance( service, ActivityClientOptions.newBuilder().setNamespace(profile.getNamespace()).build()); try (Stream activities = client.listExecutions("TaskQueue = '" + TASK_QUEUE + "'")) { activities.forEach( info -> System.out.printf( "ActivityID: %s, Type: %s, Status: %s%n", info.getActivityId(), info.getActivityType(), info.getStatus())); } finally { service.shutdown(); } } } ================================================ FILE: core/src/main/java/io/temporal/samples/standaloneactivities/README.md ================================================ # Standalone Activities This sample demonstrates [Standalone Activities](https://docs.temporal.io/develop/java/activities/standalone-activities), which run independently without being orchestrated by a Workflow. You start and manage them directly from a Temporal Client using `ActivityClient`. The sample has these separate programs: | Program | Purpose | |---|---| | `StandaloneActivityWorker` | Runs a Worker that processes activity tasks | | `ExecuteActivity` | Starts an activity and waits for its result | | `StartActivity` | Starts an activity without blocking, then waits for the result | | `ListActivities` | Lists activity executions on the task queue | | `CountActivities` | Counts activity executions on the task queue | ## Prerequisites - Temporal dev server with Standalone Activity support. See the [Java SDK Standalone Activities guide](https://docs.temporal.io/develop/java/activities/standalone-activities#get-started) for download instructions. ## Start the Temporal development server ```bash ./temporal server start-dev ``` ## Run the Worker In a terminal, start the Worker. Leave it running to process activities. ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.standaloneactivities.StandaloneActivityWorker ``` ## Execute a Standalone Activity In another terminal, execute an activity and wait for its result: ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.standaloneactivities.ExecuteActivity ``` Or use the Temporal CLI: ```bash ./temporal activity execute \ --type ComposeGreeting \ --activity-id standalone-activity-id \ --task-queue standalone-activity-task-queue \ --start-to-close-timeout 10s \ --input '"Hello"' \ --input '"World"' ``` ## Start a Standalone Activity without waiting Start an activity and retrieve its result separately: ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.standaloneactivities.StartActivity ``` Or use the Temporal CLI: ```bash ./temporal activity start \ --type ComposeGreeting \ --activity-id standalone-activity-id \ --task-queue standalone-activity-task-queue \ --start-to-close-timeout 10s \ --input '"Hello"' \ --input '"World"' ``` ## List Standalone Activities List activity executions on the task queue: ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.standaloneactivities.ListActivities ``` Or use the Temporal CLI: ```bash ./temporal activity list ``` ## Count Standalone Activities Count activity executions on the task queue: ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.standaloneactivities.CountActivities ``` Or use the Temporal CLI: ```bash ./temporal activity count ``` ================================================ FILE: core/src/main/java/io/temporal/samples/standaloneactivities/StandaloneActivityWorker.java ================================================ package io.temporal.samples.standaloneactivities; import io.temporal.client.WorkflowClient; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import java.io.IOException; /** * Worker that processes standalone activity tasks. Run this before executing or starting standalone * activities with ExecuteActivity or StartActivity. */ public class StandaloneActivityWorker { static final String TASK_QUEUE = "standalone-activity-task-queue"; public static void main(String[] args) throws IOException { ClientConfigProfile profile = ClientConfigProfile.load(); WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); WorkerFactory factory = WorkerFactory.newInstance(client); Worker worker = factory.newWorker(TASK_QUEUE); worker.registerActivitiesImplementations(new GreetingActivitiesImpl()); factory.start(); System.out.println("Worker running on task queue: " + TASK_QUEUE); } } ================================================ FILE: core/src/main/java/io/temporal/samples/standaloneactivities/StartActivity.java ================================================ package io.temporal.samples.standaloneactivities; import static io.temporal.samples.standaloneactivities.StandaloneActivityWorker.TASK_QUEUE; import io.temporal.client.ActivityClient; import io.temporal.client.ActivityClientOptions; import io.temporal.client.ActivityHandle; import io.temporal.client.StartActivityOptions; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import java.io.IOException; import java.time.Duration; /** * Starts a standalone activity without blocking, then waits for the result using the returned * handle. Requires a Worker running StandaloneActivityWorker. */ public class StartActivity { static final String ACTIVITY_ID = "standalone-activity-id"; public static void main(String[] args) throws IOException { ClientConfigProfile profile = ClientConfigProfile.load(); WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); ActivityClient client = ActivityClient.newInstance( service, ActivityClientOptions.newBuilder().setNamespace(profile.getNamespace()).build()); StartActivityOptions options = StartActivityOptions.newBuilder() .setId(ACTIVITY_ID) .setTaskQueue(TASK_QUEUE) .setStartToCloseTimeout(Duration.ofSeconds(10)) .build(); try { ActivityHandle handle = client.start( GreetingActivities.class, GreetingActivities::composeGreeting, options, "Hello", "World"); System.out.println("Started activity ID: " + ACTIVITY_ID); String result = handle.getResult(); System.out.println("Activity result: " + result); } finally { service.shutdown(); } } } ================================================ FILE: core/src/main/java/io/temporal/samples/terminateworkflow/MyWorkflow.java ================================================ package io.temporal.samples.terminateworkflow; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; @WorkflowInterface public interface MyWorkflow { @WorkflowMethod String execute(); } ================================================ FILE: core/src/main/java/io/temporal/samples/terminateworkflow/MyWorkflowImpl.java ================================================ package io.temporal.samples.terminateworkflow; import io.temporal.workflow.Workflow; import java.time.Duration; public class MyWorkflowImpl implements MyWorkflow { @Override public String execute() { // This workflow just sleeps Workflow.sleep(Duration.ofSeconds(20)); return "done"; } } ================================================ FILE: core/src/main/java/io/temporal/samples/terminateworkflow/README.md ================================================ # Terminate Workflow execution The sample demonstrates how to terminate Workflow Execution using the Client API. ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.terminateworkflow.Starter ``` ================================================ FILE: core/src/main/java/io/temporal/samples/terminateworkflow/Starter.java ================================================ package io.temporal.samples.terminateworkflow; import io.temporal.api.common.v1.WorkflowExecution; import io.temporal.api.workflow.v1.WorkflowExecutionInfo; import io.temporal.api.workflowservice.v1.DescribeWorkflowExecutionRequest; import io.temporal.api.workflowservice.v1.DescribeWorkflowExecutionResponse; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.client.WorkflowStub; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import java.io.IOException; import java.util.concurrent.TimeUnit; public class Starter { public static final String TASK_QUEUE = "terminateQueue"; public static void main(String[] args) { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); WorkerFactory factory = WorkerFactory.newInstance(client); // Create Worker createWorker(factory); // Create Workflow options WorkflowOptions workflowOptions = WorkflowOptions.newBuilder() .setWorkflowId("toTerminateWorkflow") .setTaskQueue(TASK_QUEUE) .build(); // Get the Workflow stub MyWorkflow myWorkflowStub = client.newWorkflowStub(MyWorkflow.class, workflowOptions); // Start workflow async WorkflowExecution execution = WorkflowClient.start(myWorkflowStub::execute); // Let it run for a couple of seconds sleepSeconds(2); // Terminate it WorkflowStub untyped = WorkflowStub.fromTyped(myWorkflowStub); untyped.terminate("Sample reason"); // Check workflow status, should be WORKFLOW_EXECUTION_STATUS_TERMINATED System.out.println("Status: " + getStatusAsString(execution, client, service)); System.exit(0); } /** This method creates a Worker from the factory. */ private static void createWorker(WorkerFactory factory) { Worker worker = factory.newWorker(TASK_QUEUE); worker.registerWorkflowImplementationTypes(MyWorkflowImpl.class); factory.start(); } /** * Convenience method to sleep for a number of seconds. * * @param seconds amount of seconds to sleep */ private static void sleepSeconds(int seconds) { try { Thread.sleep(TimeUnit.SECONDS.toMillis(seconds)); } catch (Exception e) { System.out.println("Exception: " + e.getMessage()); System.exit(0); } } /** * This method uses DescribeWorkflowExecutionRequest to get the status of a workflow given a * WorkflowExecution. * * @param execution workflow execution * @return Workflow status */ private static String getStatusAsString( WorkflowExecution execution, WorkflowClient client, WorkflowServiceStubs service) { DescribeWorkflowExecutionRequest describeWorkflowExecutionRequest = DescribeWorkflowExecutionRequest.newBuilder() .setNamespace(client.getOptions().getNamespace()) .setExecution(execution) .build(); DescribeWorkflowExecutionResponse resp = service.blockingStub().describeWorkflowExecution(describeWorkflowExecutionRequest); WorkflowExecutionInfo workflowExecutionInfo = resp.getWorkflowExecutionInfo(); return workflowExecutionInfo.getStatus().toString(); } } ================================================ FILE: core/src/main/java/io/temporal/samples/tracing/JaegerUtils.java ================================================ package io.temporal.samples.tracing; import io.jaegertracing.internal.JaegerTracer; import io.jaegertracing.internal.reporters.RemoteReporter; import io.jaegertracing.internal.samplers.ConstSampler; import io.jaegertracing.spi.Sampler; import io.jaegertracing.thrift.internal.senders.UdpSender; import io.opentelemetry.api.common.Attributes; import io.opentelemetry.api.trace.propagation.W3CTraceContextPropagator; import io.opentelemetry.context.propagation.ContextPropagators; import io.opentelemetry.context.propagation.TextMapPropagator; import io.opentelemetry.exporter.jaeger.JaegerGrpcSpanExporter; import io.opentelemetry.extension.trace.propagation.JaegerPropagator; import io.opentelemetry.opentracingshim.OpenTracingShim; import io.opentelemetry.sdk.OpenTelemetrySdk; import io.opentelemetry.sdk.resources.Resource; import io.opentelemetry.sdk.trace.SdkTracerProvider; import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor; import io.opentelemetry.semconv.resource.attributes.ResourceAttributes; import io.opentracing.Tracer; import io.temporal.opentracing.OpenTracingOptions; import io.temporal.opentracing.OpenTracingSpanContextCodec; import java.util.concurrent.TimeUnit; import org.apache.thrift.transport.TTransportException; public class JaegerUtils { public static OpenTracingOptions getJaegerOptions(String type) { if (type.equals("OpenTracing")) { return getJaegerOpenTracingOptions(); } // default to Open Telemetry return getJaegerOpenTelemetryOptions(); } private static OpenTracingOptions getJaegerOpenTracingOptions() { try { // Using Udp Sender for OpenTracing, make sure to change host and port // to your Jaeger options (if using different than in sample) RemoteReporter reporter = new RemoteReporter.Builder().withSender(new UdpSender("localhost", 5775, 0)).build(); Sampler sampler = new ConstSampler(true); Tracer tracer = new JaegerTracer.Builder("temporal-sample-opentracing") .withReporter(reporter) .withSampler(sampler) .build(); return getOpenTracingOptionsForTracer(tracer); } catch (TTransportException e) { System.out.println("Exception configuring Jaeger Tracer: " + e.getMessage()); return null; } } private static OpenTracingOptions getJaegerOpenTelemetryOptions() { Resource serviceNameResource = Resource.create( Attributes.of(ResourceAttributes.SERVICE_NAME, "temporal-sample-opentelemetry")); JaegerGrpcSpanExporter jaegerExporter = JaegerGrpcSpanExporter.builder() .setEndpoint("http://localhost:14250") .setTimeout(1, TimeUnit.SECONDS) .build(); SdkTracerProvider tracerProvider = SdkTracerProvider.builder() .addSpanProcessor(SimpleSpanProcessor.create(jaegerExporter)) .setResource(Resource.getDefault().merge(serviceNameResource)) .build(); OpenTelemetrySdk openTelemetry = OpenTelemetrySdk.builder() .setPropagators( ContextPropagators.create( TextMapPropagator.composite( W3CTraceContextPropagator.getInstance(), JaegerPropagator.getInstance()))) .setTracerProvider(tracerProvider) .build(); // create OpenTracing shim and return OpenTracing Tracer from it return getOpenTracingOptionsForTracer(OpenTracingShim.createTracerShim(openTelemetry)); } private static OpenTracingOptions getOpenTracingOptionsForTracer(Tracer tracer) { OpenTracingOptions options = OpenTracingOptions.newBuilder() .setSpanContextCodec(OpenTracingSpanContextCodec.TEXT_MAP_CODEC) .setTracer(tracer) .build(); return options; } } ================================================ FILE: core/src/main/java/io/temporal/samples/tracing/README.md ================================================ # Java SDK OpenTracing and OpenTelemetry Sample This sample shows the [Temporal Java SDK OpenTracing](https://github.com/temporalio/sdk-java/tree/master/temporal-opentracing) support. It shows how to set up OpenTracing, as well as OpenTelemetry. The sample uses the [CNCF Jaeger](https://github.com/jaegertracing/jaeger) distributed tracing platform. ## Run the sample Note, it is assumed that you have Temporal Server set up and running using Docker Compose. For more information on how to do this see the [main readme](../../../../../../../README.md). 1. Start Jaeger via Docker: ```bash docker run -d -p 5775:5775/udp -p 14250:14250 -p 16686:16686 -p 14268:14268 jaegertracing/all-in-one:latest ``` This starts Jaeger with udp port 5775 and grpc port 14250. Note that if these ports are different in your setup to reflect the changes in [JagerUtils](JaegerUtils.java). 1. Start the Worker: * For OpenTelemetry: ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.opentracing.TracingWorker ``` * For OpenTracing: ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.opentracing.TracingWorker --args="OpenTracing" ``` 2. Start the Starter * For OpenTelemetry ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.opentracing.Starter ``` * For OpenTracing ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.opentracing.Starter --args="OpenTracing" ``` 3. Go to your Jaeger UI on [http://127.0.0.1:16686/search](http://127.0.0.1:16686/search) 4. In the "Service" section select either "temporal-sample-opentelemetry" or "temporal-sample-opentracing", depending on your starting options. 5. Check out the Operation dropdown to see all the different operations available 6. In the Tags search input you can tag a specific workflow id, for example: ``` workflowId=tracingWorkflow ``` 7. Click on "Find Traces" in the Jager UI and see all look at all the spans info ================================================ FILE: core/src/main/java/io/temporal/samples/tracing/Starter.java ================================================ package io.temporal.samples.tracing; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowClientOptions; import io.temporal.client.WorkflowOptions; import io.temporal.client.WorkflowStub; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.opentracing.OpenTracingClientInterceptor; import io.temporal.samples.tracing.workflow.TracingWorkflow; import io.temporal.serviceclient.WorkflowServiceStubs; import java.io.IOException; public class Starter { public static final String TASK_QUEUE_NAME = "tracingTaskQueue"; public static void main(String[] args) { String type = "OpenTelemetry"; if (args.length == 1) { type = args[0]; } // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); // Set the OpenTracing client interceptor, preserving env config WorkflowClientOptions clientOptions = profile.toWorkflowClientOptions().toBuilder() .setInterceptors(new OpenTracingClientInterceptor(JaegerUtils.getJaegerOptions(type))) .build(); WorkflowClient client = WorkflowClient.newInstance(service, clientOptions); WorkflowOptions workflowOptions = WorkflowOptions.newBuilder() .setWorkflowId("tracingWorkflow") .setTaskQueue(TASK_QUEUE_NAME) .build(); // Create typed workflow stub TracingWorkflow workflow = client.newWorkflowStub(TracingWorkflow.class, workflowOptions); // Convert to untyped and start it with signalWithStart WorkflowStub untyped = WorkflowStub.fromTyped(workflow); untyped.signalWithStart("setLanguage", new Object[] {"Spanish"}, new Object[] {"John"}); String greeting = untyped.getResult(String.class); System.out.println("Greeting: " + greeting); System.exit(0); } } ================================================ FILE: core/src/main/java/io/temporal/samples/tracing/TracingWorker.java ================================================ package io.temporal.samples.tracing; import io.temporal.client.WorkflowClient; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.opentracing.OpenTracingWorkerInterceptor; import io.temporal.samples.tracing.workflow.TracingActivitiesImpl; import io.temporal.samples.tracing.workflow.TracingChildWorkflowImpl; import io.temporal.samples.tracing.workflow.TracingWorkflowImpl; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import io.temporal.worker.WorkerFactoryOptions; import java.io.IOException; public class TracingWorker { public static final String TASK_QUEUE_NAME = "tracingTaskQueue"; public static void main(String[] args) { String type = "OpenTelemetry"; if (args.length == 1) { type = args[0]; } // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); // Set the OpenTracing client interceptor WorkerFactoryOptions factoryOptions = WorkerFactoryOptions.newBuilder() .setWorkerInterceptors( new OpenTracingWorkerInterceptor(JaegerUtils.getJaegerOptions(type))) .build(); WorkerFactory factory = WorkerFactory.newInstance(client, factoryOptions); Worker worker = factory.newWorker(TASK_QUEUE_NAME); worker.registerWorkflowImplementationTypes( TracingWorkflowImpl.class, TracingChildWorkflowImpl.class); worker.registerActivitiesImplementations(new TracingActivitiesImpl()); factory.start(); } } ================================================ FILE: core/src/main/java/io/temporal/samples/tracing/workflow/TracingActivities.java ================================================ package io.temporal.samples.tracing.workflow; import io.temporal.activity.ActivityInterface; @ActivityInterface public interface TracingActivities { String greet(String name, String language); } ================================================ FILE: core/src/main/java/io/temporal/samples/tracing/workflow/TracingActivitiesImpl.java ================================================ package io.temporal.samples.tracing.workflow; public class TracingActivitiesImpl implements TracingActivities { @Override public String greet(String name, String language) { String greeting; switch (language) { case "Spanish": greeting = "Hola " + name; break; case "French": greeting = "Bonjour " + name; break; default: greeting = "Hello " + name; } return greeting; } } ================================================ FILE: core/src/main/java/io/temporal/samples/tracing/workflow/TracingChildWorkflow.java ================================================ package io.temporal.samples.tracing.workflow; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; @WorkflowInterface public interface TracingChildWorkflow { @WorkflowMethod String greet(String name, String language); } ================================================ FILE: core/src/main/java/io/temporal/samples/tracing/workflow/TracingChildWorkflowImpl.java ================================================ package io.temporal.samples.tracing.workflow; import io.temporal.activity.ActivityOptions; import io.temporal.workflow.Workflow; import java.time.Duration; public class TracingChildWorkflowImpl implements TracingChildWorkflow { @Override public String greet(String name, String language) { ActivityOptions activityOptions = ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(2)).build(); TracingActivities activities = Workflow.newActivityStub(TracingActivities.class, activityOptions); return activities.greet(name, language); } } ================================================ FILE: core/src/main/java/io/temporal/samples/tracing/workflow/TracingWorkflow.java ================================================ package io.temporal.samples.tracing.workflow; import io.temporal.workflow.QueryMethod; import io.temporal.workflow.SignalMethod; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; @WorkflowInterface public interface TracingWorkflow { @WorkflowMethod String greet(String name); @SignalMethod void setLanguage(String language); @QueryMethod String getLanguage(); } ================================================ FILE: core/src/main/java/io/temporal/samples/tracing/workflow/TracingWorkflowImpl.java ================================================ package io.temporal.samples.tracing.workflow; import io.temporal.workflow.ChildWorkflowOptions; import io.temporal.workflow.Workflow; public class TracingWorkflowImpl implements TracingWorkflow { private String language = "English"; @Override public String greet(String name) { ChildWorkflowOptions options = ChildWorkflowOptions.newBuilder().setWorkflowId("tracingChildWorkflow").build(); // Get the child workflow stub TracingChildWorkflow child = Workflow.newChildWorkflowStub(TracingChildWorkflow.class, options); // Invoke child sync and return its result return child.greet(name, language); } @Override public void setLanguage(String language) { this.language = language; } @Override public String getLanguage() { return language; } } ================================================ FILE: core/src/main/java/io/temporal/samples/updatabletimer/DynamicSleepWorkflow.java ================================================ package io.temporal.samples.updatabletimer; import io.temporal.workflow.QueryMethod; import io.temporal.workflow.SignalMethod; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; @WorkflowInterface public interface DynamicSleepWorkflow { @WorkflowMethod void execute(long wakeUpTime); @SignalMethod void updateWakeUpTime(long wakeUpTime); @QueryMethod long getWakeUpTime(); } ================================================ FILE: core/src/main/java/io/temporal/samples/updatabletimer/DynamicSleepWorkflowImpl.java ================================================ package io.temporal.samples.updatabletimer; public class DynamicSleepWorkflowImpl implements DynamicSleepWorkflow { private UpdatableTimer timer = new UpdatableTimer(); @Override public void execute(long wakeUpTime) { timer.sleepUntil(wakeUpTime); } @Override public void updateWakeUpTime(long wakeUpTime) { timer.updateWakeUpTime(wakeUpTime); } @Override public long getWakeUpTime() { return timer.getWakeUpTime(); } } ================================================ FILE: core/src/main/java/io/temporal/samples/updatabletimer/DynamicSleepWorkflowStarter.java ================================================ package io.temporal.samples.updatabletimer; import static io.temporal.samples.updatabletimer.DynamicSleepWorkflowWorker.DYNAMIC_SLEEP_WORKFLOW_ID; import static io.temporal.samples.updatabletimer.DynamicSleepWorkflowWorker.TASK_QUEUE; import io.temporal.api.common.v1.WorkflowExecution; import io.temporal.api.enums.v1.WorkflowIdReusePolicy; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowExecutionAlreadyStarted; import io.temporal.client.WorkflowOptions; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DynamicSleepWorkflowStarter { private static final Logger logger = LoggerFactory.getLogger(DynamicSleepWorkflowStarter.class); public static void main(String[] args) { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); DynamicSleepWorkflow workflow = client.newWorkflowStub( DynamicSleepWorkflow.class, WorkflowOptions.newBuilder() .setTaskQueue(TASK_QUEUE) .setWorkflowId(DYNAMIC_SLEEP_WORKFLOW_ID) .setWorkflowIdReusePolicy( WorkflowIdReusePolicy.WORKFLOW_ID_REUSE_POLICY_ALLOW_DUPLICATE) .build()); try { // Start asynchronously WorkflowExecution execution = WorkflowClient.start(workflow::execute, System.currentTimeMillis() + 60000); logger.info("Workflow started: " + execution); } catch (WorkflowExecutionAlreadyStarted e) { logger.info("Workflow already running: " + e.getExecution()); } } } ================================================ FILE: core/src/main/java/io/temporal/samples/updatabletimer/DynamicSleepWorkflowWorker.java ================================================ package io.temporal.samples.updatabletimer; import io.temporal.client.WorkflowClient; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DynamicSleepWorkflowWorker { static final String TASK_QUEUE = "TimerUpdate"; private static final Logger logger = LoggerFactory.getLogger(DynamicSleepWorkflowWorker.class); /** Create just one workflow instance for the sake of the sample. */ static final String DYNAMIC_SLEEP_WORKFLOW_ID = "DynamicSleepWorkflow"; public static void main(String[] args) { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); WorkerFactory factory = WorkerFactory.newInstance(client); final Worker worker = factory.newWorker(TASK_QUEUE); worker.registerWorkflowImplementationTypes(DynamicSleepWorkflowImpl.class); factory.start(); logger.info("Worker started for task queue: " + TASK_QUEUE); } } ================================================ FILE: core/src/main/java/io/temporal/samples/updatabletimer/README.md ================================================ # Updatable Timer Sample Demonstrates a helper class which relies on `Workflow.await` to implement a blocking sleep that can be updated at any moment. The sample is composed of the three executables: * `DynamicSleepWorkflowWorker` hosts the Workflow Executions. * `DynamicSleepWorkflowStarter` starts Workflow Executions. * `WakeUpTimeUpdater` Signals the Workflow Execution with the new time to wake up. First start the Worker: ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.updatabletimer.DynamicSleepWorkflowWorker ``` Then in a different terminal window start the Workflow Execution: ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.updatabletimer.DynamicSleepWorkflowStarter ``` Check the output of the Worker window. The expected output is: ``` [...] 11:39:08.852 [main] INFO i.t.s.u.DynamicSleepWorkflowWorker - Worker started for task queue: TimerUpdate 11:39:31.614 [workflow-method] INFO i.t.s.updatabletimer.UpdatableTimer - sleepUntil: 2021-11-30T19:40:30.979Z 11:39:31.615 [workflow-method] INFO i.t.s.updatabletimer.UpdatableTimer - Going to sleep for PT59.727S ``` Then run the updater as many times as you want to change timer to 10 seconds from now: ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.updatabletimer.WakeUpTimeUpdater ./gradlew -q execute -PmainClass=io.temporal.samples.updatabletimer.WakeUpTimeUpdater ``` Check the output of the worker window. The expected output is: ``` [...] 11:39:37.740 [signal updateWakeUpTime] INFO i.t.s.updatabletimer.UpdatableTimer - updateWakeUpTime: 2021-11-30T19:39:47.552Z 11:39:37.740 [workflow-method] INFO i.t.s.updatabletimer.UpdatableTimer - Going to sleep for PT9.841S 11:39:44.679 [signal updateWakeUpTime] INFO i.t.s.updatabletimer.UpdatableTimer - updateWakeUpTime: 2021-11-30T19:39:54.494Z 11:39:44.680 [workflow-method] INFO i.t.s.updatabletimer.UpdatableTimer - Going to sleep for PT9.838S 11:39:54.565 [workflow-method] INFO i.t.s.updatabletimer.UpdatableTimer - sleepUntil completed ``` ================================================ FILE: core/src/main/java/io/temporal/samples/updatabletimer/UpdatableTimer.java ================================================ package io.temporal.samples.updatabletimer; import io.temporal.workflow.Workflow; import java.time.Duration; import java.time.Instant; import org.slf4j.Logger; public final class UpdatableTimer { private final Logger logger = Workflow.getLogger(UpdatableTimer.class); private long wakeUpTime; private boolean wakeUpTimeUpdated; public void sleepUntil(long wakeUpTime) { logger.info("sleepUntil: " + Instant.ofEpochMilli(wakeUpTime)); this.wakeUpTime = wakeUpTime; while (true) { wakeUpTimeUpdated = false; Duration sleepInterval = Duration.ofMillis(this.wakeUpTime - Workflow.currentTimeMillis()); logger.info("Going to sleep for " + sleepInterval); if (!Workflow.await(sleepInterval, () -> wakeUpTimeUpdated)) { break; } } logger.info("sleepUntil completed"); } public void updateWakeUpTime(long wakeUpTime) { logger.info("updateWakeUpTime: " + Instant.ofEpochMilli(wakeUpTime)); this.wakeUpTime = wakeUpTime; this.wakeUpTimeUpdated = true; } public long getWakeUpTime() { return wakeUpTime; } } ================================================ FILE: core/src/main/java/io/temporal/samples/updatabletimer/WakeUpTimeUpdater.java ================================================ package io.temporal.samples.updatabletimer; import static io.temporal.samples.updatabletimer.DynamicSleepWorkflowWorker.DYNAMIC_SLEEP_WORKFLOW_ID; import io.temporal.client.WorkflowClient; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class WakeUpTimeUpdater { private static final Logger logger = LoggerFactory.getLogger(WakeUpTimeUpdater.class); public static void main(String[] args) { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); // Create a stub that points to an existing workflow with the given ID DynamicSleepWorkflow workflow = client.newWorkflowStub(DynamicSleepWorkflow.class, DYNAMIC_SLEEP_WORKFLOW_ID); // signal workflow about the wake up time change workflow.updateWakeUpTime(System.currentTimeMillis() + 10000); logger.info("Updated wake up time to 10 seconds from now"); } } ================================================ FILE: core/src/main/java/io/temporal/samples/workerversioning/Activities.java ================================================ package io.temporal.samples.workerversioning; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import io.temporal.activity.ActivityInterface; import io.temporal.activity.ActivityMethod; @ActivityInterface public interface Activities { @ActivityMethod String someActivity(String calledBy); @ActivityMethod String someIncompatibleActivity(IncompatibleActivityInput input); class IncompatibleActivityInput { private final String calledBy; private final String moreData; @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) public IncompatibleActivityInput( @JsonProperty("calledBy") String calledBy, @JsonProperty("moreData") String moreData) { this.calledBy = calledBy; this.moreData = moreData; } @JsonProperty("calledBy") public String getCalledBy() { return calledBy; } @JsonProperty("moreData") public String getMoreData() { return moreData; } } } ================================================ FILE: core/src/main/java/io/temporal/samples/workerversioning/ActivitiesImpl.java ================================================ package io.temporal.samples.workerversioning; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ActivitiesImpl implements Activities { private static final Logger logger = LoggerFactory.getLogger(ActivitiesImpl.class); @Override public String someActivity(String calledBy) { logger.info("SomeActivity called by {}", calledBy); return "SomeActivity called by " + calledBy; } @Override public String someIncompatibleActivity(IncompatibleActivityInput input) { logger.info( "SomeIncompatibleActivity called by {} with {}", input.getCalledBy(), input.getMoreData()); return "SomeIncompatibleActivity called by " + input.getCalledBy() + " with " + input.getMoreData(); } } ================================================ FILE: core/src/main/java/io/temporal/samples/workerversioning/AutoUpgradingWorkflow.java ================================================ package io.temporal.samples.workerversioning; import io.temporal.workflow.SignalMethod; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; @WorkflowInterface public interface AutoUpgradingWorkflow { @WorkflowMethod void run(); @SignalMethod void doNextSignal(String signal); } ================================================ FILE: core/src/main/java/io/temporal/samples/workerversioning/AutoUpgradingWorkflowV1Impl.java ================================================ package io.temporal.samples.workerversioning; import io.temporal.activity.ActivityOptions; import io.temporal.common.VersioningBehavior; import io.temporal.workflow.Workflow; import io.temporal.workflow.WorkflowVersioningBehavior; import java.time.Duration; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; /** * This workflow will automatically move to the latest worker version. We'll be making changes to * it, which must be replay safe. Note that generally you won't want or need to include a version * number in your workflow name if you're using the worker versioning feature. This sample does it * to illustrate changes to the same code over time - but really what we're demonstrating here is * the evolution of what would have been one workflow definition. */ public class AutoUpgradingWorkflowV1Impl implements AutoUpgradingWorkflow { private static final Logger logger = Workflow.getLogger(AutoUpgradingWorkflowV1Impl.class); private final List signals = new ArrayList<>(); private final Activities activities = Workflow.newActivityStub( Activities.class, ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(10)).build()); @Override @WorkflowVersioningBehavior(VersioningBehavior.AUTO_UPGRADE) public void run() { logger.info("Changing workflow v1 started. StartTime: {}", Workflow.currentTimeMillis()); while (true) { Workflow.await(() -> !signals.isEmpty()); String signal = signals.remove(0); if ("do-activity".equals(signal)) { logger.info("Changing workflow v1 running activity"); activities.someActivity("v1"); } else { logger.info("Concluding workflow v1"); return; } } } @Override public void doNextSignal(String signal) { signals.add(signal); } } ================================================ FILE: core/src/main/java/io/temporal/samples/workerversioning/AutoUpgradingWorkflowV1bImpl.java ================================================ package io.temporal.samples.workerversioning; import io.temporal.activity.ActivityOptions; import io.temporal.common.VersioningBehavior; import io.temporal.workflow.Workflow; import io.temporal.workflow.WorkflowVersioningBehavior; import java.time.Duration; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; /** * This represents us having made *compatible* changes to AutoUpgradingWorkflowV1Impl. * *

The compatible changes we've made are: * *

    *
  • Altering the log lines *
  • Using the `Workflow.getVersion` API to properly introduce branching behavior while * maintaining compatibility *
*/ public class AutoUpgradingWorkflowV1bImpl implements AutoUpgradingWorkflow { private static final Logger logger = Workflow.getLogger(AutoUpgradingWorkflowV1bImpl.class); private final List signals = new ArrayList<>(); private final Activities activities = Workflow.newActivityStub( Activities.class, ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(10)).build()); @Override @WorkflowVersioningBehavior(VersioningBehavior.AUTO_UPGRADE) public void run() { logger.info("Changing workflow v1b started. StartTime: {}", Workflow.currentTimeMillis()); while (true) { Workflow.await(() -> !signals.isEmpty()); String signal = signals.remove(0); if ("do-activity".equals(signal)) { logger.info("Changing workflow v1b running activity"); int version = Workflow.getVersion("DifferentActivity", Workflow.DEFAULT_VERSION, 1); if (version == 1) { activities.someIncompatibleActivity( new Activities.IncompatibleActivityInput("v1b", "hello!")); } else { // Note it is a valid compatible change to alter the input to an activity. // However, because we're using the getVersion API, this branch will never be // taken. activities.someActivity("v1b"); } } else { logger.info("Concluding workflow v1b"); break; } } } @Override public void doNextSignal(String signal) { signals.add(signal); } } ================================================ FILE: core/src/main/java/io/temporal/samples/workerversioning/PinnedWorkflow.java ================================================ package io.temporal.samples.workerversioning; import io.temporal.workflow.SignalMethod; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; @WorkflowInterface public interface PinnedWorkflow { @WorkflowMethod void run(); @SignalMethod void doNextSignal(String signal); } ================================================ FILE: core/src/main/java/io/temporal/samples/workerversioning/PinnedWorkflowV1Impl.java ================================================ package io.temporal.samples.workerversioning; import io.temporal.activity.ActivityOptions; import io.temporal.common.VersioningBehavior; import io.temporal.workflow.Workflow; import io.temporal.workflow.WorkflowVersioningBehavior; import java.time.Duration; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; /** * This workflow represents one that likely has a short lifetime, and we want to always stay pinned * to the same version it began on. Note that generally you won't want or need to include a version * number in your workflow name if you're using the worker versioning feature. This sample does it * to illustrate changes to the same code over time - but really what we're demonstrating here is * the evolution of what would have been one workflow definition. */ public class PinnedWorkflowV1Impl implements PinnedWorkflow { private static final Logger logger = Workflow.getLogger(PinnedWorkflowV1Impl.class); private final List signals = new ArrayList<>(); private final Activities activities = Workflow.newActivityStub( Activities.class, ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(10)).build()); @Override @WorkflowVersioningBehavior(VersioningBehavior.PINNED) public void run() { logger.info("Pinned Workflow v1 started. StartTime: {}", Workflow.currentTimeMillis()); while (true) { Workflow.await(() -> !signals.isEmpty()); String signal = signals.remove(0); if ("conclude".equals(signal)) { break; } } activities.someActivity("Pinned-v1"); } @Override public void doNextSignal(String signal) { signals.add(signal); } } ================================================ FILE: core/src/main/java/io/temporal/samples/workerversioning/PinnedWorkflowV2Impl.java ================================================ package io.temporal.samples.workerversioning; import io.temporal.activity.ActivityOptions; import io.temporal.common.VersioningBehavior; import io.temporal.workflow.Workflow; import io.temporal.workflow.WorkflowVersioningBehavior; import java.time.Duration; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; /** * This workflow has changes that would make it incompatible with v1, and aren't protected by a * patch. */ public class PinnedWorkflowV2Impl implements PinnedWorkflow { private static final Logger logger = Workflow.getLogger(PinnedWorkflowV2Impl.class); private final List signals = new ArrayList<>(); private final Activities activities = Workflow.newActivityStub( Activities.class, ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(10)).build()); @Override @WorkflowVersioningBehavior(VersioningBehavior.PINNED) public void run() { logger.info("Pinned Workflow v2 started. StartTime: {}", Workflow.currentTimeMillis()); // Here we call an activity where we didn't before, which is an incompatible change. activities.someActivity("Pinned-v2"); while (true) { Workflow.await(() -> !signals.isEmpty()); String signal = signals.remove(0); if ("conclude".equals(signal)) { break; } } // We've also changed the activity type here, another incompatible change activities.someIncompatibleActivity( new Activities.IncompatibleActivityInput("Pinned-v2", "hi")); } @Override public void doNextSignal(String signal) { signals.add(signal); } } ================================================ FILE: core/src/main/java/io/temporal/samples/workerversioning/README.md ================================================ # Worker Versioning This sample demonstrates how to use Temporal's Worker Versioning feature to safely deploy updates to workflow and activity code. It shows the difference between auto-upgrading and pinned workflows, and how to manage worker deployments with different build IDs. The sample creates multiple worker versions (1.0, 1.1, and 2.0) within one deployment and demonstrates: - **Auto-upgrading workflows**: Automatically and controllably migrate to newer worker versions - **Pinned workflows**: Stay on the original worker version throughout their lifecycle - **Compatible vs incompatible changes**: How to make safe updates using `Workflow.getVersion` ## Steps to run this sample: 1) Run a [Temporal service](https://github.com/temporalio/samples-java/tree/main/#how-to-use). And ensure that you're using at least Server version 1.28.0 (CLI version 1.4.0). 2) Start the main application (this will guide you through the sample): ```bash ./gradlew -q execute -PmainClass=io.temporal.samples.workerversioning.Starter ``` 3) Follow the prompts to start workers in separate terminals: - When prompted, run: `./gradlew -q execute -PmainClass=io.temporal.samples.workerversioning.WorkerV1` - When prompted, run: `./gradlew -q execute -PmainClass=io.temporal.samples.workerversioning.WorkerV1_1` - When prompted, run: `./gradlew -q execute -PmainClass=io.temporal.samples.workerversioning.WorkerV2` Follow the prompts in the example to observe auto-upgrading workflows migrating to newer workers while pinned workflows remain on their original versions. ================================================ FILE: core/src/main/java/io/temporal/samples/workerversioning/Starter.java ================================================ package io.temporal.samples.workerversioning; import io.temporal.api.workflowservice.v1.DescribeWorkerDeploymentRequest; import io.temporal.api.workflowservice.v1.DescribeWorkerDeploymentResponse; import io.temporal.api.workflowservice.v1.SetWorkerDeploymentCurrentVersionRequest; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.client.WorkflowStub; import io.temporal.common.WorkerDeploymentVersion; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import java.io.IOException; import java.util.UUID; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Starter { public static final String TASK_QUEUE = "worker-versioning"; public static final String DEPLOYMENT_NAME = "my-deployment"; private static final Logger logger = LoggerFactory.getLogger(Starter.class); public static void main(String[] args) throws Exception { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); // Wait for v1 worker and set as current version logger.info( "Waiting for v1 worker to appear. Run `./gradlew -q execute -PmainClass=io.temporal.samples.workerversioning.WorkerV1` in another terminal"); waitForWorkerAndMakeCurrent(client, service, "1.0"); // Start auto-upgrading and pinned workflows. Importantly, note that when we start the // workflows, // we are using a workflow type name which does *not* include the version number. We defined // them // with versioned names so we could show changes to the code, but here when the client invokes // them, we're demonstrating that the client remains version-agnostic. String autoUpgradeWorkflowId = "worker-versioning-versioning-autoupgrade_" + UUID.randomUUID(); WorkflowStub autoUpgradeExecution = client.newUntypedWorkflowStub( "AutoUpgradingWorkflow", WorkflowOptions.newBuilder() .setWorkflowId(autoUpgradeWorkflowId) .setTaskQueue(TASK_QUEUE) .build()); String pinnedWorkflowId = "worker-versioning-versioning-pinned_" + UUID.randomUUID(); WorkflowStub pinnedExecution = client.newUntypedWorkflowStub( "PinnedWorkflow", WorkflowOptions.newBuilder() .setWorkflowId(pinnedWorkflowId) .setTaskQueue(TASK_QUEUE) .build()); // Start workflows asynchronously autoUpgradeExecution.start(); pinnedExecution.start(); logger.info( "Started auto-upgrading workflow: {}", autoUpgradeExecution.getExecution().getWorkflowId()); logger.info("Started pinned workflow: {}", pinnedExecution.getExecution().getWorkflowId()); // Signal both workflows a few times to drive them advanceWorkflows(autoUpgradeExecution, pinnedExecution); // Now wait for the v1.1 worker to appear and become current logger.info( "Waiting for v1.1 worker to appear. Run `./gradlew -q execute -PmainClass=io.temporal.samples.workerversioning.WorkerV1_1` in another terminal"); waitForWorkerAndMakeCurrent(client, service, "1.1"); // Once it has, we will continue to advance the workflows. // The auto-upgrade workflow will now make progress on the new worker, while the pinned one will // keep progressing on the old worker. advanceWorkflows(autoUpgradeExecution, pinnedExecution); // Finally we'll start the v2 worker, and again it'll become the new current version logger.info( "Waiting for v2 worker to appear. Run `./gradlew -q execute -PmainClass=io.temporal.samples.workerversioning.WorkerV2` in another terminal"); waitForWorkerAndMakeCurrent(client, service, "2.0"); // Once it has we'll start one more new workflow, another pinned one, to demonstrate that new // pinned workflows start on the current version. String pinnedWorkflow2Id = "worker-versioning-versioning-pinned-2_" + UUID.randomUUID(); WorkflowStub pinnedExecution2 = client.newUntypedWorkflowStub( "PinnedWorkflow", WorkflowOptions.newBuilder() .setWorkflowId(pinnedWorkflow2Id) .setTaskQueue(TASK_QUEUE) .build()); pinnedExecution2.start(); logger.info("Started pinned workflow v2: {}", pinnedExecution2.getExecution().getWorkflowId()); // Now we'll conclude all workflows. You should be able to see in your server UI that the pinned // workflow always stayed on 1.0, while the auto-upgrading workflow migrated. autoUpgradeExecution.signal("doNextSignal", "conclude"); pinnedExecution.signal("doNextSignal", "conclude"); pinnedExecution2.signal("doNextSignal", "conclude"); // Wait for all workflows to complete autoUpgradeExecution.getResult(Void.class); pinnedExecution.getResult(Void.class); pinnedExecution2.getResult(Void.class); logger.info("All workflows completed"); } private static void advanceWorkflows( WorkflowStub autoUpgradeExecution, WorkflowStub pinnedExecution) { // Signal both workflows a few times to drive them for (int i = 0; i < 3; i++) { autoUpgradeExecution.signal("doNextSignal", "do-activity"); pinnedExecution.signal("doNextSignal", "some-signal"); } } private static void waitForWorkerAndMakeCurrent( WorkflowClient client, WorkflowServiceStubs service, String buildId) throws InterruptedException { WorkerDeploymentVersion targetVersion = new WorkerDeploymentVersion(DEPLOYMENT_NAME, buildId); // Wait for the worker to appear while (true) { try { DescribeWorkerDeploymentRequest describeRequest = DescribeWorkerDeploymentRequest.newBuilder() .setNamespace(client.getOptions().getNamespace()) .setDeploymentName(DEPLOYMENT_NAME) .build(); DescribeWorkerDeploymentResponse response = service.blockingStub().describeWorkerDeployment(describeRequest); // Check if our version is present in the version summaries boolean found = response.getWorkerDeploymentInfo().getVersionSummariesList().stream() .anyMatch( versionSummary -> targetVersion .getDeploymentName() .equals(versionSummary.getDeploymentVersion().getDeploymentName()) && targetVersion .getBuildId() .equals(versionSummary.getDeploymentVersion().getBuildId())); if (found) { break; } } catch (Exception ignored) { System.out.println(); } Thread.sleep(1000); } // Once the version is available, set it as current SetWorkerDeploymentCurrentVersionRequest setRequest = SetWorkerDeploymentCurrentVersionRequest.newBuilder() .setNamespace(client.getOptions().getNamespace()) .setDeploymentName(DEPLOYMENT_NAME) .setBuildId(targetVersion.getBuildId()) .build(); service.blockingStub().setWorkerDeploymentCurrentVersion(setRequest); } } ================================================ FILE: core/src/main/java/io/temporal/samples/workerversioning/WorkerV1.java ================================================ package io.temporal.samples.workerversioning; import io.temporal.client.WorkflowClient; import io.temporal.common.WorkerDeploymentVersion; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerDeploymentOptions; import io.temporal.worker.WorkerFactory; import io.temporal.worker.WorkerOptions; import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class WorkerV1 { private static final Logger logger = LoggerFactory.getLogger(WorkerV1.class); public static void main(String[] args) { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); WorkerDeploymentVersion version = new WorkerDeploymentVersion(Starter.DEPLOYMENT_NAME, "1.0"); WorkerDeploymentOptions deploymentOptions = WorkerDeploymentOptions.newBuilder().setUseVersioning(true).setVersion(version).build(); WorkerOptions workerOptions = WorkerOptions.newBuilder().setDeploymentOptions(deploymentOptions).build(); WorkerFactory factory = WorkerFactory.newInstance(client); Worker worker = factory.newWorker(Starter.TASK_QUEUE, workerOptions); worker.registerWorkflowImplementationTypes( AutoUpgradingWorkflowV1Impl.class, PinnedWorkflowV1Impl.class); worker.registerActivitiesImplementations(new ActivitiesImpl()); logger.info("Starting worker v1 (build 1.0)"); factory.start(); } } ================================================ FILE: core/src/main/java/io/temporal/samples/workerversioning/WorkerV1_1.java ================================================ package io.temporal.samples.workerversioning; import io.temporal.client.WorkflowClient; import io.temporal.common.WorkerDeploymentVersion; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerDeploymentOptions; import io.temporal.worker.WorkerFactory; import io.temporal.worker.WorkerOptions; import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class WorkerV1_1 { private static final Logger logger = LoggerFactory.getLogger(WorkerV1_1.class); public static void main(String[] args) { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); WorkerDeploymentVersion version = new WorkerDeploymentVersion(Starter.DEPLOYMENT_NAME, "1.1"); WorkerDeploymentOptions deploymentOptions = WorkerDeploymentOptions.newBuilder().setUseVersioning(true).setVersion(version).build(); WorkerOptions workerOptions = WorkerOptions.newBuilder().setDeploymentOptions(deploymentOptions).build(); WorkerFactory factory = WorkerFactory.newInstance(client); Worker worker = factory.newWorker(Starter.TASK_QUEUE, workerOptions); worker.registerWorkflowImplementationTypes( AutoUpgradingWorkflowV1bImpl.class, PinnedWorkflowV1Impl.class); worker.registerActivitiesImplementations(new ActivitiesImpl()); logger.info("Starting worker v1.1 (build 1.1)"); factory.start(); } } ================================================ FILE: core/src/main/java/io/temporal/samples/workerversioning/WorkerV2.java ================================================ package io.temporal.samples.workerversioning; import io.temporal.client.WorkflowClient; import io.temporal.common.WorkerDeploymentVersion; import io.temporal.envconfig.ClientConfigProfile; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.worker.Worker; import io.temporal.worker.WorkerDeploymentOptions; import io.temporal.worker.WorkerFactory; import io.temporal.worker.WorkerOptions; import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class WorkerV2 { private static final Logger logger = LoggerFactory.getLogger(WorkerV2.class); public static void main(String[] args) { // Load configuration from environment and files ClientConfigProfile profile; try { profile = ClientConfigProfile.load(); } catch (IOException e) { throw new RuntimeException("Failed to load client configuration", e); } WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions()); WorkflowClient client = WorkflowClient.newInstance(service, profile.toWorkflowClientOptions()); WorkerDeploymentVersion version = new WorkerDeploymentVersion(Starter.DEPLOYMENT_NAME, "2.0"); WorkerDeploymentOptions deploymentOptions = WorkerDeploymentOptions.newBuilder().setUseVersioning(true).setVersion(version).build(); WorkerOptions workerOptions = WorkerOptions.newBuilder().setDeploymentOptions(deploymentOptions).build(); WorkerFactory factory = WorkerFactory.newInstance(client); Worker worker = factory.newWorker(Starter.TASK_QUEUE, workerOptions); worker.registerWorkflowImplementationTypes( AutoUpgradingWorkflowV1bImpl.class, PinnedWorkflowV2Impl.class); worker.registerActivitiesImplementations(new ActivitiesImpl()); logger.info("Starting worker v2 (build 2.0)"); factory.start(); } } ================================================ FILE: core/src/main/resources/config.toml ================================================ # This is a sample configuration file for demonstrating Temporal's environment # configuration feature. It defines multiple profiles for different environments, # such as local development, production, and staging. # Default profile for local development [profile.default] address = "localhost:7233" namespace = "default" # Optional: Add custom gRPC headers [profile.default.grpc_meta] my-custom-header = "development-value" trace-id = "dev-trace-123" # Staging profile with inline certificate data [profile.staging] address = "localhost:9999" namespace = "staging" # Nexus messaging sample profiles [profile.nexus-messaging-handler] address = "localhost:7233" namespace = "nexus-messaging-handler-namespace" [profile.nexus-messaging-caller] address = "localhost:7233" namespace = "nexus-messaging-caller-namespace" # An example production profile for Temporal Cloud [profile.prod] address = "your-namespace.a1b2c.tmprl.cloud:7233" namespace = "your-namespace" # Replace with your actual Temporal Cloud API key api_key = "your-api-key-here" # TLS configuration for production [profile.prod.tls] # TLS is auto-enabled when an API key is present, but you can configure it # explicitly. # disabled = false # Use certificate files for mTLS. Replace with actual paths. client_cert_path = "/etc/temporal/certs/client.pem" client_key_path = "/etc/temporal/certs/client.key" # Custom headers for production [profile.prod.grpc_meta] environment = "production" service-version = "v1.2.3" ================================================ FILE: core/src/main/resources/dsl/sampleflow.json ================================================ { "id": "sampleFlow", "name": "Sample Flow One", "description": "Sample Flow Definition", "actions": [ { "action": "One", "retries": 10, "startToCloseSec": 3 }, { "action": "Two", "retries": 8, "startToCloseSec": 3 }, { "action": "Three", "retries": 10, "startToCloseSec": 4 }, { "action": "Four", "retries": 9, "startToCloseSec": 5 } ] } ================================================ FILE: core/src/main/resources/logback.xml ================================================ %d{HH:mm:ss.SSS} {%X{WorkflowId} %X{ActivityId}} [%thread] %-5level %logger{36} - %msg %n ================================================ FILE: core/src/test/java/io/temporal/samples/asyncchild/AsyncChildTest.java ================================================ package io.temporal.samples.asyncchild; import static org.junit.Assert.assertNotNull; import io.temporal.api.common.v1.WorkflowExecution; import io.temporal.client.WorkflowOptions; import io.temporal.testing.TestWorkflowRule; import org.junit.Rule; import org.junit.Test; public class AsyncChildTest { @Rule public TestWorkflowRule testWorkflowRule = TestWorkflowRule.newBuilder() .setWorkflowTypes(ParentWorkflowImpl.class, ChildWorkflowImpl.class) .build(); @Test public void testAsyncChildWorkflow() { ParentWorkflow parentWorkflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub( ParentWorkflow.class, WorkflowOptions.newBuilder().setTaskQueue(testWorkflowRule.getTaskQueue()).build()); WorkflowExecution childExecution = parentWorkflow.executeParent(); assertNotNull(childExecution); } } ================================================ FILE: core/src/test/java/io/temporal/samples/asyncuntypedchild/AsyncUntypedChildTest.java ================================================ package io.temporal.samples.asyncuntypedchild; import static io.temporal.api.enums.v1.WorkflowExecutionStatus.WORKFLOW_EXECUTION_STATUS_RUNNING; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.mockito.Mockito.*; import io.temporal.api.common.v1.WorkflowExecution; import io.temporal.api.enums.v1.WorkflowExecutionStatus; import io.temporal.api.workflowservice.v1.DescribeWorkflowExecutionRequest; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.testing.TestWorkflowRule; import org.jetbrains.annotations.NotNull; import org.junit.Rule; import org.junit.Test; /** Unit test for {@link ParentWorkflowImpl}. Doesn't use an external Temporal service. */ public class AsyncUntypedChildTest { @Rule public TestWorkflowRule testWorkflowRule = TestWorkflowRule.newBuilder().setDoNotStart(true).build(); @Test public void testMockedChild() { testWorkflowRule.getWorker().registerWorkflowImplementationTypes(ParentWorkflowImpl.class); // Factory is called to create a new workflow object on each workflow task. testWorkflowRule .getWorker() .registerWorkflowImplementationFactory( ChildWorkflow.class, () -> { ChildWorkflow child = mock(ChildWorkflow.class); when(child.composeGreeting("Hello", "World")) .thenReturn("Hello World from mocked child!"); return child; }); testWorkflowRule.getTestEnvironment().start(); // Get a workflow stub using the same task queue the worker uses. WorkflowClient workflowClient = testWorkflowRule.getWorkflowClient(); ParentWorkflow workflow = workflowClient.newWorkflowStub( ParentWorkflow.class, WorkflowOptions.newBuilder().setTaskQueue(testWorkflowRule.getTaskQueue()).build()); // Execute the parent workflow and wait for it to complete. String childWorkflowId = workflow.getGreeting("World"); assertNotNull(childWorkflowId); assertEquals( WORKFLOW_EXECUTION_STATUS_RUNNING, getChildWorkflowExecutionStatus(workflowClient, childWorkflowId)); // Wait for the child to complete String childResult = workflowClient.newUntypedWorkflowStub(childWorkflowId).getResult(String.class); assertEquals("Hello World from mocked child!", childResult); testWorkflowRule.getTestEnvironment().shutdown(); } @NotNull private WorkflowExecutionStatus getChildWorkflowExecutionStatus( WorkflowClient workflowClient, String childWorkflowId) { return workflowClient .getWorkflowServiceStubs() .blockingStub() .describeWorkflowExecution( DescribeWorkflowExecutionRequest.newBuilder() .setNamespace(testWorkflowRule.getTestEnvironment().getNamespace()) .setExecution(WorkflowExecution.newBuilder().setWorkflowId(childWorkflowId).build()) .build()) .getWorkflowExecutionInfo() .getStatus(); } } ================================================ FILE: core/src/test/java/io/temporal/samples/batch/heartbeatingactivity/HeartbeatingActivityBatchWorkflowTest.java ================================================ package io.temporal.samples.batch.heartbeatingactivity; import static io.temporal.samples.batch.heartbeatingactivity.RecordLoaderImpl.RECORD_COUNT; import static org.junit.Assert.assertTrue; import io.temporal.testing.TestWorkflowRule; import org.junit.Rule; import org.junit.Test; public class HeartbeatingActivityBatchWorkflowTest { private static boolean[] processedRecords = new boolean[RECORD_COUNT]; public static class TestRecordProcessorImpl implements RecordProcessor { @Override public void processRecord(SingleRecord r) { processedRecords[r.getId()] = true; } } @Rule public TestWorkflowRule testWorkflowRule = TestWorkflowRule.newBuilder() .setWorkflowTypes(HeartbeatingActivityBatchWorkflowImpl.class) .setActivityImplementations( new RecordProcessorActivityImpl( new RecordLoaderImpl(), new TestRecordProcessorImpl())) .build(); @Test public void testBatchWorkflow() { HeartbeatingActivityBatchWorkflow workflow = testWorkflowRule.newWorkflowStub(HeartbeatingActivityBatchWorkflow.class); workflow.processBatch(); for (int i = 0; i < processedRecords.length; i++) { assertTrue(processedRecords[i]); } } } ================================================ FILE: core/src/test/java/io/temporal/samples/batch/iterator/IteratorIteratorBatchWorkflowTest.java ================================================ package io.temporal.samples.batch.iterator; import static io.temporal.samples.batch.iterator.RecordLoaderImpl.PAGE_COUNT; import static org.junit.Assert.assertTrue; import io.temporal.testing.TestWorkflowRule; import io.temporal.workflow.Workflow; import org.junit.Rule; import org.junit.Test; public class IteratorIteratorBatchWorkflowTest { private static final int PAGE_SIZE = 10; /** The sample RecordLoaderImpl always returns the fixed number pages. */ private static boolean[] processedRecords = new boolean[PAGE_SIZE * PAGE_COUNT]; public static class TestRecordProcessorWorkflowImpl implements RecordProcessorWorkflow { @Override public void processRecord(SingleRecord r) { Workflow.sleep(5000); processedRecords[r.getId()] = true; } } @Rule public TestWorkflowRule testWorkflowRule = TestWorkflowRule.newBuilder() .setWorkflowTypes(IteratorBatchWorkflowImpl.class, TestRecordProcessorWorkflowImpl.class) .setActivityImplementations(new RecordLoaderImpl()) .build(); @Test public void testBatchWorkflow() { IteratorBatchWorkflow workflow = testWorkflowRule.newWorkflowStub(IteratorBatchWorkflow.class); workflow.processBatch(PAGE_SIZE, 0); for (int i = 0; i < processedRecords.length; i++) { assertTrue(processedRecords[i]); } } } ================================================ FILE: core/src/test/java/io/temporal/samples/batch/slidingwindow/SlidingWindowBatchWorkflowTest.java ================================================ package io.temporal.samples.batch.slidingwindow; import static org.junit.Assert.assertTrue; import io.temporal.testing.TestWorkflowRule; import io.temporal.workflow.Workflow; import io.temporal.workflow.WorkflowInfo; import org.junit.Rule; import org.junit.Test; public class SlidingWindowBatchWorkflowTest { private static final int RECORD_COUNT = 15; private static boolean[] processedRecords = new boolean[RECORD_COUNT]; public static class TestRecordProcessorWorkflowImpl implements RecordProcessorWorkflow { @Override public void processRecord(SingleRecord r) { processedRecords[r.getId()] = true; WorkflowInfo info = Workflow.getInfo(); String parentId = info.getParentWorkflowId().get(); SlidingWindowBatchWorkflow parent = Workflow.newExternalWorkflowStub(SlidingWindowBatchWorkflow.class, parentId); Workflow.sleep(500); // Notify parent about record processing completion // Needs to retry due to a continue-as-new atomicity // bug in the testservice: // https://github.com/temporalio/sdk-java/issues/1538 while (true) { try { parent.reportCompletion(r.getId()); break; } catch (Exception e) { continue; } } } } @Rule public TestWorkflowRule testWorkflowRule = TestWorkflowRule.newBuilder() .setWorkflowTypes( SlidingWindowBatchWorkflowImpl.class, TestRecordProcessorWorkflowImpl.class) .setActivityImplementations(new RecordLoaderImpl()) .build(); @Test public void testSlidingWindowBatchWorkflow() { SlidingWindowBatchWorkflow workflow = testWorkflowRule.newWorkflowStub(SlidingWindowBatchWorkflow.class); ProcessBatchInput input = new ProcessBatchInput(); input.setPageSize(3); input.setSlidingWindowSize(7); input.setOffset(0); input.setMaximumOffset(RECORD_COUNT); workflow.processBatch(input); for (int i = 0; i < RECORD_COUNT; i++) { assertTrue(processedRecords[i]); } } } ================================================ FILE: core/src/test/java/io/temporal/samples/bookingsaga/TripBookingWorkflowTest.java ================================================ package io.temporal.samples.bookingsaga; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import io.temporal.client.WorkflowException; import io.temporal.failure.ApplicationFailure; import io.temporal.testing.TestWorkflowEnvironment; import io.temporal.testing.TestWorkflowExtension; import io.temporal.worker.Worker; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import org.mockito.ArgumentCaptor; public class TripBookingWorkflowTest { @RegisterExtension public static final TestWorkflowExtension testWorkflowExtension = TestWorkflowExtension.newBuilder() .setWorkflowTypes(TripBookingWorkflowImpl.class) .setDoNotStart(true) .build(); /** * Not very useful test that validates that the default activities cause workflow to fail. See * other tests on using mocked activities to test SAGA logic. */ @Test public void testTripBookingFails( TestWorkflowEnvironment testEnv, Worker worker, TripBookingWorkflow workflow) { worker.registerActivitiesImplementations(new TripBookingActivitiesImpl()); testEnv.start(); WorkflowException exception = assertThrows(WorkflowException.class, () -> workflow.bookTrip("trip1")); assertEquals( "Flight booking did not work", ((ApplicationFailure) exception.getCause().getCause()).getOriginalMessage()); } /** Unit test workflow logic using mocked activities. */ @Test public void testSAGA( TestWorkflowEnvironment testEnv, Worker worker, TripBookingWorkflow workflow) { TripBookingActivities activities = mock(TripBookingActivities.class); ArgumentCaptor captorHotelRequestId = ArgumentCaptor.forClass(String.class); when(activities.bookHotel(captorHotelRequestId.capture(), eq("trip1"))) .thenReturn("HotelBookingID1"); ArgumentCaptor captorCarRequestId = ArgumentCaptor.forClass(String.class); when(activities.reserveCar(captorCarRequestId.capture(), eq("trip1"))) .thenReturn("CarBookingID1"); ArgumentCaptor captorFlightRequestId = ArgumentCaptor.forClass(String.class); when(activities.bookFlight(captorFlightRequestId.capture(), eq("trip1"))) .thenThrow( ApplicationFailure.newNonRetryableFailure( "Flight booking did not work", "bookingFailure")); worker.registerActivitiesImplementations(activities); testEnv.start(); WorkflowException exception = assertThrows(WorkflowException.class, () -> workflow.bookTrip("trip1")); assertEquals( "Flight booking did not work", ((ApplicationFailure) exception.getCause().getCause()).getOriginalMessage()); verify(activities).cancelHotel(captorHotelRequestId.getValue(), "trip1"); verify(activities).cancelCar(captorCarRequestId.getValue(), "trip1"); verify(activities).cancelFlight(captorFlightRequestId.getValue(), "trip1"); } } ================================================ FILE: core/src/test/java/io/temporal/samples/bookingsyncsaga/TripBookingWorkflowTest.java ================================================ package io.temporal.samples.bookingsyncsaga; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.*; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowException; import io.temporal.client.WorkflowStub; import io.temporal.client.WorkflowUpdateException; import io.temporal.failure.ApplicationFailure; import io.temporal.testing.TestWorkflowEnvironment; import io.temporal.testing.TestWorkflowExtension; import io.temporal.worker.Worker; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import org.mockito.ArgumentCaptor; public class TripBookingWorkflowTest { @RegisterExtension public static final TestWorkflowExtension testWorkflowExtension = TestWorkflowExtension.newBuilder() .setWorkflowTypes(TripBookingWorkflowImpl.class) .setDoNotStart(true) .build(); /** * Not very useful test that validates that the default activities cause workflow to fail. See * other tests on using mocked activities to test SAGA logic. */ @Test public void testTripBookingFails( TestWorkflowEnvironment testEnv, Worker worker, TripBookingWorkflow workflow) { worker.registerActivitiesImplementations(new TripBookingActivitiesImpl()); testEnv.start(); WorkflowException exception = assertThrows(WorkflowException.class, () -> workflow.bookTrip("trip1")); Assertions.assertEquals( "Flight booking did not work", ((ApplicationFailure) exception.getCause().getCause()).getOriginalMessage()); } /** Unit test workflow logic using mocked activities. */ @Test public void testSAGA( TestWorkflowEnvironment testEnv, Worker worker, TripBookingWorkflow workflow) { TripBookingActivities activities = mock(TripBookingActivities.class); ArgumentCaptor captorHotelRequestId = ArgumentCaptor.forClass(String.class); when(activities.bookHotel(captorHotelRequestId.capture(), eq("trip1"))) .thenReturn("HotelBookingID1"); ArgumentCaptor captorCarRequestId = ArgumentCaptor.forClass(String.class); when(activities.reserveCar(captorCarRequestId.capture(), eq("trip1"))) .thenReturn("CarBookingID1"); ArgumentCaptor captorFlightRequestId = ArgumentCaptor.forClass(String.class); when(activities.bookFlight(captorFlightRequestId.capture(), eq("trip1"))) .thenThrow( ApplicationFailure.newNonRetryableFailure( "Flight booking did not work", "bookingFailure")); worker.registerActivitiesImplementations(activities); testEnv.start(); // Starts workflow asynchronously. WorkflowClient.start(workflow::bookTrip, "trip1"); // Waits for update to return. WorkflowException exception1 = assertThrows(WorkflowUpdateException.class, () -> workflow.waitForBooking()); Assertions.assertEquals( "Flight booking did not work", ((ApplicationFailure) exception1.getCause().getCause()).getOriginalMessage()); // Waits for workflow to complete. WorkflowStub stub = WorkflowStub.fromTyped(workflow); WorkflowException exception2 = assertThrows(WorkflowException.class, () -> stub.getResult(Void.class)); Assertions.assertEquals( "Flight booking did not work", ((ApplicationFailure) exception2.getCause().getCause()).getOriginalMessage()); verify(activities).cancelHotel(captorHotelRequestId.getValue(), "trip1"); verify(activities).cancelCar(captorCarRequestId.getValue(), "trip1"); verify(activities).cancelFlight(captorFlightRequestId.getValue(), "trip1"); } } ================================================ FILE: core/src/test/java/io/temporal/samples/countinterceptor/ClientCountInterceptorTest.java ================================================ package io.temporal.samples.countinterceptor; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowClientOptions; import io.temporal.client.WorkflowOptions; import io.temporal.client.WorkflowStub; import io.temporal.samples.countinterceptor.activities.MyActivitiesImpl; import io.temporal.samples.countinterceptor.workflow.MyChildWorkflowImpl; import io.temporal.samples.countinterceptor.workflow.MyWorkflow; import io.temporal.samples.countinterceptor.workflow.MyWorkflowImpl; import io.temporal.testing.TestWorkflowRule; import org.junit.Rule; import org.junit.Test; public class ClientCountInterceptorTest { private static final String WORKFLOW_ID = "TestInterceptorWorkflow"; private final ClientCounter clientCounter = new ClientCounter(); @Rule public TestWorkflowRule testWorkflowRule = TestWorkflowRule.newBuilder() .setWorkflowTypes(MyWorkflowImpl.class, MyChildWorkflowImpl.class) .setActivityImplementations(new MyActivitiesImpl()) .setWorkflowClientOptions( WorkflowClientOptions.newBuilder() .setInterceptors(new SimpleClientInterceptor(clientCounter)) .build()) .build(); @Test public void testInterceptor() { WorkflowClient workflowClient = testWorkflowRule.getWorkflowClient(); MyWorkflow workflow = workflowClient.newWorkflowStub( MyWorkflow.class, WorkflowOptions.newBuilder() .setTaskQueue(testWorkflowRule.getTaskQueue()) .setWorkflowId(WORKFLOW_ID) .build()); WorkflowClient.start(workflow::exec); workflow.signalNameAndTitle("John", "Customer"); String name = workflow.queryName(); String title = workflow.queryTitle(); workflow.exit(); // Wait for workflow completion via WorkflowStub WorkflowStub untyped = WorkflowStub.fromTyped(workflow); String result = untyped.getResult(String.class); assertNotNull(result); assertNotNull(name); assertEquals("John", name); assertNotNull(title); assertEquals("Customer", title); assertEquals(1, clientCounter.getNumOfWorkflowExecutions(WORKFLOW_ID)); assertEquals(1, clientCounter.getNumOfGetResults(WORKFLOW_ID)); assertEquals(2, clientCounter.getNumOfSignals(WORKFLOW_ID)); assertEquals(2, clientCounter.getNumOfQueries(WORKFLOW_ID)); } } ================================================ FILE: core/src/test/java/io/temporal/samples/countinterceptor/WorkerCountInterceptorTest.java ================================================ package io.temporal.samples.countinterceptor; import static org.junit.Assert.*; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.client.WorkflowStub; import io.temporal.samples.countinterceptor.activities.MyActivitiesImpl; import io.temporal.samples.countinterceptor.workflow.MyChildWorkflowImpl; import io.temporal.samples.countinterceptor.workflow.MyWorkflow; import io.temporal.samples.countinterceptor.workflow.MyWorkflowImpl; import io.temporal.testing.TestWorkflowRule; import io.temporal.worker.WorkerFactoryOptions; import org.junit.Rule; import org.junit.Test; public class WorkerCountInterceptorTest { private static final String WORKFLOW_ID = "TestInterceptorWorkflow"; private static final String CHILD_WORKFLOW_ID = "TestInterceptorChildWorkflow"; @Rule public TestWorkflowRule testWorkflowRule = TestWorkflowRule.newBuilder() .setWorkflowTypes(MyWorkflowImpl.class, MyChildWorkflowImpl.class) .setActivityImplementations(new MyActivitiesImpl()) .setWorkerFactoryOptions( WorkerFactoryOptions.newBuilder() .setWorkerInterceptors(new SimpleCountWorkerInterceptor()) .build()) .build(); @Test public void testInterceptor() { MyWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub( MyWorkflow.class, WorkflowOptions.newBuilder() .setTaskQueue(testWorkflowRule.getTaskQueue()) .setWorkflowId(WORKFLOW_ID) .build()); WorkflowClient.start(workflow::exec); workflow.signalNameAndTitle("John", "Customer"); String name = workflow.queryName(); String title = workflow.queryTitle(); workflow.exit(); // Wait for workflow completion via WorkflowStub WorkflowStub untyped = WorkflowStub.fromTyped(workflow); String result = untyped.getResult(String.class); assertNotNull(result); assertNotNull(name); assertEquals("John", name); assertNotNull(title); assertEquals("Customer", title); assertEquals(1, WorkerCounter.getNumOfWorkflowExecutions(WORKFLOW_ID)); assertEquals(1, WorkerCounter.getNumOfChildWorkflowExecutions(WORKFLOW_ID)); // parent workflow does not execute any activities assertEquals(0, WorkerCounter.getNumOfActivityExecutions(WORKFLOW_ID)); // child workflow executes 2 activities assertEquals(2, WorkerCounter.getNumOfActivityExecutions(CHILD_WORKFLOW_ID)); assertEquals(2, WorkerCounter.getNumOfSignals(WORKFLOW_ID)); assertEquals(2, WorkerCounter.getNumOfQueries(WORKFLOW_ID)); } } ================================================ FILE: core/src/test/java/io/temporal/samples/dsl/DslWorkflowTest.java ================================================ package io.temporal.samples.dsl; import static org.junit.Assert.*; import com.fasterxml.jackson.databind.ObjectMapper; import io.temporal.client.WorkflowOptions; import io.temporal.samples.dsl.model.Flow; import io.temporal.testing.TestWorkflowRule; import org.junit.Rule; import org.junit.Test; public class DslWorkflowTest { @Rule public TestWorkflowRule testWorkflowRule = TestWorkflowRule.newBuilder() .setWorkflowTypes(DslWorkflowImpl.class) .setActivityImplementations(new DslActivitiesImpl()) .build(); @Test public void testDslWorkflow() throws Exception { DslWorkflow workflow = testWorkflowRule .getTestEnvironment() .getWorkflowClient() .newWorkflowStub( DslWorkflow.class, WorkflowOptions.newBuilder() .setWorkflowId("dsl-workflow") .setTaskQueue(testWorkflowRule.getWorker().getTaskQueue()) .build()); String result = workflow.run(getFlowFromResource(), "test input"); assertNotNull(result); assertEquals( "Activity one done...,Activity two done...,Activity three done...,Activity four done...", result); } private static Flow getFlowFromResource() { ObjectMapper objectMapper = new ObjectMapper(); try { return objectMapper.readValue( DslWorkflowTest.class.getClassLoader().getResource("dsl/sampleflow.json"), Flow.class); } catch (Exception e) { e.printStackTrace(); return null; } } } ================================================ FILE: core/src/test/java/io/temporal/samples/earlyreturn/TransactionWorkflowTest.java ================================================ package io.temporal.samples.earlyreturn; import static org.junit.Assert.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import io.temporal.api.enums.v1.WorkflowIdConflictPolicy; import io.temporal.client.*; import io.temporal.failure.ActivityFailure; import io.temporal.failure.ApplicationFailure; import io.temporal.testing.TestWorkflowRule; import java.util.UUID; import org.junit.Rule; import org.junit.Test; public class TransactionWorkflowTest { private static final String SOURCE_ACCOUNT = "Bob"; private static final String TARGET_ACCOUNT = "Alice"; private static final String TEST_TRANSACTION_ID = "test-id-123"; private static final int VALID_AMOUNT = 1000; private static final int INVALID_AMOUNT = -1000; @Rule public TestWorkflowRule testWorkflowRule = TestWorkflowRule.newBuilder() .setWorkflowTypes(TransactionWorkflowImpl.class) .setDoNotStart(true) .build(); @Test public void testUpdateWithStartValidAmount() throws Exception { // Mock activities TransactionActivities activities = mock(TransactionActivities.class, withSettings().withoutAnnotations()); when(activities.initTransaction(any())) .thenReturn( new Transaction(TEST_TRANSACTION_ID, SOURCE_ACCOUNT, TARGET_ACCOUNT, VALID_AMOUNT)); testWorkflowRule.getWorker().registerActivitiesImplementations(activities); testWorkflowRule.getTestEnvironment().start(); // Create workflow stub WorkflowClient workflowClient = testWorkflowRule.getWorkflowClient(); TransactionWorkflow workflow = workflowClient.newWorkflowStub( TransactionWorkflow.class, WorkflowOptions.newBuilder() .setWorkflowIdConflictPolicy( WorkflowIdConflictPolicy.WORKFLOW_ID_CONFLICT_POLICY_FAIL) .setTaskQueue(testWorkflowRule.getTaskQueue()) .build()); // Execute UpdateWithStart TransactionRequest txRequest = new TransactionRequest(SOURCE_ACCOUNT, TARGET_ACCOUNT, VALID_AMOUNT); TxResult updateResult = WorkflowClient.executeUpdateWithStart( workflow::returnInitResult, UpdateOptions.newBuilder().build(), new WithStartWorkflowOperation<>(workflow::processTransaction, txRequest)); // Verify both update and final results assertEquals(TEST_TRANSACTION_ID, updateResult.getTransactionId()); TxResult finalResult = WorkflowStub.fromTyped(workflow).getResult(TxResult.class); assertEquals("Transaction completed successfully.", finalResult.getStatus()); // Verify activities were calledgit verify(activities).mintTransactionId(any()); verify(activities).initTransaction(any()); verify(activities).completeTransaction(any()); verifyNoMoreInteractions(activities); } @Test public void testUpdateWithStartInvalidAmount() throws Exception { // Mock activities TransactionActivities activities = mock(TransactionActivities.class, withSettings().withoutAnnotations()); when(activities.initTransaction(any())) .thenThrow( ApplicationFailure.newNonRetryableFailure( "Non-retryable Activity Failure: Invalid Amount", "InvalidAmount")); doNothing().when(activities).cancelTransaction(any()); testWorkflowRule.getWorker().registerActivitiesImplementations(activities); testWorkflowRule.getTestEnvironment().start(); // Create workflow stub with explicit ID WorkflowClient workflowClient = testWorkflowRule.getWorkflowClient(); String workflowId = "test-workflow-" + UUID.randomUUID(); WorkflowOptions options = WorkflowOptions.newBuilder() .setWorkflowIdConflictPolicy(WorkflowIdConflictPolicy.WORKFLOW_ID_CONFLICT_POLICY_FAIL) .setTaskQueue(testWorkflowRule.getTaskQueue()) .setWorkflowId(workflowId) .build(); TransactionWorkflow workflow = workflowClient.newWorkflowStub(TransactionWorkflow.class, options); // Execute UpdateWithStart and expect the exception TransactionRequest txRequest = new TransactionRequest(SOURCE_ACCOUNT, TARGET_ACCOUNT, INVALID_AMOUNT); WorkflowUpdateException exception = assertThrows( WorkflowUpdateException.class, () -> WorkflowClient.executeUpdateWithStart( workflow::returnInitResult, UpdateOptions.newBuilder().build(), new WithStartWorkflowOperation<>(workflow::processTransaction, txRequest))); // Verify the exception chain assertTrue(exception.getCause() instanceof ActivityFailure); ApplicationFailure appFailure = (ApplicationFailure) exception.getCause().getCause(); assertEquals("InvalidAmount", appFailure.getType()); assertTrue(appFailure.getMessage().contains("Invalid Amount")); // Create a new stub to get the result TransactionWorkflow workflowById = workflowClient.newWorkflowStub(TransactionWorkflow.class, workflowId); TxResult finalResult = WorkflowStub.fromTyped(workflowById).getResult(TxResult.class); assertEquals("", finalResult.getTransactionId()); assertEquals("Transaction cancelled.", finalResult.getStatus()); // Verify activities were called in correct order verify(activities).mintTransactionId(any()); verify(activities).initTransaction(any()); verify(activities).cancelTransaction(any()); verifyNoMoreInteractions(activities); } } ================================================ FILE: core/src/test/java/io/temporal/samples/encodefailures/EncodeFailuresTest.java ================================================ package io.temporal.samples.encodefailures; import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; import io.temporal.api.common.v1.Payload; import io.temporal.api.history.v1.HistoryEvent; import io.temporal.client.WorkflowClientOptions; import io.temporal.client.WorkflowFailedException; import io.temporal.client.WorkflowOptions; import io.temporal.common.converter.CodecDataConverter; import io.temporal.common.converter.DefaultDataConverter; import io.temporal.testing.TestWorkflowRule; import io.temporal.worker.WorkflowImplementationOptions; import java.util.Collections; import org.junit.Rule; import org.junit.Test; public class EncodeFailuresTest { CodecDataConverter codecDataConverter = new CodecDataConverter( DefaultDataConverter.newDefaultInstance(), Collections.singletonList(new SimplePrefixPayloadCodec()), true); @Rule public TestWorkflowRule testWorkflowRule = TestWorkflowRule.newBuilder() .setWorkflowTypes( WorkflowImplementationOptions.newBuilder() .setFailWorkflowExceptionTypes(InvalidCustomerException.class) .build(), CustomerAgeCheckImpl.class) .setWorkflowClientOptions( WorkflowClientOptions.newBuilder().setDataConverter(codecDataConverter).build()) .build(); @Test public void testFailureMessageIsEncoded() { CustomerAgeCheck workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub( CustomerAgeCheck.class, WorkflowOptions.newBuilder() .setWorkflowId("CustomerAgeCheck") .setTaskQueue(testWorkflowRule.getTaskQueue()) .build()); assertThrows( WorkflowFailedException.class, () -> { workflow.validateCustomer(new MyCustomer("John", 20)); }); HistoryEvent wfExecFailedEvent = testWorkflowRule.getWorkflowClient().fetchHistory("CustomerAgeCheck").getLastEvent(); Payload payload = wfExecFailedEvent .getWorkflowExecutionFailedEventAttributes() .getFailure() .getEncodedAttributes(); assertTrue(isEncoded(payload)); } private boolean isEncoded(Payload payload) { return payload.getData().startsWith(SimplePrefixPayloadCodec.PREFIX); } } ================================================ FILE: core/src/test/java/io/temporal/samples/excludefrominterceptor/ExcludeFromInterceptorTest.java ================================================ package io.temporal.samples.excludefrominterceptor; import io.temporal.api.enums.v1.EventType; import io.temporal.api.history.v1.HistoryEvent; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.client.WorkflowStub; import io.temporal.common.WorkflowExecutionHistory; import io.temporal.samples.excludefrominterceptor.activities.ForInterceptorActivitiesImpl; import io.temporal.samples.excludefrominterceptor.activities.MyActivitiesImpl; import io.temporal.samples.excludefrominterceptor.interceptor.MyWorkerInterceptor; import io.temporal.samples.excludefrominterceptor.workflows.*; import io.temporal.testing.TestWorkflowRule; import io.temporal.worker.WorkerFactoryOptions; import java.util.Arrays; import java.util.concurrent.CompletableFuture; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; public class ExcludeFromInterceptorTest { @Rule public TestWorkflowRule testWorkflowRule = TestWorkflowRule.newBuilder() .setWorkflowTypes(MyWorkflowOneImpl.class, MyWorkflowTwoImpl.class) .setActivityImplementations(new MyActivitiesImpl(), new ForInterceptorActivitiesImpl()) .setWorkerFactoryOptions( WorkerFactoryOptions.newBuilder() .setWorkerInterceptors( new MyWorkerInterceptor( // exclude MyWorkflowTwo from workflow interceptors Arrays.asList(MyWorkflowTwo.class.getSimpleName()), // exclude ActivityTwo and the "ForInterceptor" activities from activity // interceptor // note with SpringBoot starter you could use bean names here, we use // strings to // not have // to reflect on the activity impl class in sample Arrays.asList( "ActivityTwo", "ForInterceptorActivityOne", "ForInterceptorActivityTwo"))) .build()) .build(); @Test public void testExcludeFromInterceptor() { MyWorkflow myWorkflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub( MyWorkflowOne.class, WorkflowOptions.newBuilder() .setWorkflowId("MyWorkflowOne") .setTaskQueue(testWorkflowRule.getTaskQueue()) .build()); MyWorkflowTwo myWorkflowTwo = testWorkflowRule .getWorkflowClient() .newWorkflowStub( MyWorkflowTwo.class, WorkflowOptions.newBuilder() .setWorkflowId("MyWorkflowTwo") .setTaskQueue(testWorkflowRule.getTaskQueue()) .build()); WorkflowClient.start(myWorkflow::execute, "my workflow input"); WorkflowClient.start(myWorkflowTwo::execute, "my workflow two input"); // wait for both execs to complete try { CompletableFuture.allOf( WorkflowStub.fromTyped(myWorkflow).getResultAsync(String.class), WorkflowStub.fromTyped(myWorkflowTwo).getResultAsync(String.class)) .get(); } catch (Exception e) { Assert.fail("Exception executing workflows: " + e.getMessage()); } Assert.assertEquals(5, getNumOfActivitiesForExec("MyWorkflowOne")); Assert.assertEquals(2, getNumOfActivitiesForExec("MyWorkflowTwo")); } private int getNumOfActivitiesForExec(String workflowId) { WorkflowExecutionHistory history = testWorkflowRule.getWorkflowClient().fetchHistory(workflowId); int counter = 0; for (HistoryEvent event : history.getEvents()) { if (event.getEventType().equals(EventType.EVENT_TYPE_ACTIVITY_TASK_COMPLETED)) { counter++; } } return counter; } } ================================================ FILE: core/src/test/java/io/temporal/samples/fileprocessing/FileProcessingTest.java ================================================ package io.temporal.samples.fileprocessing; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import io.temporal.client.WorkflowOptions; import io.temporal.samples.fileprocessing.StoreActivities.TaskQueueFileNamePair; import io.temporal.testing.TestWorkflowRule; import io.temporal.worker.Worker; import java.net.MalformedURLException; import java.net.URL; import org.junit.*; public class FileProcessingTest { private static final String HOST_NAME_1 = "host1"; private static final String HOST_NAME_2 = "host2"; private static final String FILE_NAME_UNPROCESSED = "input_file"; private static final String FILE_NAME_PROCESSED = "output_file"; private static final URL SOURCE; private static final URL DESTINATION; static { try { SOURCE = new URL("http://www.google.com/"); DESTINATION = new URL("http://dummy"); } catch (MalformedURLException e) { throw new RuntimeException(e); } } @Rule public TestWorkflowRule testWorkflowRule = TestWorkflowRule.newBuilder() .setWorkflowTypes(FileProcessingWorkflowImpl.class) .setDoNotStart(true) .build(); // Host specific workers. private Worker workerHost1; private Worker workerHost2; @Before public void setUp() { workerHost1 = testWorkflowRule.getTestEnvironment().newWorker(HOST_NAME_1); workerHost2 = testWorkflowRule.getTestEnvironment().newWorker(HOST_NAME_2); } @Test public void testHappyPath() { StoreActivities activities = mock(StoreActivities.class); when(activities.download(any())) .thenReturn(new TaskQueueFileNamePair(HOST_NAME_1, FILE_NAME_UNPROCESSED)); testWorkflowRule.getWorker().registerActivitiesImplementations(activities); StoreActivities activitiesHost1 = mock(StoreActivities.class); when(activitiesHost1.process(FILE_NAME_UNPROCESSED)).thenReturn(FILE_NAME_PROCESSED); workerHost1.registerActivitiesImplementations(activitiesHost1); StoreActivities activitiesHost2 = mock(StoreActivities.class); workerHost2.registerActivitiesImplementations(activitiesHost2); testWorkflowRule.getTestEnvironment().start(); FileProcessingWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub( FileProcessingWorkflow.class, WorkflowOptions.newBuilder().setTaskQueue(testWorkflowRule.getTaskQueue()).build()); // Execute workflow waiting for completion. workflow.processFile(SOURCE, DESTINATION); verify(activities).download(SOURCE); verify(activitiesHost1).process(FILE_NAME_UNPROCESSED); verify(activitiesHost1).upload(FILE_NAME_PROCESSED, DESTINATION); verifyNoMoreInteractions(activities, activitiesHost1); verifyNoInteractions(activitiesHost2); testWorkflowRule.getTestEnvironment().shutdown(); } @Test(timeout = 30_000) public void testHostFailover() { StoreActivities activities = mock(StoreActivities.class); when(activities.download(any())) .thenReturn(new TaskQueueFileNamePair(HOST_NAME_1, FILE_NAME_UNPROCESSED)) .thenReturn(new TaskQueueFileNamePair(HOST_NAME_2, FILE_NAME_UNPROCESSED)); testWorkflowRule.getWorker().registerActivitiesImplementations(activities); StoreActivities activitiesHost1 = mock(StoreActivities.class); when(activitiesHost1.process(FILE_NAME_UNPROCESSED)) .then( invocation -> { Thread.sleep(Long.MAX_VALUE); return "done"; }); workerHost1.registerActivitiesImplementations(activitiesHost1); StoreActivities activitiesHost2 = mock(StoreActivities.class); when(activitiesHost2.process(FILE_NAME_UNPROCESSED)).thenReturn(FILE_NAME_PROCESSED); workerHost2.registerActivitiesImplementations(activitiesHost2); testWorkflowRule.getTestEnvironment().start(); FileProcessingWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub( FileProcessingWorkflow.class, WorkflowOptions.newBuilder().setTaskQueue(testWorkflowRule.getTaskQueue()).build()); workflow.processFile(SOURCE, DESTINATION); verify(activities, times(2)).download(SOURCE); // TODO(maxim): Change to 1, once retry of SimulatedTimeoutException is not happening. // https://github.com/temporalio/temporal-java-sdk/issues/94 verify(activitiesHost1, times(4)).process(FILE_NAME_UNPROCESSED); verify(activitiesHost2).process(FILE_NAME_UNPROCESSED); verify(activitiesHost2).upload(FILE_NAME_PROCESSED, DESTINATION); verifyNoMoreInteractions(activities, activitiesHost1, activitiesHost2); testWorkflowRule.getTestEnvironment().shutdown(); } } ================================================ FILE: core/src/test/java/io/temporal/samples/getresultsasync/GetResultsAsyncTest.java ================================================ package io.temporal.samples.getresultsasync; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import io.temporal.client.WorkflowOptions; import io.temporal.client.WorkflowStub; import io.temporal.testing.TestWorkflowRule; import java.util.concurrent.CompletableFuture; import org.junit.Rule; import org.junit.Test; public class GetResultsAsyncTest { @Rule public TestWorkflowRule testWorkflowRule = TestWorkflowRule.newBuilder().setWorkflowTypes(MyWorkflowImpl.class).build(); @Test public void testGetResultsAsync() throws Exception { WorkflowStub workflowStub = testWorkflowRule .getWorkflowClient() .newUntypedWorkflowStub( "MyWorkflow", WorkflowOptions.newBuilder().setTaskQueue(testWorkflowRule.getTaskQueue()).build()); workflowStub.start(5); CompletableFuture completableFuture = workflowStub.getResultAsync(String.class); String result = completableFuture.get(); assertNotNull(result); assertEquals("woke up after 5 seconds", result); } } ================================================ FILE: core/src/test/java/io/temporal/samples/hello/HelloAccumulatorTest.java ================================================ package io.temporal.samples.hello; import static io.temporal.samples.hello.HelloAccumulator.MAX_AWAIT_TIME; import io.temporal.client.BatchRequest; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.samples.hello.HelloAccumulator.Greeting; import io.temporal.testing.TestWorkflowEnvironment; import io.temporal.testing.TestWorkflowRule; import java.time.Duration; import java.util.ArrayDeque; import java.util.HashSet; import org.junit.Rule; import org.junit.Test; public class HelloAccumulatorTest { private TestWorkflowEnvironment testEnv; @Rule public TestWorkflowRule testWorkflowRule = TestWorkflowRule.newBuilder() .setWorkflowTypes(HelloAccumulator.AccumulatorWorkflowImpl.class) .setActivityImplementations(new HelloAccumulator.GreetingActivitiesImpl()) .build(); @Test public void testWorkflow() { String bucket = "blue"; ArrayDeque greetingList = new ArrayDeque(); HashSet allGreetingsSet = new HashSet(); testEnv = testWorkflowRule.getTestEnvironment(); testEnv.start(); HelloAccumulator.AccumulatorWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub( HelloAccumulator.AccumulatorWorkflow.class, WorkflowOptions.newBuilder().setTaskQueue(testWorkflowRule.getTaskQueue()).build()); WorkflowClient.start(workflow::accumulateGreetings, bucket, greetingList, allGreetingsSet); Greeting xvxGreeting = new Greeting("XVX Robot", bucket, "1123581321"); workflow.sendGreeting(xvxGreeting); String results = workflow.accumulateGreetings(bucket, greetingList, allGreetingsSet); assert results.contains("Hello (1)"); assert results.contains("XVX Robot"); } @Test public void testJustExit() { String bucket = "blue"; ArrayDeque greetingList = new ArrayDeque(); HashSet allGreetingsSet = new HashSet(); testEnv = testWorkflowRule.getTestEnvironment(); testEnv.start(); HelloAccumulator.AccumulatorWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub( HelloAccumulator.AccumulatorWorkflow.class, WorkflowOptions.newBuilder().setTaskQueue(testWorkflowRule.getTaskQueue()).build()); WorkflowClient.start(workflow::accumulateGreetings, bucket, greetingList, allGreetingsSet); workflow.exit(); String results = workflow.accumulateGreetings(bucket, greetingList, allGreetingsSet); assert results.contains("Hello (0)"); assert !results.contains("Robot"); } @Test public void testNoExit() { String bucket = "blue"; ArrayDeque greetingList = new ArrayDeque(); HashSet allGreetingsSet = new HashSet(); testEnv = testWorkflowRule.getTestEnvironment(); testEnv.start(); HelloAccumulator.AccumulatorWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub( HelloAccumulator.AccumulatorWorkflow.class, WorkflowOptions.newBuilder().setTaskQueue(testWorkflowRule.getTaskQueue()).build()); WorkflowClient.start(workflow::accumulateGreetings, bucket, greetingList, allGreetingsSet); Greeting xvxGreeting = new Greeting("XVX Robot", bucket, "1123581321"); workflow.sendGreeting(xvxGreeting); String results = workflow.accumulateGreetings(bucket, greetingList, allGreetingsSet); assert results.contains("Hello (1)"); assert results.contains("XVX Robot"); } @Test public void testMultipleGreetings() { String bucket = "blue"; ArrayDeque greetingList = new ArrayDeque(); HashSet allGreetingsSet = new HashSet(); testEnv = testWorkflowRule.getTestEnvironment(); testEnv.start(); HelloAccumulator.AccumulatorWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub( HelloAccumulator.AccumulatorWorkflow.class, WorkflowOptions.newBuilder().setTaskQueue(testWorkflowRule.getTaskQueue()).build()); WorkflowClient.start(workflow::accumulateGreetings, bucket, greetingList, allGreetingsSet); workflow.sendGreeting(new Greeting("XVX Robot", bucket, "1123581321")); workflow.sendGreeting(new Greeting("Han Robot", bucket, "112358")); String results = workflow.accumulateGreetings(bucket, greetingList, allGreetingsSet); assert results.contains("Hello (2)"); assert results.contains("XVX Robot"); assert results.contains("Han Robot"); } @Test public void testDuplicateGreetings() { String bucket = "blue"; ArrayDeque greetingList = new ArrayDeque(); HashSet allGreetingsSet = new HashSet(); testEnv = testWorkflowRule.getTestEnvironment(); testEnv.start(); HelloAccumulator.AccumulatorWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub( HelloAccumulator.AccumulatorWorkflow.class, WorkflowOptions.newBuilder().setTaskQueue(testWorkflowRule.getTaskQueue()).build()); WorkflowClient.start(workflow::accumulateGreetings, bucket, greetingList, allGreetingsSet); workflow.sendGreeting(new Greeting("XVX Robot", bucket, "1123581321")); workflow.sendGreeting(new Greeting("Han Robot", bucket, "1123581321")); String results = workflow.accumulateGreetings(bucket, greetingList, allGreetingsSet); assert results.contains("Hello (1)"); assert results.contains("XVX Robot"); assert !results.contains("Han Robot"); } @Test public void testWrongBucketGreeting() { String bucket = "blue"; ArrayDeque greetingList = new ArrayDeque(); HashSet allGreetingsSet = new HashSet(); testEnv = testWorkflowRule.getTestEnvironment(); testEnv.start(); HelloAccumulator.AccumulatorWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub( HelloAccumulator.AccumulatorWorkflow.class, WorkflowOptions.newBuilder().setTaskQueue(testWorkflowRule.getTaskQueue()).build()); WorkflowClient.start(workflow::accumulateGreetings, bucket, greetingList, allGreetingsSet); workflow.sendGreeting(new Greeting("Bad Robot", "orange", "1123581321")); workflow.sendGreeting(new Greeting("XVX Robot", bucket, "11235")); String results = workflow.accumulateGreetings(bucket, greetingList, allGreetingsSet); assert results.contains("Hello (1)"); assert results.contains("XVX Robot"); assert !results.contains("Bad Robot"); } @Test public void testSignalWithStart() { String bucket = "blue"; ArrayDeque greetingList = new ArrayDeque(); HashSet allGreetingsSet = new HashSet(); testEnv = testWorkflowRule.getTestEnvironment(); testEnv.start(); WorkflowClient client = testWorkflowRule.getWorkflowClient(); HelloAccumulator.AccumulatorWorkflow workflow = client.newWorkflowStub( HelloAccumulator.AccumulatorWorkflow.class, WorkflowOptions.newBuilder().setTaskQueue(testWorkflowRule.getTaskQueue()).build()); Greeting starterGreeting = new Greeting("Robby Robot", bucket, "112"); BatchRequest request = client.newSignalWithStartRequest(); request.add(workflow::accumulateGreetings, bucket, greetingList, allGreetingsSet); request.add(workflow::sendGreeting, starterGreeting); client.signalWithStart(request); String results = workflow.accumulateGreetings(bucket, greetingList, allGreetingsSet); assert results.contains("Hello (1)"); assert results.contains("Robby Robot"); } @Test public void testWaitTooLongForFirstWorkflow() { String bucket = "blue"; ArrayDeque greetingList = new ArrayDeque(); HashSet allGreetingsSet = new HashSet(); testEnv = testWorkflowRule.getTestEnvironment(); testEnv.start(); WorkflowClient client = testWorkflowRule.getWorkflowClient(); HelloAccumulator.AccumulatorWorkflow workflow = client.newWorkflowStub( HelloAccumulator.AccumulatorWorkflow.class, WorkflowOptions.newBuilder() .setTaskQueue(testWorkflowRule.getTaskQueue()) .setWorkflowId(bucket) .setWorkflowId("helloacc-blue") .build()); Greeting starterGreeting = new Greeting("Robby Robot", bucket, "112"); BatchRequest request = client.newSignalWithStartRequest(); request.add(workflow::accumulateGreetings, bucket, greetingList, allGreetingsSet); request.add(workflow::sendGreeting, starterGreeting); client.signalWithStart(request); // testEnv.sleep(MAX_AWAIT_TIME.plus(Duration.ofMillis(1))); is not long enough // to guarantee the // first workflow will end testEnv.sleep(MAX_AWAIT_TIME.plus(Duration.ofMillis(100))); HelloAccumulator.AccumulatorWorkflow workflow2 = client.newWorkflowStub( HelloAccumulator.AccumulatorWorkflow.class, WorkflowOptions.newBuilder() .setTaskQueue(testWorkflowRule.getTaskQueue()) .setWorkflowId(bucket) .setWorkflowId("helloacc-blue") .build()); Greeting secondGreeting = new Greeting("Dave Robot", bucket, "1123"); request = client.newSignalWithStartRequest(); request.add(workflow2::accumulateGreetings, bucket, greetingList, allGreetingsSet); request.add(workflow2::sendGreeting, secondGreeting); client.signalWithStart(request); String results = workflow.accumulateGreetings(bucket, greetingList, allGreetingsSet); assert results.contains("Hello (1)"); assert !results.contains("Robby Robot"); assert results.contains("Dave Robot"); } @Test public void testWaitNotLongEnoughForNewWorkflow() { String bucket = "blue"; ArrayDeque greetingList = new ArrayDeque(); HashSet allGreetingsSet = new HashSet(); testEnv = testWorkflowRule.getTestEnvironment(); testEnv.start(); WorkflowClient client = testWorkflowRule.getWorkflowClient(); HelloAccumulator.AccumulatorWorkflow workflow = client.newWorkflowStub( HelloAccumulator.AccumulatorWorkflow.class, WorkflowOptions.newBuilder() .setTaskQueue(testWorkflowRule.getTaskQueue()) .setWorkflowId(bucket) .setWorkflowId("helloacc-blue") .build()); Greeting starterGreeting = new Greeting("Robby Robot", bucket, "112"); BatchRequest request = client.newSignalWithStartRequest(); request.add(workflow::accumulateGreetings, bucket, greetingList, allGreetingsSet); request.add(workflow::sendGreeting, starterGreeting); client.signalWithStart(request); testEnv.sleep(MAX_AWAIT_TIME.minus(Duration.ofMillis(1))); HelloAccumulator.AccumulatorWorkflow workflow2 = client.newWorkflowStub( HelloAccumulator.AccumulatorWorkflow.class, WorkflowOptions.newBuilder() .setTaskQueue(testWorkflowRule.getTaskQueue()) .setWorkflowId(bucket) .setWorkflowId("helloacc-blue") .build()); Greeting secondGreeting = new Greeting("Dave Robot", bucket, "1123"); request = client.newSignalWithStartRequest(); request.add(workflow2::accumulateGreetings, bucket, greetingList, allGreetingsSet); request.add(workflow2::sendGreeting, secondGreeting); client.signalWithStart(request); String results = workflow.accumulateGreetings(bucket, greetingList, allGreetingsSet); assert results.contains("Hello (2)"); assert results.contains("Robby Robot"); assert results.contains("Dave Robot"); } @Test public void testWaitExactlyMAX_TIME() { String bucket = "blue"; ArrayDeque greetingList = new ArrayDeque(); HashSet allGreetingsSet = new HashSet(); testEnv = testWorkflowRule.getTestEnvironment(); testEnv.start(); WorkflowClient client = testWorkflowRule.getWorkflowClient(); HelloAccumulator.AccumulatorWorkflow workflow = client.newWorkflowStub( HelloAccumulator.AccumulatorWorkflow.class, WorkflowOptions.newBuilder() .setTaskQueue(testWorkflowRule.getTaskQueue()) .setWorkflowId(bucket) .setWorkflowId("helloacc-blue") .build()); Greeting starterGreeting = new Greeting("Robby Robot", bucket, "112"); BatchRequest request = client.newSignalWithStartRequest(); request.add(workflow::accumulateGreetings, bucket, greetingList, allGreetingsSet); request.add(workflow::sendGreeting, starterGreeting); client.signalWithStart(request); testEnv.sleep(MAX_AWAIT_TIME); HelloAccumulator.AccumulatorWorkflow workflow2 = client.newWorkflowStub( HelloAccumulator.AccumulatorWorkflow.class, WorkflowOptions.newBuilder() .setTaskQueue(testWorkflowRule.getTaskQueue()) .setWorkflowId(bucket) .setWorkflowId("helloacc-blue") .build()); Greeting secondGreeting = new Greeting("Dave Robot", bucket, "1123"); request = client.newSignalWithStartRequest(); request.add(workflow2::accumulateGreetings, bucket, greetingList, allGreetingsSet); request.add(workflow2::sendGreeting, secondGreeting); client.signalWithStart(request); String results = workflow.accumulateGreetings(bucket, greetingList, allGreetingsSet); assert results.contains("Hello (2)"); assert results.contains("Robby Robot"); assert results.contains("Dave Robot"); } @Test public void testSignalAfterExit() { String bucket = "blue"; ArrayDeque greetingList = new ArrayDeque(); HashSet allGreetingsSet = new HashSet(); testEnv = testWorkflowRule.getTestEnvironment(); testEnv.start(); WorkflowClient client = testWorkflowRule.getWorkflowClient(); HelloAccumulator.AccumulatorWorkflow workflow = client.newWorkflowStub( HelloAccumulator.AccumulatorWorkflow.class, WorkflowOptions.newBuilder() .setTaskQueue(testWorkflowRule.getTaskQueue()) .setWorkflowId(bucket) .setWorkflowId("helloacc-blue") .build()); Greeting starterGreeting = new Greeting("Robby Robot", bucket, "112"); BatchRequest request = client.newSignalWithStartRequest(); request.add(workflow::accumulateGreetings, bucket, greetingList, allGreetingsSet); request.add(workflow::sendGreeting, starterGreeting); client.signalWithStart(request); HelloAccumulator.AccumulatorWorkflow workflow2 = client.newWorkflowStub( HelloAccumulator.AccumulatorWorkflow.class, WorkflowOptions.newBuilder() .setTaskQueue(testWorkflowRule.getTaskQueue()) .setWorkflowId(bucket) .setWorkflowId("helloacc-blue") .build()); Greeting secondGreeting = new Greeting("Dave Robot", bucket, "1123"); request = client.newSignalWithStartRequest(); request.add(workflow2::accumulateGreetings, bucket, greetingList, allGreetingsSet); request.add(workflow2::sendGreeting, secondGreeting); // exit signal the workflow we signaled-to-start workflow.exit(); // try to signal with start the workflow client.signalWithStart(request); String results = workflow.accumulateGreetings(bucket, greetingList, allGreetingsSet); assert results.contains("Hello (2)"); assert results.contains("Robby Robot"); assert results.contains("Dave Robot"); } } ================================================ FILE: core/src/test/java/io/temporal/samples/hello/HelloActivityExclusiveChoiceJUnit5Test.java ================================================ package io.temporal.samples.hello; import static org.junit.jupiter.api.Assertions.assertEquals; import io.temporal.testing.TestWorkflowExtension; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; /** Unit test for {@link HelloActivityExclusiveChoice}. Doesn't use an external Temporal service. */ public class HelloActivityExclusiveChoiceJUnit5Test { @RegisterExtension public static final TestWorkflowExtension testWorkflowExtension = TestWorkflowExtension.newBuilder() .setWorkflowTypes(HelloActivityExclusiveChoice.PurchaseFruitsWorkflowImpl.class) .setActivityImplementations(new HelloActivityExclusiveChoice.OrderFruitsActivitiesImpl()) .build(); @Test public void testWorkflow(HelloActivityExclusiveChoice.PurchaseFruitsWorkflow workflow) { // Execute a workflow waiting for it to complete. HelloActivityExclusiveChoice.ShoppingList shoppingList = new HelloActivityExclusiveChoice.ShoppingList(); shoppingList.addFruitOrder(HelloActivityExclusiveChoice.Fruits.APPLE, 10); StringBuilder orderResults = workflow.orderFruit(shoppingList); assertEquals("Ordered 10 Apples...", orderResults.toString()); } } ================================================ FILE: core/src/test/java/io/temporal/samples/hello/HelloActivityExclusiveChoiceTest.java ================================================ package io.temporal.samples.hello; import static io.temporal.samples.hello.HelloActivityExclusiveChoice.WORKFLOW_ID; import static org.junit.Assert.assertEquals; import io.temporal.client.WorkflowOptions; import io.temporal.testing.TestWorkflowRule; import org.junit.Rule; import org.junit.Test; /** Unit test for {@link HelloActivityExclusiveChoice}. Doesn't use an external Temporal service. */ public class HelloActivityExclusiveChoiceTest { @Rule public TestWorkflowRule testWorkflowRule = TestWorkflowRule.newBuilder() .setWorkflowTypes(HelloActivityExclusiveChoice.PurchaseFruitsWorkflowImpl.class) .setActivityImplementations(new HelloActivityExclusiveChoice.OrderFruitsActivitiesImpl()) .build(); @Test public void testWorkflow() { // Get a workflow stub using the same task queue the worker uses. HelloActivityExclusiveChoice.PurchaseFruitsWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub( HelloActivityExclusiveChoice.PurchaseFruitsWorkflow.class, WorkflowOptions.newBuilder() .setWorkflowId(WORKFLOW_ID) .setTaskQueue(testWorkflowRule.getTaskQueue()) .build()); // Execute a workflow waiting for it to complete. HelloActivityExclusiveChoice.ShoppingList shoppingList = new HelloActivityExclusiveChoice.ShoppingList(); shoppingList.addFruitOrder(HelloActivityExclusiveChoice.Fruits.APPLE, 10); StringBuilder orderResults = workflow.orderFruit(shoppingList); assertEquals("Ordered 10 Apples...", orderResults.toString()); } } ================================================ FILE: core/src/test/java/io/temporal/samples/hello/HelloActivityJUnit5Test.java ================================================ package io.temporal.samples.hello; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.mockito.Mockito.withSettings; import io.temporal.samples.hello.HelloActivity.GreetingActivities; import io.temporal.samples.hello.HelloActivity.GreetingActivitiesImpl; import io.temporal.samples.hello.HelloActivity.GreetingWorkflow; import io.temporal.samples.hello.HelloActivity.GreetingWorkflowImpl; import io.temporal.testing.TestWorkflowEnvironment; import io.temporal.testing.TestWorkflowExtension; import io.temporal.worker.Worker; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; /** Unit test for {@link HelloActivity}. Doesn't use an external Temporal service. */ public class HelloActivityJUnit5Test { @RegisterExtension public static final TestWorkflowExtension testWorkflowExtension = TestWorkflowExtension.newBuilder() .setWorkflowTypes(GreetingWorkflowImpl.class) .setDoNotStart(true) .build(); @Test public void testActivityImpl( TestWorkflowEnvironment testEnv, Worker worker, GreetingWorkflow workflow) { worker.registerActivitiesImplementations(new GreetingActivitiesImpl()); testEnv.start(); // Execute a workflow waiting for it to complete. String greeting = workflow.getGreeting("World"); assertEquals("Hello World!", greeting); } @Test public void testMockedActivity( TestWorkflowEnvironment testEnv, Worker worker, GreetingWorkflow workflow) { // withoutAnnotations() is required to stop Mockito from copying // method-level annotations from the GreetingActivities interface GreetingActivities activities = mock(GreetingActivities.class, withSettings().withoutAnnotations()); when(activities.composeGreeting("Hello", "World")).thenReturn("Hello World!"); worker.registerActivitiesImplementations(activities); testEnv.start(); // Execute a workflow waiting for it to complete. String greeting = workflow.getGreeting("World"); assertEquals("Hello World!", greeting); } @Test public void testMockedActivityWithoutSettings(Worker worker) { // Mocking activity that has method-level annotations // with no withoutAnnotations() setting results in a failure GreetingActivities activities = mock(GreetingActivities.class); assertThrows( IllegalArgumentException.class, () -> worker.registerActivitiesImplementations(activities)); } } ================================================ FILE: core/src/test/java/io/temporal/samples/hello/HelloActivityReplayTest.java ================================================ package io.temporal.samples.hello; import static org.hamcrest.MatcherAssert.assertThat; import io.temporal.activity.ActivityOptions; import io.temporal.api.common.v1.WorkflowExecution; import io.temporal.client.WorkflowOptions; import io.temporal.client.WorkflowStub; import io.temporal.internal.common.WorkflowExecutionHistory; import io.temporal.testing.TestWorkflowRule; import io.temporal.testing.WorkflowReplayer; import io.temporal.workflow.Workflow; import java.time.Duration; import org.hamcrest.CoreMatchers; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; /** * Unit test for replay {@link HelloActivity.GreetingWorkflowImpl}. Doesn't use an external Temporal * service. */ public class HelloActivityReplayTest { @Rule public TestWorkflowRule testWorkflowRule = TestWorkflowRule.newBuilder().setDoNotStart(true).build(); @Test public void replayWorkflowExecution() throws Exception { final String eventHistory = executeWorkflow(HelloActivity.GreetingWorkflowImpl.class); WorkflowReplayer.replayWorkflowExecution( eventHistory, HelloActivity.GreetingWorkflowImpl.class); } @Test public void replayWorkflowExecutionNonDeterministic() { // We are executing the workflow with one implementation (GreetingWorkflowImplTest) and trying // to replay the even history with a different implementation (GreetingWorkflowImpl), // which causes an exception during the replay try { final String eventHistory = executeWorkflow(GreetingWorkflowImplTest.class); WorkflowReplayer.replayWorkflowExecution( eventHistory, HelloActivity.GreetingWorkflowImpl.class); Assert.fail("Should have thrown an Exception"); } catch (Exception e) { assertThat( e.getMessage(), CoreMatchers.containsString("error=io.temporal.worker.NonDeterministicException")); } } private String executeWorkflow( Class workflowImplementationType) { testWorkflowRule .getWorker() .registerActivitiesImplementations(new HelloActivity.GreetingActivitiesImpl()); testWorkflowRule.getWorker().registerWorkflowImplementationTypes(workflowImplementationType); testWorkflowRule.getTestEnvironment().start(); HelloActivity.GreetingWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub( HelloActivity.GreetingWorkflow.class, WorkflowOptions.newBuilder().setTaskQueue(testWorkflowRule.getTaskQueue()).build()); WorkflowExecution execution = WorkflowStub.fromTyped(workflow).start("Hello"); // wait until workflow completes WorkflowStub.fromTyped(workflow).getResult(String.class); return new WorkflowExecutionHistory(testWorkflowRule.getHistory(execution)).toJson(true); } public static class GreetingWorkflowImplTest implements HelloActivity.GreetingWorkflow { private final HelloActivity.GreetingActivities activities = Workflow.newActivityStub( HelloActivity.GreetingActivities.class, ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(2)).build()); @Override public String getGreeting(String name) { Workflow.sleep(100); return activities.composeGreeting("Hello", name); } } } ================================================ FILE: core/src/test/java/io/temporal/samples/hello/HelloActivityRetryTest.java ================================================ package io.temporal.samples.hello; import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.*; import io.temporal.client.WorkflowOptions; import io.temporal.samples.hello.HelloActivityRetry.GreetingActivities; import io.temporal.samples.hello.HelloActivityRetry.GreetingActivitiesImpl; import io.temporal.samples.hello.HelloActivityRetry.GreetingWorkflow; import io.temporal.samples.hello.HelloActivityRetry.GreetingWorkflowImpl; import io.temporal.testing.TestWorkflowRule; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestWatcher; import org.junit.runner.Description; /** Unit test for {@link HelloActivityRetry}. Doesn't use an external Temporal service. */ public class HelloActivityRetryTest { @Rule public TestWorkflowRule testWorkflowRule = TestWorkflowRule.newBuilder() .setWorkflowTypes(GreetingWorkflowImpl.class) .setDoNotStart(true) .build(); /** Prints a history of the workflow under test in case of a test failure. */ @Rule public TestWatcher watchman = new TestWatcher() { @Override protected void failed(Throwable e, Description description) { if (testWorkflowRule.getTestEnvironment() != null) { System.err.println(testWorkflowRule.getTestEnvironment().getDiagnostics()); testWorkflowRule.getTestEnvironment().shutdown(); } } }; @Test public void testActivityImpl() { testWorkflowRule.getWorker().registerActivitiesImplementations(new GreetingActivitiesImpl()); testWorkflowRule.getTestEnvironment().start(); // Get a workflow stub using the same task queue the worker uses. GreetingWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub( GreetingWorkflow.class, WorkflowOptions.newBuilder().setTaskQueue(testWorkflowRule.getTaskQueue()).build()); // Execute a workflow waiting for it to complete String greeting = workflow.getGreeting("World"); assertEquals("Hello World!", greeting); testWorkflowRule.getTestEnvironment().shutdown(); } @Test public void testMockedActivity() { GreetingActivities activities = mock(GreetingActivities.class); when(activities.composeGreeting("Hello", "World")) .thenThrow( new IllegalStateException("not yet1"), new IllegalStateException("not yet2"), new IllegalStateException("not yet3")) .thenReturn("Hello World!"); testWorkflowRule.getWorker().registerActivitiesImplementations(activities); testWorkflowRule.getTestEnvironment().start(); // Get a workflow stub using the same task queue the worker uses. WorkflowOptions workflowOptions = WorkflowOptions.newBuilder().setTaskQueue(testWorkflowRule.getTaskQueue()).build(); GreetingWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub(GreetingWorkflow.class, workflowOptions); // Execute a workflow waiting for it to complete. String greeting = workflow.getGreeting("World"); assertEquals("Hello World!", greeting); verify(activities, times(4)).composeGreeting(anyString(), anyString()); testWorkflowRule.getTestEnvironment().shutdown(); } } ================================================ FILE: core/src/test/java/io/temporal/samples/hello/HelloActivityTest.java ================================================ package io.temporal.samples.hello; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.mockito.Mockito.withSettings; import io.temporal.client.WorkflowOptions; import io.temporal.samples.hello.HelloActivity.GreetingActivities; import io.temporal.samples.hello.HelloActivity.GreetingActivitiesImpl; import io.temporal.samples.hello.HelloActivity.GreetingWorkflow; import io.temporal.samples.hello.HelloActivity.GreetingWorkflowImpl; import io.temporal.testing.TestWorkflowRule; import org.junit.Rule; import org.junit.Test; /** Unit test for {@link HelloActivity}. Doesn't use an external Temporal service. */ public class HelloActivityTest { @Rule public TestWorkflowRule testWorkflowRule = TestWorkflowRule.newBuilder() .setWorkflowTypes(GreetingWorkflowImpl.class) .setDoNotStart(true) .build(); @Test public void testActivityImpl() { testWorkflowRule.getWorker().registerActivitiesImplementations(new GreetingActivitiesImpl()); testWorkflowRule.getTestEnvironment().start(); // Get a workflow stub using the same task queue the worker uses. GreetingWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub( GreetingWorkflow.class, WorkflowOptions.newBuilder().setTaskQueue(testWorkflowRule.getTaskQueue()).build()); // Execute a workflow waiting for it to complete. String greeting = workflow.getGreeting("World"); assertEquals("Hello World!", greeting); testWorkflowRule.getTestEnvironment().shutdown(); } @Test public void testMockedActivity() { // withoutAnnotations() is required to stop Mockito from copying // method-level annotations from the GreetingActivities interface GreetingActivities activities = mock(GreetingActivities.class, withSettings().withoutAnnotations()); when(activities.composeGreeting("Hello", "World")).thenReturn("Hello World!"); testWorkflowRule.getWorker().registerActivitiesImplementations(activities); testWorkflowRule.getTestEnvironment().start(); // Get a workflow stub using the same task queue the worker uses. GreetingWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub( GreetingWorkflow.class, WorkflowOptions.newBuilder().setTaskQueue(testWorkflowRule.getTaskQueue()).build()); // Execute a workflow waiting for it to complete. String greeting = workflow.getGreeting("World"); assertEquals("Hello World!", greeting); testWorkflowRule.getTestEnvironment().shutdown(); } @Test(expected = IllegalArgumentException.class) public void testMockedActivityWithoutSettings() { // Mocking activity that has method-level annotations // with no withoutAnnotations() setting results in a failure GreetingActivities activities = mock(GreetingActivities.class); testWorkflowRule.getWorker().registerActivitiesImplementations(activities); } } ================================================ FILE: core/src/test/java/io/temporal/samples/hello/HelloAsyncActivityCompletionTest.java ================================================ package io.temporal.samples.hello; import static org.junit.Assert.assertEquals; import io.temporal.client.ActivityCompletionClient; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.samples.hello.HelloAsyncActivityCompletion.GreetingActivitiesImpl; import io.temporal.samples.hello.HelloAsyncActivityCompletion.GreetingWorkflow; import io.temporal.samples.hello.HelloAsyncActivityCompletion.GreetingWorkflowImpl; import io.temporal.testing.TestWorkflowRule; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import org.junit.Rule; import org.junit.Test; /** Unit test for {@link HelloAsyncActivityCompletion}. Doesn't use an external Temporal service. */ public class HelloAsyncActivityCompletionTest { @Rule public TestWorkflowRule testWorkflowRule = TestWorkflowRule.newBuilder() .setWorkflowTypes(GreetingWorkflowImpl.class) .setDoNotStart(true) .build(); @Test public void testActivityImpl() throws ExecutionException, InterruptedException { ActivityCompletionClient completionClient = testWorkflowRule.getWorkflowClient().newActivityCompletionClient(); testWorkflowRule .getWorker() .registerActivitiesImplementations(new GreetingActivitiesImpl(completionClient)); testWorkflowRule.getTestEnvironment().start(); GreetingWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub( GreetingWorkflow.class, WorkflowOptions.newBuilder().setTaskQueue(testWorkflowRule.getTaskQueue()).build()); // Execute a workflow asynchronously. CompletableFuture greeting = WorkflowClient.execute(workflow::getGreeting, "World"); // Wait for workflow completion. assertEquals("Hello World!", greeting.get()); testWorkflowRule.getTestEnvironment().shutdown(); } } ================================================ FILE: core/src/test/java/io/temporal/samples/hello/HelloAsyncLambdaTest.java ================================================ package io.temporal.samples.hello; import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.*; import io.temporal.client.WorkflowOptions; import io.temporal.samples.hello.HelloAsyncLambda.GreetingActivities; import io.temporal.samples.hello.HelloAsyncLambda.GreetingActivitiesImpl; import io.temporal.samples.hello.HelloAsyncLambda.GreetingWorkflow; import io.temporal.samples.hello.HelloAsyncLambda.GreetingWorkflowImpl; import io.temporal.testing.TestWorkflowRule; import org.junit.Rule; import org.junit.Test; import org.junit.rules.Timeout; /** Unit test for {@link HelloAsyncLambda}. Doesn't use an external Temporal service. */ public class HelloAsyncLambdaTest { @Rule public Timeout globalTimeout = Timeout.seconds(3); @Rule public TestWorkflowRule testWorkflowRule = TestWorkflowRule.newBuilder() .setWorkflowTypes(GreetingWorkflowImpl.class) .setDoNotStart(true) .build(); @Test public void testActivityImpl() { testWorkflowRule.getWorker().registerActivitiesImplementations(new GreetingActivitiesImpl()); testWorkflowRule.getTestEnvironment().start(); // Get a workflow stub using the same task queue the worker uses. WorkflowOptions workflowOptions = WorkflowOptions.newBuilder().setTaskQueue(testWorkflowRule.getTaskQueue()).build(); GreetingWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub(GreetingWorkflow.class, workflowOptions); // Execute a workflow waiting for it to complete. String greeting = workflow.getGreeting("World"); assertEquals("Hello World!\nHello World!", greeting); testWorkflowRule.getTestEnvironment().shutdown(); } @Test public void testMockedActivity() { GreetingActivities activities = mock(GreetingActivities.class); when(activities.getGreeting()).thenReturn("Hello"); when(activities.composeGreeting("Hello", "World")).thenReturn("Hello World!"); testWorkflowRule.getWorker().registerActivitiesImplementations(activities); testWorkflowRule.getTestEnvironment().start(); WorkflowOptions workflowOptions = WorkflowOptions.newBuilder().setTaskQueue(testWorkflowRule.getTaskQueue()).build(); GreetingWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub(GreetingWorkflow.class, workflowOptions); // Execute a workflow waiting for it to complete. String greeting = workflow.getGreeting("World"); assertEquals("Hello World!\nHello World!", greeting); verify(activities, times(2)).composeGreeting(anyString(), anyString()); verify(activities, times(2)).getGreeting(); testWorkflowRule.getTestEnvironment().shutdown(); } } ================================================ FILE: core/src/test/java/io/temporal/samples/hello/HelloAsyncTest.java ================================================ package io.temporal.samples.hello; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import io.temporal.client.WorkflowOptions; import io.temporal.samples.hello.HelloAsync.GreetingActivities; import io.temporal.samples.hello.HelloAsync.GreetingActivitiesImpl; import io.temporal.samples.hello.HelloAsync.GreetingWorkflow; import io.temporal.samples.hello.HelloAsync.GreetingWorkflowImpl; import io.temporal.testing.TestWorkflowRule; import org.junit.Rule; import org.junit.Test; /** Unit test for {@link HelloAsync}. Doesn't use an external Temporal service. */ public class HelloAsyncTest { @Rule public TestWorkflowRule testWorkflowRule = TestWorkflowRule.newBuilder() .setWorkflowTypes(GreetingWorkflowImpl.class) .setDoNotStart(true) .build(); @Test public void testActivityImpl() { testWorkflowRule.getWorker().registerActivitiesImplementations(new GreetingActivitiesImpl()); testWorkflowRule.getTestEnvironment().start(); GreetingWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub( GreetingWorkflow.class, WorkflowOptions.newBuilder().setTaskQueue(testWorkflowRule.getTaskQueue()).build()); // Execute a workflow waiting for it to complete. String greeting = workflow.getGreeting("World"); assertEquals("Hello World!\nBye World!", greeting); testWorkflowRule.getTestEnvironment().shutdown(); } @Test public void testMockedActivity() { GreetingActivities activities = mock(GreetingActivities.class); when(activities.composeGreeting("Hello", "World")).thenReturn("Hello World!"); when(activities.composeGreeting("Bye", "World")).thenReturn("Bye World!"); testWorkflowRule.getWorker().registerActivitiesImplementations(activities); testWorkflowRule.getTestEnvironment().start(); GreetingWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub( GreetingWorkflow.class, WorkflowOptions.newBuilder().setTaskQueue(testWorkflowRule.getTaskQueue()).build()); // Execute a workflow waiting for it to complete. String greeting = workflow.getGreeting("World"); assertEquals("Hello World!\nBye World!", greeting); testWorkflowRule.getTestEnvironment().shutdown(); } } ================================================ FILE: core/src/test/java/io/temporal/samples/hello/HelloAwaitTest.java ================================================ package io.temporal.samples.hello; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowException; import io.temporal.client.WorkflowOptions; import io.temporal.client.WorkflowStub; import io.temporal.failure.ApplicationFailure; import io.temporal.samples.hello.HelloAwait.GreetingWorkflow; import io.temporal.testing.TestWorkflowRule; import java.time.Duration; import org.junit.Rule; import org.junit.Test; /** Unit test for {@link HelloAwait}. Doesn't use an external Temporal service. */ public class HelloAwaitTest { private final String WORKFLOW_ID = "WORKFLOW1"; @Rule public TestWorkflowRule testWorkflowRule = TestWorkflowRule.newBuilder().setWorkflowTypes(HelloAwait.GreetingWorkflowImpl.class).build(); @Test public void testAwaitSignal() { // Get a workflow stub using the same task queue the worker uses. WorkflowOptions workflowOptions = WorkflowOptions.newBuilder() .setTaskQueue(testWorkflowRule.getTaskQueue()) .setWorkflowId(WORKFLOW_ID) .build(); GreetingWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub(GreetingWorkflow.class, workflowOptions); // Start workflow asynchronously to not use another thread to await. WorkflowClient.start(workflow::getGreeting); workflow.waitForName("World"); // So we can send a await to it using workflow stub immediately. // But just to demonstrate the unit testing of a long running workflow adding a long sleep here. // testWorkflowRule.getTestEnvironment().sleep(Duration.ofSeconds(30)); WorkflowStub workflowById = testWorkflowRule.getWorkflowClient().newUntypedWorkflowStub(WORKFLOW_ID); String greeting = workflowById.getResult(String.class); assertEquals("Hello World!", greeting); } @Test public void testAwaitTimeout() { // Get a workflow stub using the same task queue the worker uses. WorkflowOptions workflowOptions = WorkflowOptions.newBuilder() .setTaskQueue(testWorkflowRule.getTaskQueue()) .setWorkflowId(WORKFLOW_ID) .build(); GreetingWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub(GreetingWorkflow.class, workflowOptions); // Start workflow asynchronously to not use another thread to wait. WorkflowClient.start(workflow::getGreeting); // Skip time to force Await timeout testWorkflowRule.getTestEnvironment().sleep(Duration.ofSeconds(30)); WorkflowStub workflowById = testWorkflowRule.getWorkflowClient().newUntypedWorkflowStub(WORKFLOW_ID); try { workflowById.getResult(String.class); fail("not reachable"); } catch (WorkflowException e) { ApplicationFailure applicationFailure = (ApplicationFailure) e.getCause(); assertEquals("signal-timeout", applicationFailure.getType()); } } } ================================================ FILE: core/src/test/java/io/temporal/samples/hello/HelloCancellationScopeTest.java ================================================ package io.temporal.samples.hello; import static org.junit.Assert.assertTrue; import io.temporal.client.WorkflowOptions; import io.temporal.samples.hello.HelloCancellationScope.GreetingActivitiesImpl; import io.temporal.samples.hello.HelloCancellationScope.GreetingWorkflow; import io.temporal.samples.hello.HelloCancellationScope.GreetingWorkflowImpl; import io.temporal.testing.TestWorkflowRule; import org.junit.Rule; import org.junit.Test; /** Unit test for {@link HelloCancellationScope}. Doesn't use an external Temporal service. */ public class HelloCancellationScopeTest { @Rule public TestWorkflowRule testWorkflowRule = TestWorkflowRule.newBuilder() .setWorkflowTypes(GreetingWorkflowImpl.class) .setActivityImplementations(new GreetingActivitiesImpl()) .build(); @Test(timeout = 240_000) public void testActivityImpl() { // Get a workflow stub using the same task queue the worker uses. GreetingWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub( GreetingWorkflow.class, WorkflowOptions.newBuilder().setTaskQueue(testWorkflowRule.getTaskQueue()).build()); // Execute a workflow waiting for it to complete. String greeting = workflow.getGreeting("World"); assertTrue(greeting.endsWith(" World!")); } } ================================================ FILE: core/src/test/java/io/temporal/samples/hello/HelloCancellationScopeWithTimerTest.java ================================================ package io.temporal.samples.hello; import static org.junit.Assert.assertTrue; import io.temporal.client.WorkflowOptions; import io.temporal.testing.TestWorkflowRule; import org.junit.Rule; import org.junit.Test; public class HelloCancellationScopeWithTimerTest { @Rule public TestWorkflowRule testWorkflowRule = TestWorkflowRule.newBuilder() .setWorkflowTypes(HelloCancellationScopeWithTimer.CancellationWithTimerWorkflowImpl.class) .setActivityImplementations( new HelloCancellationScopeWithTimer.UpdateInfoActivitiesImpl()) .build(); @Test(timeout = 240_000) public void testActivityImpl() { // Get a workflow stub using the same task queue the worker uses. HelloCancellationScopeWithTimer.CancellationWithTimerWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub( HelloCancellationScopeWithTimer.CancellationWithTimerWorkflow.class, WorkflowOptions.newBuilder().setTaskQueue(testWorkflowRule.getTaskQueue()).build()); // Execute a workflow waiting for it to complete. String result = workflow.execute("Test Input"); assertTrue(result.endsWith("Activity canceled due to timer firing.")); } } ================================================ FILE: core/src/test/java/io/temporal/samples/hello/HelloChildJUnit5Test.java ================================================ package io.temporal.samples.hello; import static org.mockito.Mockito.*; import io.temporal.testing.TestWorkflowEnvironment; import io.temporal.testing.TestWorkflowExtension; import io.temporal.worker.Worker; import org.junit.Assert; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; /** Unit test for {@link HelloChild}. Doesn't use an external Temporal service. */ public class HelloChildJUnit5Test { private HelloChild.GreetingChild child = mock(HelloChild.GreetingChildImpl.class); @RegisterExtension public static final TestWorkflowExtension testWorkflowExtension = TestWorkflowExtension.newBuilder() .setWorkflowTypes(HelloChild.GreetingWorkflowImpl.class) .setDoNotStart(true) .build(); @Test public void testChild( TestWorkflowEnvironment testEnv, Worker worker, HelloChild.GreetingWorkflow workflow) { worker.registerWorkflowImplementationFactory( HelloChild.GreetingChild.class, () -> { when(child.composeGreeting(anyString(), anyString())).thenReturn("Bye World!"); return child; }); testEnv.start(); // Execute a workflow waiting for it to complete. String greeting = workflow.getGreeting("World"); Assert.assertEquals("Bye World!", greeting); verify(child).composeGreeting(eq("Hello"), eq("World")); testEnv.shutdown(); } } ================================================ FILE: core/src/test/java/io/temporal/samples/hello/HelloChildTest.java ================================================ package io.temporal.samples.hello; import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.*; import io.temporal.client.WorkflowOptions; import io.temporal.samples.hello.HelloChild.GreetingChild; import io.temporal.samples.hello.HelloChild.GreetingChildImpl; import io.temporal.samples.hello.HelloChild.GreetingWorkflow; import io.temporal.samples.hello.HelloChild.GreetingWorkflowImpl; import io.temporal.testing.TestWorkflowRule; import java.util.concurrent.atomic.AtomicReference; import org.junit.Rule; import org.junit.Test; /** Unit test for {@link HelloChild}. Doesn't use an external Temporal service. */ public class HelloChildTest { @Rule public TestWorkflowRule testWorkflowRule = TestWorkflowRule.newBuilder().setDoNotStart(true).build(); @Test public void testChild() { testWorkflowRule .getWorker() .registerWorkflowImplementationTypes(GreetingWorkflowImpl.class, GreetingChildImpl.class); testWorkflowRule.getTestEnvironment().start(); // Get a workflow stub using the same task queue the worker uses. GreetingWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub( GreetingWorkflow.class, WorkflowOptions.newBuilder().setTaskQueue(testWorkflowRule.getTaskQueue()).build()); // Execute a workflow waiting for it to complete. String greeting = workflow.getGreeting("World"); assertEquals("Hello World!", greeting); testWorkflowRule.getTestEnvironment().shutdown(); } @Test public void testMockedChild() { testWorkflowRule.getWorker().registerWorkflowImplementationTypes(GreetingWorkflowImpl.class); // As new mock is created on each workflow task the only last one is useful to verify calls. AtomicReference lastChildMock = new AtomicReference<>(); // Factory is called to create a new workflow object on each workflow task. testWorkflowRule .getWorker() .registerWorkflowImplementationFactory( GreetingChild.class, () -> { GreetingChild child = mock(GreetingChild.class); when(child.composeGreeting("Hello", "World")).thenReturn("Hello World!"); lastChildMock.set(child); return child; }); testWorkflowRule.getTestEnvironment().start(); // Get a workflow stub using the same task queue the worker uses. GreetingWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub( GreetingWorkflow.class, WorkflowOptions.newBuilder().setTaskQueue(testWorkflowRule.getTaskQueue()).build()); // Execute a workflow waiting for it to complete. String greeting = workflow.getGreeting("World"); assertEquals("Hello World!", greeting); GreetingChild mock = lastChildMock.get(); verify(mock).composeGreeting(eq("Hello"), eq("World")); testWorkflowRule.getTestEnvironment().shutdown(); } } ================================================ FILE: core/src/test/java/io/temporal/samples/hello/HelloCronTest.java ================================================ package io.temporal.samples.hello; import static io.temporal.samples.hello.HelloCron.WORKFLOW_ID; import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.*; import io.temporal.api.common.v1.WorkflowExecution; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.samples.hello.HelloCron.GreetingActivities; import io.temporal.samples.hello.HelloCron.GreetingWorkflow; import io.temporal.samples.hello.HelloCron.GreetingWorkflowImpl; import io.temporal.testing.TestWorkflowRule; import java.time.Duration; import org.junit.Rule; import org.junit.Test; /** Unit test for {@link HelloCron}. Doesn't use an external Temporal service. */ public class HelloCronTest { @Rule public TestWorkflowRule testWorkflowRule = TestWorkflowRule.newBuilder() .setWorkflowTypes(GreetingWorkflowImpl.class) .setDoNotStart(true) .build(); @Test public void testMockedActivity() { GreetingActivities activities = mock(GreetingActivities.class); testWorkflowRule.getWorker().registerActivitiesImplementations(activities); testWorkflowRule.getTestEnvironment().start(); // Unfortunately the supported cron format of the Java test service is not exactly the same as // the temporal service. For example @every is not supported by the unit testing framework. WorkflowOptions workflowOptions = WorkflowOptions.newBuilder() .setCronSchedule("0 * * * *") .setTaskQueue(testWorkflowRule.getTaskQueue()) .setWorkflowId(WORKFLOW_ID) .build(); GreetingWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub(GreetingWorkflow.class, workflowOptions); // Execute a workflow waiting for it to complete. WorkflowExecution execution = WorkflowClient.start(workflow::greet, "World"); assertEquals(WORKFLOW_ID, execution.getWorkflowId()); // Use TestWorkflowEnvironment.sleep to execute the unit test without really sleeping. testWorkflowRule.getTestEnvironment().sleep(Duration.ofDays(1)); verify(activities, atLeast(10)).greet(anyString()); testWorkflowRule.getTestEnvironment().shutdown(); } } ================================================ FILE: core/src/test/java/io/temporal/samples/hello/HelloDelayedStartTest.java ================================================ package io.temporal.samples.hello; import static org.junit.Assert.assertEquals; import io.temporal.client.WorkflowOptions; import io.temporal.common.WorkflowExecutionHistory; import io.temporal.testing.TestWorkflowRule; import java.time.Duration; import org.junit.Rule; import org.junit.Test; public class HelloDelayedStartTest { private final String WORKFLOW_ID = "HelloDelayedStartWorkflow"; @Rule public TestWorkflowRule testWorkflowRule = TestWorkflowRule.newBuilder() .setWorkflowTypes(HelloDelayedStart.DelayedStartWorkflowImpl.class) .build(); @Test public void testDelayedStart() { // Get a workflow stub using the same task queue the worker uses. WorkflowOptions workflowOptions = WorkflowOptions.newBuilder() .setTaskQueue(testWorkflowRule.getTaskQueue()) .setWorkflowId(WORKFLOW_ID) .setStartDelay(Duration.ofSeconds(2)) .build(); HelloDelayedStart.DelayedStartWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub(HelloDelayedStart.DelayedStartWorkflow.class, workflowOptions); workflow.start(); // Fetch event history and make sure we got the 2 seconds first workflow task backoff WorkflowExecutionHistory history = testWorkflowRule.getWorkflowClient().fetchHistory(WORKFLOW_ID); com.google.protobuf.Duration backoff = history .getHistory() .getEvents(0) .getWorkflowExecutionStartedEventAttributes() .getFirstWorkflowTaskBackoff(); assertEquals(2, backoff.getSeconds()); } } ================================================ FILE: core/src/test/java/io/temporal/samples/hello/HelloDetachedCancellationScopeTest.java ================================================ package io.temporal.samples.hello; import static org.junit.Assert.assertEquals; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowFailedException; import io.temporal.client.WorkflowOptions; import io.temporal.client.WorkflowStub; import io.temporal.testing.TestWorkflowRule; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.junit.Rule; import org.junit.Test; /** * Unit test for {@link HelloDetachedCancellationScope}. Doesn't use an external Temporal service. */ public class HelloDetachedCancellationScopeTest { @Rule public TestWorkflowRule testWorkflowRule = TestWorkflowRule.newBuilder() .setWorkflowTypes(HelloDetachedCancellationScope.GreetingWorkflowImpl.class) .setActivityImplementations(new HelloDetachedCancellationScope.GreetingActivitiesImpl()) .build(); @Test public void testDetachedWorkflowScope() { // Get a workflow stub using the same task queue the worker uses. HelloDetachedCancellationScope.GreetingWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub( HelloDetachedCancellationScope.GreetingWorkflow.class, WorkflowOptions.newBuilder().setTaskQueue(testWorkflowRule.getTaskQueue()).build()); WorkflowClient.start(workflow::getGreeting, "John"); WorkflowStub workflowStub = WorkflowStub.fromTyped(workflow); workflowStub.cancel(); String result; try { // Wait for workflow results // Because we cancelled the workflow we should get WorkflowFailedException result = workflowStub.getResult(6, TimeUnit.SECONDS, String.class, String.class); } catch (TimeoutException | WorkflowFailedException e) { // Query the workflow to get the result which was set by the detached cancellation scope run result = workflowStub.query("queryGreeting", String.class); } assertEquals("Goodbye John!", result); } } ================================================ FILE: core/src/test/java/io/temporal/samples/hello/HelloDynamicActivityJUnit5Test.java ================================================ package io.temporal.samples.hello; import static org.junit.jupiter.api.Assertions.assertEquals; import io.temporal.activity.ActivityInterface; import io.temporal.testing.TestActivityExtension; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; /** * Unit test for {@link HelloDynamic.DynamicGreetingActivityImpl}. Doesn't use an external Temporal * service. */ public class HelloDynamicActivityJUnit5Test { @RegisterExtension public static final TestActivityExtension testActivityExtension = TestActivityExtension.newBuilder() .setActivityImplementations(new HelloDynamic.DynamicGreetingActivityImpl()) .build(); /** * Dynamic activity {@link HelloDynamic.DynamicGreetingActivityImpl} is injected as an * implementation for a static activity interface {@link MyStaticActivity}. */ @Test public void testDynamicActivity(MyStaticActivity activity) { String result = activity.response("Hello", "John", "HelloDynamicActivityJUnit5Test"); assertEquals("MyStaticResponse: Hello John from: HelloDynamicActivityJUnit5Test", result); } @ActivityInterface(namePrefix = "MyStatic") public interface MyStaticActivity { String response(String name, String greeting, String source); } } ================================================ FILE: core/src/test/java/io/temporal/samples/hello/HelloDynamicTest.java ================================================ package io.temporal.samples.hello; import static org.junit.Assert.*; import io.temporal.client.WorkflowOptions; import io.temporal.client.WorkflowStub; import io.temporal.testing.TestWorkflowRule; import org.junit.Rule; import org.junit.Test; /** Unit test for {@link HelloDynamic}. Doesn't use an external Temporal service. */ public class HelloDynamicTest { @Rule public TestWorkflowRule testWorkflowRule = TestWorkflowRule.newBuilder() .setWorkflowTypes(HelloDynamic.DynamicGreetingWorkflowImpl.class) .setActivityImplementations(new HelloDynamic.DynamicGreetingActivityImpl()) .build(); @Test public void testActivityImpl() { WorkflowOptions workflowOptions = WorkflowOptions.newBuilder() .setTaskQueue(testWorkflowRule.getTaskQueue()) .setWorkflowId(HelloDynamic.WORKFLOW_ID) .build(); WorkflowStub workflow = testWorkflowRule.getWorkflowClient().newUntypedWorkflowStub("DynamicWF", workflowOptions); // Start workflow execution and signal right after Pass in the workflow args and signal args workflow.signalWithStart("greetingSignal", new Object[] {"John"}, new Object[] {"Hello"}); // Wait for workflow to finish getting the results String result = workflow.getResult(String.class); assertNotNull(result); assertEquals("DynamicACT: Hello John from: DynamicWF", result); } } ================================================ FILE: core/src/test/java/io/temporal/samples/hello/HelloEagerWorkflowStartTest.java ================================================ package io.temporal.samples.hello; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.mockito.Mockito.withSettings; import io.temporal.client.WorkflowOptions; import io.temporal.samples.hello.HelloEagerWorkflowStart.GreetingActivities; import io.temporal.samples.hello.HelloEagerWorkflowStart.GreetingLocalActivitiesImpl; import io.temporal.samples.hello.HelloEagerWorkflowStart.GreetingWorkflow; import io.temporal.samples.hello.HelloEagerWorkflowStart.GreetingWorkflowImpl; import io.temporal.testing.TestWorkflowRule; import org.junit.Rule; import org.junit.Test; /** Unit test for {@link HelloEagerWorkflowStart}. Doesn't use an external Temporal service. */ public class HelloEagerWorkflowStartTest { @Rule public TestWorkflowRule testWorkflowRule = TestWorkflowRule.newBuilder() .setWorkflowTypes(GreetingWorkflowImpl.class) .setDoNotStart(true) .build(); @Test public void testActivityImpl() { testWorkflowRule .getWorker() .registerActivitiesImplementations(new GreetingLocalActivitiesImpl()); testWorkflowRule.getTestEnvironment().start(); // Get a workflow stub using the same task queue the worker uses. GreetingWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub( GreetingWorkflow.class, WorkflowOptions.newBuilder().setTaskQueue(testWorkflowRule.getTaskQueue()).build()); // Execute a workflow waiting for it to complete. String greeting = workflow.getGreeting("World"); assertEquals("Hello World!", greeting); testWorkflowRule.getTestEnvironment().shutdown(); } @Test public void testMockedActivity() { // withoutAnnotations() is required to stop Mockito from copying // method-level annotations from the GreetingActivities interface GreetingActivities activities = mock(GreetingActivities.class, withSettings().withoutAnnotations()); when(activities.composeGreeting("Hello", "World")).thenReturn("Hello World!"); testWorkflowRule.getWorker().registerActivitiesImplementations(activities); testWorkflowRule.getTestEnvironment().start(); // Get a workflow stub using the same task queue the worker uses. GreetingWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub( GreetingWorkflow.class, WorkflowOptions.newBuilder().setTaskQueue(testWorkflowRule.getTaskQueue()).build()); // Execute a workflow waiting for it to complete. String greeting = workflow.getGreeting("World"); assertEquals("Hello World!", greeting); testWorkflowRule.getTestEnvironment().shutdown(); } } ================================================ FILE: core/src/test/java/io/temporal/samples/hello/HelloExceptionTest.java ================================================ package io.temporal.samples.hello; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import io.temporal.api.enums.v1.TimeoutType; import io.temporal.client.WorkflowException; import io.temporal.client.WorkflowOptions; import io.temporal.failure.ActivityFailure; import io.temporal.failure.ApplicationFailure; import io.temporal.failure.ChildWorkflowFailure; import io.temporal.failure.TimeoutFailure; import io.temporal.samples.hello.HelloException.GreetingChildImpl; import io.temporal.samples.hello.HelloException.GreetingWorkflow; import io.temporal.samples.hello.HelloException.GreetingWorkflowImpl; import io.temporal.testing.TestWorkflowRule; import org.junit.Rule; import org.junit.Test; public class HelloExceptionTest { @Rule public TestWorkflowRule testWorkflowRule = TestWorkflowRule.newBuilder().setDoNotStart(true).build(); @Test public void testIOException() { testWorkflowRule .getWorker() .registerWorkflowImplementationTypes( HelloException.GreetingWorkflowImpl.class, GreetingChildImpl.class); testWorkflowRule .getWorker() .registerActivitiesImplementations(new HelloException.GreetingActivitiesImpl()); testWorkflowRule.getTestEnvironment().start(); WorkflowOptions workflowOptions = WorkflowOptions.newBuilder().setTaskQueue(testWorkflowRule.getTaskQueue()).build(); GreetingWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub(GreetingWorkflow.class, workflowOptions); try { workflow.getGreeting("World"); throw new IllegalStateException("unreachable"); } catch (WorkflowException e) { assertTrue(e.getCause() instanceof ChildWorkflowFailure); assertTrue(e.getCause().getCause() instanceof ActivityFailure); assertTrue(e.getCause().getCause().getCause() instanceof ApplicationFailure); assertEquals( "Hello World!", ((ApplicationFailure) e.getCause().getCause().getCause()).getOriginalMessage()); } testWorkflowRule.getTestEnvironment().shutdown(); } @Test public void testActivityScheduleToStartTimeout() { testWorkflowRule .getWorker() .registerWorkflowImplementationTypes( HelloException.GreetingWorkflowImpl.class, GreetingChildImpl.class); // We don't register an activity implementation on the worker and the activity has 5 seconds // schedule to start timeout in GreetingChildImpl testWorkflowRule.getTestEnvironment().start(); WorkflowOptions workflowOptions = WorkflowOptions.newBuilder().setTaskQueue(testWorkflowRule.getTaskQueue()).build(); GreetingWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub(GreetingWorkflow.class, workflowOptions); try { workflow.getGreeting("World"); throw new IllegalStateException("unreachable"); } catch (WorkflowException e) { assertTrue(e.getCause() instanceof ChildWorkflowFailure); Throwable doubleCause = e.getCause().getCause(); assertTrue(doubleCause instanceof ActivityFailure); Throwable tripleCause = doubleCause.getCause(); assertTrue(tripleCause instanceof TimeoutFailure); assertEquals( TimeoutType.TIMEOUT_TYPE_SCHEDULE_TO_START, ((TimeoutFailure) tripleCause).getTimeoutType()); } testWorkflowRule.getTestEnvironment().shutdown(); } @Test(timeout = 100000) public void testChildWorkflowTimeout() { testWorkflowRule.getWorker().registerWorkflowImplementationTypes(GreetingWorkflowImpl.class); // Mock a child that times out. testWorkflowRule .getWorker() .registerWorkflowImplementationFactory( HelloException.GreetingChild.class, () -> { GreetingChildImpl child = mock(GreetingChildImpl.class); when(child.composeGreeting(anyString(), anyString())) .thenThrow( new TimeoutFailure( "simulated", null, TimeoutType.TIMEOUT_TYPE_START_TO_CLOSE)); return child; }); testWorkflowRule.getTestEnvironment().start(); WorkflowOptions workflowOptions = WorkflowOptions.newBuilder().setTaskQueue(testWorkflowRule.getTaskQueue()).build(); GreetingWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub(GreetingWorkflow.class, workflowOptions); try { workflow.getGreeting("World"); throw new IllegalStateException("unreachable"); } catch (WorkflowException e) { assertTrue(e.getCause() instanceof ChildWorkflowFailure); assertTrue(e.getCause().getCause() instanceof TimeoutFailure); } testWorkflowRule.getTestEnvironment().shutdown(); } } ================================================ FILE: core/src/test/java/io/temporal/samples/hello/HelloLocalActivityTest.java ================================================ package io.temporal.samples.hello; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.mockito.Mockito.withSettings; import io.temporal.client.WorkflowOptions; import io.temporal.samples.hello.HelloLocalActivity.GreetingActivities; import io.temporal.samples.hello.HelloLocalActivity.GreetingLocalActivityImpl; import io.temporal.samples.hello.HelloLocalActivity.GreetingWorkflow; import io.temporal.samples.hello.HelloLocalActivity.GreetingWorkflowImpl; import io.temporal.testing.TestWorkflowRule; import org.junit.Rule; import org.junit.Test; /** Unit test for {@link HelloLocalActivity}. Doesn't use an external Temporal service. */ public class HelloLocalActivityTest { @Rule public TestWorkflowRule testWorkflowRule = TestWorkflowRule.newBuilder() .setWorkflowTypes(GreetingWorkflowImpl.class) .setDoNotStart(true) .build(); @Test public void testActivityImpl() { testWorkflowRule.getWorker().registerActivitiesImplementations(new GreetingLocalActivityImpl()); testWorkflowRule.getTestEnvironment().start(); // Get a workflow stub using the same task queue the worker uses. GreetingWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub( GreetingWorkflow.class, WorkflowOptions.newBuilder().setTaskQueue(testWorkflowRule.getTaskQueue()).build()); // Execute a workflow waiting for it to complete. String greeting = workflow.getGreeting("World"); assertEquals("Hello World!", greeting); testWorkflowRule.getTestEnvironment().shutdown(); } @Test public void testMockedActivity() { // withoutAnnotations() is required to stop Mockito from copying // method-level annotations from the GreetingActivities interface GreetingActivities activities = mock(GreetingActivities.class, withSettings().withoutAnnotations()); when(activities.composeGreeting("Hello", "World")).thenReturn("Hello World!"); testWorkflowRule.getWorker().registerActivitiesImplementations(activities); testWorkflowRule.getTestEnvironment().start(); // Get a workflow stub using the same task queue the worker uses. GreetingWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub( GreetingWorkflow.class, WorkflowOptions.newBuilder().setTaskQueue(testWorkflowRule.getTaskQueue()).build()); // Execute a workflow waiting for it to complete. String greeting = workflow.getGreeting("World"); assertEquals("Hello World!", greeting); testWorkflowRule.getTestEnvironment().shutdown(); } } ================================================ FILE: core/src/test/java/io/temporal/samples/hello/HelloParallelActivityTest.java ================================================ package io.temporal.samples.hello; import static org.junit.Assert.assertEquals; import io.temporal.client.WorkflowOptions; import io.temporal.testing.TestWorkflowRule; import java.util.Arrays; import java.util.List; import org.junit.Rule; import org.junit.Test; /** Unit test for {@link HelloParallelActivity}. Doesn't use an external Temporal service. */ public class HelloParallelActivityTest { @Rule public TestWorkflowRule testWorkflowRule = TestWorkflowRule.newBuilder() .setWorkflowTypes(HelloParallelActivity.MultiGreetingWorkflowImpl.class) .setActivityImplementations(new HelloParallelActivity.GreetingActivitiesImpl()) .build(); @Test public void testParallelActivity() { WorkflowOptions workflowOptions = WorkflowOptions.newBuilder().setTaskQueue(testWorkflowRule.getTaskQueue()).build(); HelloParallelActivity.MultiGreetingWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub(HelloParallelActivity.MultiGreetingWorkflow.class, workflowOptions); // Execute a workflow waiting for it to complete. List results = workflow.getGreetings(Arrays.asList("John", "Marry", "Michael", "Janet")); assertEquals(4, results.size()); } } ================================================ FILE: core/src/test/java/io/temporal/samples/hello/HelloPeriodicTest.java ================================================ package io.temporal.samples.hello; import static io.temporal.samples.hello.HelloPeriodic.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.*; import io.temporal.api.common.v1.WorkflowExecution; import io.temporal.api.enums.v1.WorkflowExecutionStatus; import io.temporal.api.filter.v1.WorkflowExecutionFilter; import io.temporal.api.workflow.v1.WorkflowExecutionInfo; import io.temporal.api.workflowservice.v1.ListClosedWorkflowExecutionsRequest; import io.temporal.api.workflowservice.v1.ListClosedWorkflowExecutionsResponse; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.samples.hello.HelloPeriodic.GreetingActivities; import io.temporal.samples.hello.HelloPeriodic.GreetingActivitiesImpl; import io.temporal.samples.hello.HelloPeriodic.GreetingWorkflow; import io.temporal.samples.hello.HelloPeriodic.GreetingWorkflowImpl; import io.temporal.testing.TestWorkflowRule; import java.time.Duration; import org.junit.Rule; import org.junit.Test; /** Unit test for {@link HelloPeriodic}. Doesn't use an external Temporal service. */ public class HelloPeriodicTest { @Rule public TestWorkflowRule testWorkflowRule = TestWorkflowRule.newBuilder() .setWorkflowTypes(GreetingWorkflowImpl.class) .setDoNotStart(true) .build(); @Test public void testPeriodicActivityInvocation() { testWorkflowRule.getWorker().registerActivitiesImplementations(new GreetingActivitiesImpl()); testWorkflowRule.getTestEnvironment().start(); // Get a workflow stub using the same task queue the worker uses. GreetingWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub( GreetingWorkflow.class, WorkflowOptions.newBuilder() .setTaskQueue(testWorkflowRule.getTaskQueue()) .setWorkflowId(WORKFLOW_ID) .build()); // Execute a workflow waiting for it to complete. WorkflowExecution execution = WorkflowClient.start(workflow::greetPeriodically, "World"); assertEquals(WORKFLOW_ID, execution.getWorkflowId()); // Validate that workflow was continued as new at least once. // Use TestWorkflowEnvironment.sleep to execute the unit test without really sleeping. testWorkflowRule.getTestEnvironment().sleep(Duration.ofMinutes(3)); ListClosedWorkflowExecutionsRequest request = ListClosedWorkflowExecutionsRequest.newBuilder() .setNamespace(testWorkflowRule.getTestEnvironment().getNamespace()) .setExecutionFilter(WorkflowExecutionFilter.newBuilder().setWorkflowId(WORKFLOW_ID)) .build(); ListClosedWorkflowExecutionsResponse listResponse = testWorkflowRule .getTestEnvironment() .getWorkflowService() .blockingStub() .listClosedWorkflowExecutions(request); assertTrue(listResponse.getExecutionsCount() > 1); for (WorkflowExecutionInfo e : listResponse.getExecutionsList()) { assertEquals( WorkflowExecutionStatus.WORKFLOW_EXECUTION_STATUS_CONTINUED_AS_NEW, e.getStatus()); } testWorkflowRule.getTestEnvironment().shutdown(); } @Test public void testMockedActivity() { GreetingActivities activities = mock(GreetingActivities.class); testWorkflowRule.getWorker().registerActivitiesImplementations(activities); testWorkflowRule.getTestEnvironment().start(); // Get a workflow stub using the same task queue the worker uses. GreetingWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub( GreetingWorkflow.class, WorkflowOptions.newBuilder() .setTaskQueue(testWorkflowRule.getTaskQueue()) .setWorkflowId(WORKFLOW_ID) .build()); // Execute a workflow waiting for it to complete. WorkflowExecution execution = WorkflowClient.start(workflow::greetPeriodically, "World"); assertEquals(WORKFLOW_ID, execution.getWorkflowId()); // Use TestWorkflowEnvironment.sleep to execute the unit test without really sleeping. testWorkflowRule.getTestEnvironment().sleep(Duration.ofMinutes(1)); verify(activities, atLeast(5)).greet(anyString()); testWorkflowRule.getTestEnvironment().shutdown(); } } ================================================ FILE: core/src/test/java/io/temporal/samples/hello/HelloPolymorphicActivityTest.java ================================================ package io.temporal.samples.hello; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import io.temporal.client.WorkflowOptions; import io.temporal.samples.hello.HelloPolymorphicActivity.ByeActivityImpl; import io.temporal.samples.hello.HelloPolymorphicActivity.GreetingWorkflow; import io.temporal.samples.hello.HelloPolymorphicActivity.GreetingWorkflowImpl; import io.temporal.samples.hello.HelloPolymorphicActivity.HelloActivityImpl; import io.temporal.testing.TestWorkflowRule; import org.junit.Rule; import org.junit.Test; /** Unit test for {@link HelloActivity}. Doesn't use an external Temporal service. */ public class HelloPolymorphicActivityTest { @Rule public TestWorkflowRule testWorkflowRule = TestWorkflowRule.newBuilder() .setWorkflowTypes(GreetingWorkflowImpl.class) .setDoNotStart(true) .build(); @Test public void testActivityImpl() { testWorkflowRule .getWorker() .registerActivitiesImplementations(new HelloActivityImpl(), new ByeActivityImpl()); testWorkflowRule.getTestEnvironment().start(); // Get a workflow stub using the same task queue the worker uses. GreetingWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub( GreetingWorkflow.class, WorkflowOptions.newBuilder().setTaskQueue(testWorkflowRule.getTaskQueue()).build()); // Execute a workflow waiting for it to complete. String greeting = workflow.getGreeting("World"); assertEquals("Hello World!\nBye World!\n", greeting); testWorkflowRule.getTestEnvironment().shutdown(); } @Test public void testMockedActivity() { HelloPolymorphicActivity.HelloActivity hello = mock(HelloPolymorphicActivity.HelloActivity.class); when(hello.composeGreeting("World")).thenReturn("Hello World!"); HelloPolymorphicActivity.ByeActivity bye = mock(HelloPolymorphicActivity.ByeActivity.class); when(bye.composeGreeting("World")).thenReturn("Bye World!"); testWorkflowRule.getWorker().registerActivitiesImplementations(hello, bye); testWorkflowRule.getTestEnvironment().start(); // Get a workflow stub using the same task queue the worker uses. GreetingWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub( GreetingWorkflow.class, WorkflowOptions.newBuilder().setTaskQueue(testWorkflowRule.getTaskQueue()).build()); // Execute a workflow waiting for it to complete. String greeting = workflow.getGreeting("World"); assertEquals("Hello World!\nBye World!\n", greeting); testWorkflowRule.getTestEnvironment().shutdown(); } } ================================================ FILE: core/src/test/java/io/temporal/samples/hello/HelloQueryTest.java ================================================ package io.temporal.samples.hello; import static org.junit.Assert.assertEquals; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.samples.hello.HelloQuery.GreetingWorkflow; import io.temporal.testing.TestWorkflowRule; import java.time.Duration; import org.junit.Rule; import org.junit.Test; /** Unit test for {@link HelloQuery}. Doesn't use an external Temporal service. */ public class HelloQueryTest { @Rule public TestWorkflowRule testWorkflowRule = TestWorkflowRule.newBuilder().setWorkflowTypes(HelloQuery.GreetingWorkflowImpl.class).build(); @Test(timeout = 5000) public void testQuery() { // Get a workflow stub using the same task queue the worker uses. WorkflowOptions workflowOptions = WorkflowOptions.newBuilder().setTaskQueue(testWorkflowRule.getTaskQueue()).build(); GreetingWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub(GreetingWorkflow.class, workflowOptions); // Start workflow asynchronously to not use another thread to query. WorkflowClient.start(workflow::createGreeting, "World"); // After start for getGreeting returns, the workflow is guaranteed to be started. // So we can send a signal to it using workflow stub. assertEquals("Hello World!", workflow.queryGreeting()); // Unit tests should call testWorkflowRule.getTestEnvironment().sleep. // It allows skipping the time if workflow is just waiting on a timer // and executing tests of long running workflows very fast. // Note that this unit test executes under a second and not // over 3 as it would if Thread.sleep(3000) was called. testWorkflowRule.getTestEnvironment().sleep(Duration.ofSeconds(3)); assertEquals("Bye World!", workflow.queryGreeting()); } } ================================================ FILE: core/src/test/java/io/temporal/samples/hello/HelloSearchAttributesTest.java ================================================ package io.temporal.samples.hello; import static io.temporal.samples.hello.HelloSearchAttributes.getKeywordFromSearchAttribute; import io.temporal.api.common.v1.SearchAttributes; import io.temporal.api.common.v1.WorkflowExecution; import io.temporal.api.workflowservice.v1.DescribeWorkflowExecutionRequest; import io.temporal.api.workflowservice.v1.DescribeWorkflowExecutionResponse; import io.temporal.client.WorkflowOptions; import io.temporal.client.WorkflowStub; import io.temporal.testing.TestWorkflowRule; import java.util.Map; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; /** Unit test for {@link HelloSearchAttributes}. Doesn't use an external Temporal service. */ public class HelloSearchAttributesTest { @Rule public TestWorkflowRule testWorkflowRule = TestWorkflowRule.newBuilder() .setWorkflowTypes(HelloSearchAttributes.GreetingWorkflowImpl.class) .setDoNotStart(true) .build(); @Test public void testStartWorkflowWithSearchAttribute() { final String taskQueue = testWorkflowRule.getTaskQueue(); final String workflowId = "workflowId"; final String customKeywordField = "CustomKeywordField"; final String customKeywordValue = "CustomKeywordValue"; testWorkflowRule .getWorker() .registerActivitiesImplementations(new HelloSearchAttributes.GreetingActivitiesImpl()); testWorkflowRule.getTestEnvironment().start(); // Get a workflow stub using the same task queue the worker uses. final HelloSearchAttributes.GreetingWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub( HelloSearchAttributes.GreetingWorkflow.class, WorkflowOptions.newBuilder() .setSearchAttributes(Map.of(customKeywordField, customKeywordValue)) .setWorkflowId(workflowId) .setTaskQueue(taskQueue) .build()); final WorkflowStub untyped = WorkflowStub.fromTyped(workflow); final WorkflowExecution execution = untyped.start("Hello"); // wait until workflow completes untyped.getResult(String.class); final DescribeWorkflowExecutionResponse resp = testWorkflowRule .getWorkflowClient() .getWorkflowServiceStubs() .blockingStub() .describeWorkflowExecution( DescribeWorkflowExecutionRequest.newBuilder() .setNamespace(testWorkflowRule.getTestEnvironment().getNamespace()) .setExecution(execution) .build()); // get all search attributes final SearchAttributes searchAttributes = resp.getWorkflowExecutionInfo().getSearchAttributes(); Assert.assertEquals( customKeywordValue, getKeywordFromSearchAttribute(searchAttributes, customKeywordField)); } } ================================================ FILE: core/src/test/java/io/temporal/samples/hello/HelloSideEffectTest.java ================================================ package io.temporal.samples.hello; import static org.junit.Assert.assertEquals; import io.temporal.client.WorkflowOptions; import io.temporal.testing.TestWorkflowRule; import org.junit.Rule; import org.junit.Test; public class HelloSideEffectTest { @Rule public TestWorkflowRule testWorkflowRule = TestWorkflowRule.newBuilder() .setWorkflowTypes(HelloSideEffect.SideEffectWorkflowImpl.class) .setActivityImplementations(new HelloSideEffect.SideEffectActivitiesImpl()) .build(); @Test public void testSideffectsWorkflow() { // Get a workflow stub using the same task queue the worker uses. HelloSideEffect.SideEffectWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub( HelloSideEffect.SideEffectWorkflow.class, WorkflowOptions.newBuilder().setTaskQueue(testWorkflowRule.getTaskQueue()).build()); // Execute a workflow waiting for it to complete. String result = workflow.execute(); // make sure the result is same as the query result after workflow completion assertEquals(result, workflow.getResult()); } } ================================================ FILE: core/src/test/java/io/temporal/samples/hello/HelloSignalTest.java ================================================ package io.temporal.samples.hello; import static org.junit.Assert.assertEquals; import io.temporal.api.enums.v1.WorkflowIdReusePolicy; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.samples.hello.HelloSignal.GreetingWorkflow; import io.temporal.testing.TestWorkflowRule; import java.time.Duration; import java.util.List; import org.junit.Rule; import org.junit.Test; /** Unit test for {@link HelloSignal}. Doesn't use an external Temporal service. */ public class HelloSignalTest { @Rule public TestWorkflowRule testWorkflowRule = TestWorkflowRule.newBuilder() .setWorkflowTypes(HelloSignal.GreetingWorkflowImpl.class) .build(); @Test public void testSignal() { // Get a workflow stub using the same task queue the worker uses. WorkflowOptions workflowOptions = WorkflowOptions.newBuilder() .setTaskQueue(testWorkflowRule.getTaskQueue()) .setWorkflowIdReusePolicy( WorkflowIdReusePolicy.WORKFLOW_ID_REUSE_POLICY_REJECT_DUPLICATE) .build(); GreetingWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub(GreetingWorkflow.class, workflowOptions); // Start workflow asynchronously to not use another thread to signal. WorkflowClient.start(workflow::getGreetings); // After start for getGreeting returns, the workflow is guaranteed to be started. // So we can send a signal to it using workflow stub immediately. // But just to demonstrate the unit testing of a long running workflow adding a long sleep here. testWorkflowRule.getTestEnvironment().sleep(Duration.ofDays(1)); // This workflow keeps receiving signals until exit is called workflow.waitForName("World"); workflow.waitForName("Universe"); workflow.exit(); // Calling synchronous getGreeting after workflow has started reconnects to the existing // workflow and // blocks until result is available. Note that this behavior assumes that WorkflowOptions are // not configured // with WorkflowIdReusePolicy.AllowDuplicate. In that case the call would fail with // WorkflowExecutionAlreadyStartedException. List greetings = workflow.getGreetings(); assertEquals(2, greetings.size()); assertEquals("Hello World!", greetings.get(0)); assertEquals("Hello Universe!", greetings.get(1)); } } ================================================ FILE: core/src/test/java/io/temporal/samples/hello/HelloSignalWithStartAndWorkflowInitTest.java ================================================ package io.temporal.samples.hello; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.fail; import io.temporal.client.WorkflowFailedException; import io.temporal.client.WorkflowOptions; import io.temporal.client.WorkflowStub; import io.temporal.testing.TestWorkflowEnvironment; import io.temporal.testing.TestWorkflowExtension; import io.temporal.worker.Worker; import io.temporal.worker.WorkflowImplementationOptions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; public class HelloSignalWithStartAndWorkflowInitTest { @RegisterExtension public static final TestWorkflowExtension testWorkflowExtension = TestWorkflowExtension.newBuilder() .registerWorkflowImplementationTypes( HelloSignalWithStartAndWorkflowInit.WithInitMyWorkflowImpl.class) .registerWorkflowImplementationTypes( WorkflowImplementationOptions.newBuilder() .setFailWorkflowExceptionTypes(NullPointerException.class) .build(), HelloSignalWithStartAndWorkflowInit.WithoutInitMyWorkflowImpl.class) .setActivityImplementations( new HelloSignalWithStartAndWorkflowInit.MyGreetingActivitiesImpl()) .build(); @Test public void testWithInit(TestWorkflowEnvironment testEnv, Worker worker) { HelloSignalWithStartAndWorkflowInit.MyWorkflowWithInit withInitStub = testEnv .getWorkflowClient() .newWorkflowStub( HelloSignalWithStartAndWorkflowInit.MyWorkflowWithInit.class, WorkflowOptions.newBuilder() .setWorkflowId("with-init") .setTaskQueue(worker.getTaskQueue()) .build()); WorkflowStub.fromTyped(withInitStub) .signalWithStart( "addGreeting", new Object[] {new HelloSignalWithStartAndWorkflowInit.Person("Michael", "Jordan", 55)}, new Object[] {new HelloSignalWithStartAndWorkflowInit.Person("John", "Stockton", 57)}); String result = WorkflowStub.fromTyped(withInitStub).getResult(String.class); assertEquals("Hello Michael Jordan,Hello John Stockton", result); } @Test public void testWithoutInit(TestWorkflowEnvironment testEnv, Worker worker) { HelloSignalWithStartAndWorkflowInit.MyWorkflowNoInit noInitStub = testEnv .getWorkflowClient() .newWorkflowStub( HelloSignalWithStartAndWorkflowInit.MyWorkflowNoInit.class, WorkflowOptions.newBuilder() .setWorkflowId("without-init") .setTaskQueue(worker.getTaskQueue()) .build()); WorkflowStub.fromTyped(noInitStub) .signalWithStart( "addGreeting", new Object[] {new HelloSignalWithStartAndWorkflowInit.Person("Michael", "Jordan", 55)}, new Object[] {new HelloSignalWithStartAndWorkflowInit.Person("John", "Stockton", 57)}); try { WorkflowStub.fromTyped(noInitStub).getResult(String.class); fail("Workflow execution should have failed"); } catch (Exception e) { if (!(e instanceof WorkflowFailedException)) { fail("Workflow execution should have failed with WorkflowFailedException"); } } } } ================================================ FILE: core/src/test/java/io/temporal/samples/hello/HelloSignalWithTimerTest.java ================================================ package io.temporal.samples.hello; import io.temporal.api.common.v1.WorkflowExecution; import io.temporal.api.enums.v1.WorkflowExecutionStatus; import io.temporal.api.workflowservice.v1.DescribeWorkflowExecutionRequest; import io.temporal.api.workflowservice.v1.DescribeWorkflowExecutionResponse; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.client.WorkflowStub; import io.temporal.testing.TestWorkflowRule; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; public class HelloSignalWithTimerTest { @Rule public TestWorkflowRule testWorkflowRule = TestWorkflowRule.newBuilder() .setWorkflowTypes(HelloSignalWithTimer.SignalWithTimerWorkflowImpl.class) .setActivityImplementations(new HelloSignalWithTimer.ValueProcessingActivitiesImpl()) .build(); private static final String WORKFLOW_ID = "SignalWithTimerTestWorkflow"; @Test public void testSignalWithTimer() { HelloSignalWithTimer.SignalWithTimerWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub( HelloSignalWithTimer.SignalWithTimerWorkflow.class, WorkflowOptions.newBuilder() .setTaskQueue(testWorkflowRule.getTaskQueue()) .setWorkflowId(WORKFLOW_ID) .build()); WorkflowClient.start(workflow::execute); workflow.newValue("1"); workflow.newValue("2"); workflow.exit(); WorkflowStub.fromTyped(workflow).getResult(Void.class); DescribeWorkflowExecutionResponse res = testWorkflowRule .getWorkflowClient() .getWorkflowServiceStubs() .blockingStub() .describeWorkflowExecution( DescribeWorkflowExecutionRequest.newBuilder() .setNamespace(testWorkflowRule.getTestEnvironment().getNamespace()) .setExecution(WorkflowExecution.newBuilder().setWorkflowId(WORKFLOW_ID).build()) .build()); Assert.assertEquals( res.getWorkflowExecutionInfo().getStatus(), WorkflowExecutionStatus.WORKFLOW_EXECUTION_STATUS_COMPLETED); } } ================================================ FILE: core/src/test/java/io/temporal/samples/hello/HelloStandaloneActivityTest.java ================================================ package io.temporal.samples.hello; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.Mockito.withSettings; import io.temporal.activity.ActivityOptions; import io.temporal.client.WorkflowOptions; import io.temporal.samples.hello.HelloStandaloneActivity.GreetingActivities; import io.temporal.samples.hello.HelloStandaloneActivity.GreetingActivitiesImpl; import io.temporal.testing.TestWorkflowRule; import io.temporal.workflow.Workflow; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; import java.time.Duration; import org.junit.Rule; import org.junit.Test; /** * Unit tests for {@link HelloStandaloneActivity}. Uses an embedded Temporal test server so no * external service is required. * *

Standalone Activities do not use a Workflow at runtime, but the embedded test server only * supports Activity execution through a Workflow. These tests therefore drive the Activity through * a minimal wrapper Workflow so the Activity logic is exercised against the real SDK worker stack. */ public class HelloStandaloneActivityTest { /** * Minimal wrapper Workflow used to invoke {@link GreetingActivities} through the embedded test * worker. */ @WorkflowInterface public interface TestWorkflow { @WorkflowMethod String run(String greeting, String name); } public static class TestWorkflowImpl implements TestWorkflow { private final GreetingActivities activities = Workflow.newActivityStub( GreetingActivities.class, ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(5)).build()); @Override public String run(String greeting, String name) { return activities.composeGreeting(greeting, name); } } @Rule public TestWorkflowRule testWorkflowRule = TestWorkflowRule.newBuilder() .setWorkflowTypes(TestWorkflowImpl.class) .setDoNotStart(true) .build(); @Test public void testActivityImpl() { testWorkflowRule.getWorker().registerActivitiesImplementations(new GreetingActivitiesImpl()); testWorkflowRule.getTestEnvironment().start(); TestWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub( TestWorkflow.class, WorkflowOptions.newBuilder().setTaskQueue(testWorkflowRule.getTaskQueue()).build()); assertEquals("Hello, World!", workflow.run("Hello", "World")); testWorkflowRule.getTestEnvironment().shutdown(); } @Test public void testMockedActivity() { // withoutAnnotations() prevents Mockito from copying @ActivityMethod from the interface onto // the mock, which would cause worker registration to fail. GreetingActivities activities = mock(GreetingActivities.class, withSettings().withoutAnnotations()); when(activities.composeGreeting("Hello", "World")).thenReturn("Hello, World!"); testWorkflowRule.getWorker().registerActivitiesImplementations(activities); testWorkflowRule.getTestEnvironment().start(); TestWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub( TestWorkflow.class, WorkflowOptions.newBuilder().setTaskQueue(testWorkflowRule.getTaskQueue()).build()); assertEquals("Hello, World!", workflow.run("Hello", "World")); verify(activities).composeGreeting("Hello", "World"); testWorkflowRule.getTestEnvironment().shutdown(); } } ================================================ FILE: core/src/test/java/io/temporal/samples/hello/HelloUpdateAndCancellationTest.java ================================================ package io.temporal.samples.hello; import io.temporal.activity.*; import io.temporal.api.enums.v1.WorkflowIdConflictPolicy; import io.temporal.client.*; import io.temporal.failure.ActivityFailure; import io.temporal.failure.CanceledFailure; import io.temporal.testing.TestWorkflowRule; import io.temporal.workflow.*; import java.time.Duration; import java.util.concurrent.TimeUnit; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; public class HelloUpdateAndCancellationTest { @Rule public TestWorkflowRule testWorkflowRule = TestWorkflowRule.newBuilder() .setWorkflowTypes(TestWorkflowImpl.class) .setActivityImplementations(new TestActivitiesImpl()) .build(); @Test public void testUpdateAndWorkflowCancellation() { // Start workflow with UpdateWithStart then cancel workflow before activity completes TestWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub( TestWorkflow.class, WorkflowOptions.newBuilder() .setWorkflowId("test-workflow-cancel") .setTaskQueue(testWorkflowRule.getTaskQueue()) .setWorkflowIdConflictPolicy( WorkflowIdConflictPolicy.WORKFLOW_ID_CONFLICT_POLICY_USE_EXISTING) .build()); WorkflowUpdateHandle updateHandle = WorkflowClient.startUpdateWithStart( workflow::mileStoneCompleted, UpdateOptions.newBuilder() .setWaitForStage(WorkflowUpdateStage.ACCEPTED) .build(), new WithStartWorkflowOperation<>(workflow::execute)); testWorkflowRule .getTestEnvironment() .registerDelayedCallback( Duration.ofSeconds(3), () -> { WorkflowStub.fromTyped(workflow).cancel("canceled by test"); }); String updateResult = updateHandle.getResult(); Assert.assertEquals("milestone canceled", updateResult); try { WorkflowStub.fromTyped(workflow).getResult(String.class); Assert.fail("Workflow Execution should have been canceled"); } catch (WorkflowFailedException e) { // Our workflow should have been canceled Assert.assertEquals(CanceledFailure.class, e.getCause().getClass()); } } @Test public void testUpdateAndActivityCancellation() { // Start workflow with UpdateWithStart then cancel the activity only by sending signal to // execution TestWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub( TestWorkflow.class, WorkflowOptions.newBuilder() .setWorkflowId("test-activity-cancel") .setTaskQueue(testWorkflowRule.getTaskQueue()) .setWorkflowIdConflictPolicy( WorkflowIdConflictPolicy.WORKFLOW_ID_CONFLICT_POLICY_USE_EXISTING) .build()); WorkflowUpdateHandle updateHandle = WorkflowClient.startUpdateWithStart( workflow::mileStoneCompleted, UpdateOptions.newBuilder() .setWaitForStage(WorkflowUpdateStage.ACCEPTED) .build(), new WithStartWorkflowOperation<>(workflow::execute)); testWorkflowRule .getTestEnvironment() .registerDelayedCallback( Duration.ofSeconds(3), () -> { WorkflowStub.fromTyped(workflow).signal("cancelActivity"); }); String updateResult = updateHandle.getResult(); Assert.assertEquals("milestone canceled", updateResult); try { WorkflowStub.fromTyped(workflow).getResult(String.class); Assert.fail("Workflow Execution should have failed"); } catch (WorkflowFailedException e) { // In this case we did not cancel workflow execution but we failed it by throwing // ActivityFailure Assert.assertEquals(ActivityFailure.class, e.getCause().getClass()); ActivityFailure af = (ActivityFailure) e.getCause(); // Since we canceled the activity still, the cause of ActivityFailure should be // CanceledFailure Assert.assertEquals(CanceledFailure.class, af.getCause().getClass()); } } @WorkflowInterface public interface TestWorkflow { @WorkflowMethod String execute(); @UpdateMethod String mileStoneCompleted(); @SignalMethod void cancelActivity(); } public static class TestWorkflowImpl implements TestWorkflow { boolean milestoneDone, mileStoneCanceled; CancellationScope scope; TestActivities activities = Workflow.newActivityStub( TestActivities.class, ActivityOptions.newBuilder() .setHeartbeatTimeout(Duration.ofSeconds(3)) .setStartToCloseTimeout(Duration.ofSeconds(10)) .setCancellationType(ActivityCancellationType.WAIT_CANCELLATION_COMPLETED) .build()); @Override public String execute() { scope = Workflow.newCancellationScope( () -> { activities.runActivity(); }); try { scope.run(); milestoneDone = true; Workflow.await(Workflow::isEveryHandlerFinished); return "workflow completed"; } catch (ActivityFailure e) { if (e.getCause() instanceof CanceledFailure) { CancellationScope detached = Workflow.newDetachedCancellationScope( () -> { mileStoneCanceled = true; Workflow.await(Workflow::isEveryHandlerFinished); }); detached.run(); } throw e; } } @Override public String mileStoneCompleted() { Workflow.await(() -> milestoneDone || mileStoneCanceled); // For sake of testing isEveryHandlerFinished block here for 2 seconds Workflow.sleep(Duration.ofSeconds(2)); return milestoneDone ? "milestone completed" : "milestone canceled"; } @Override public void cancelActivity() { if (scope != null) { scope.cancel("test reason"); } } } @ActivityInterface public interface TestActivities { void runActivity(); } public static class TestActivitiesImpl implements TestActivities { @Override public void runActivity() { ActivityExecutionContext context = Activity.getExecutionContext(); for (int i = 0; i < 9; i++) { sleep(1); try { context.heartbeat(i); } catch (ActivityCompletionException e) { throw e; } } } } private static void sleep(int seconds) { try { Thread.sleep(TimeUnit.SECONDS.toMillis(seconds)); } catch (InterruptedException e) { } } } ================================================ FILE: core/src/test/java/io/temporal/samples/hello/HelloUpdateTest.java ================================================ package io.temporal.samples.hello; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.*; import io.temporal.api.enums.v1.WorkflowIdReusePolicy; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.samples.hello.HelloUpdate.GreetingWorkflow; import io.temporal.testing.TestWorkflowRule; import java.time.Duration; import java.util.List; import org.junit.Rule; import org.junit.Test; /** Unit test for {@link HelloUpdateTest}. Doesn't use an external Temporal service. */ public class HelloUpdateTest { @Rule public TestWorkflowRule testWorkflowRule = TestWorkflowRule.newBuilder() .setWorkflowTypes(HelloUpdate.GreetingWorkflowImpl.class) .setDoNotStart(true) .build(); @Test public void testUpdate() { // Setup mocks HelloActivity.GreetingActivities activities = mock(HelloActivity.GreetingActivities.class, withSettings().withoutAnnotations()); when(activities.composeGreeting("Hello", "World")).thenReturn("Hello World!"); when(activities.composeGreeting("Hello", "Universe")).thenReturn("Hello Universe!"); testWorkflowRule.getWorker().registerActivitiesImplementations(activities); testWorkflowRule.getTestEnvironment().start(); // Get a workflow stub using the same task queue the worker uses. WorkflowOptions workflowOptions = WorkflowOptions.newBuilder() .setTaskQueue(testWorkflowRule.getTaskQueue()) .setWorkflowIdReusePolicy( WorkflowIdReusePolicy.WORKFLOW_ID_REUSE_POLICY_REJECT_DUPLICATE) .build(); GreetingWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub(GreetingWorkflow.class, workflowOptions); // Start workflow asynchronously to not use another thread to update. WorkflowClient.start(workflow::getGreetings); // After start for getGreeting returns, the workflow is guaranteed to be started. // So we can send a update to it using workflow stub immediately. // But just to demonstrate the unit testing of a long running workflow adding a long sleep here. testWorkflowRule.getTestEnvironment().sleep(Duration.ofDays(1)); // This workflow keeps receiving updates until exit is called assertEquals(1, workflow.addGreeting("World")); assertEquals(2, workflow.addGreeting("Universe")); workflow.exit(); // Calling synchronous getGreeting after workflow has started reconnects to the existing // workflow and // blocks until result is available. Note that this behavior assumes that WorkflowOptions are // not configured // with WorkflowIdReusePolicy.AllowDuplicate. In that case the call would fail with // WorkflowExecutionAlreadyStartedException. List greetings = workflow.getGreetings(); assertEquals(2, greetings.size()); assertEquals("Hello World!", greetings.get(0)); assertEquals("Hello Universe!", greetings.get(1)); } } ================================================ FILE: core/src/test/java/io/temporal/samples/hello/HelloWorkflowTimerTest.java ================================================ package io.temporal.samples.hello; import io.temporal.client.WorkflowOptions; import io.temporal.testing.TestWorkflowRule; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; public class HelloWorkflowTimerTest { @Rule public TestWorkflowRule testWorkflowRule = TestWorkflowRule.newBuilder() .setWorkflowTypes( HelloWorkflowTimer.WorkflowWithTimerImpl.class, HelloWorkflowTimer.WorkflowWithTimerChildWorkflowImpl.class) .setActivityImplementations(new HelloWorkflowTimer.WorkflowWithTimerActivitiesImpl()) .build(); @Test public void testWorkflowTimer() { HelloWorkflowTimer.WorkflowWithTimer workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub( HelloWorkflowTimer.WorkflowWithTimer.class, WorkflowOptions.newBuilder() .setWorkflowId("WorkflowWithTimerTestId") .setTaskQueue(testWorkflowRule.getTaskQueue()) .build()); String result = workflow.execute("test input"); Assert.assertEquals("Workflow timer fired while activities were executing.", result); } } ================================================ FILE: core/src/test/java/io/temporal/samples/interceptorreplaytest/InterceptorReplayTest.java ================================================ package io.temporal.samples.interceptorreplaytest; import static org.junit.Assert.fail; import io.temporal.activity.ActivityInterface; import io.temporal.activity.ActivityOptions; import io.temporal.client.WorkflowOptions; import io.temporal.common.WorkflowExecutionHistory; import io.temporal.common.interceptors.*; import io.temporal.testing.TestWorkflowEnvironment; import io.temporal.testing.TestWorkflowExtension; import io.temporal.testing.WorkflowReplayer; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactoryOptions; import io.temporal.workflow.Workflow; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; import java.time.Duration; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; public class InterceptorReplayTest { @RegisterExtension public static final TestWorkflowExtension testWorkflowExtension = TestWorkflowExtension.newBuilder() // Register workflow and activity impls .registerWorkflowImplementationTypes(TestWorkflowImpl.class) .setActivityImplementations(new TestActivitiesImpl()) // Register worker interceptor .setWorkerFactoryOptions( WorkerFactoryOptions.newBuilder() .setWorkerInterceptors(new TestWorkerInterceptor()) .build()) .setDoNotStart(true) .build(); @Test public void testReplayWithInterceptors(TestWorkflowEnvironment testEnv, Worker worker) { // Run our test workflow. We need to set workflow id so can get history after testEnv.start(); TestWorkflow workflow = testEnv .getWorkflowClient() .newWorkflowStub( TestWorkflow.class, WorkflowOptions.newBuilder() .setWorkflowId("test-workflow") .setTaskQueue(worker.getTaskQueue()) .build()); workflow.execute(); // Replay execution with history of just executed WorkflowExecutionHistory eventHistory = testEnv.getWorkflowClient().fetchHistory("test-workflow"); try { WorkflowReplayer.replayWorkflowExecution(eventHistory, worker); } catch (Exception e) { fail(e.getMessage()); } testEnv.shutdown(); // Try replaying execution with test env where we dont have interceptors registered TestWorkflowEnvironment testEnv2 = TestWorkflowEnvironment.newInstance(); Worker testEnv2Worker = testEnv2.newWorker("test-taskqueue"); testEnv2Worker.registerWorkflowImplementationTypes(TestWorkflowImpl.class); testEnv2Worker.registerActivitiesImplementations(new TestActivitiesImpl()); testEnv2.start(); // Replay should fail with worker that does not have interceptor registered try { WorkflowReplayer.replayWorkflowExecution(eventHistory, testEnv2Worker); fail("This should have failed"); } catch (Exception e) { System.out.println(e.getMessage()); } // But it should be fine with worker that does try { WorkflowReplayer.replayWorkflowExecution(eventHistory, worker); } catch (Exception e) { fail(e.getMessage()); } testEnv2.shutdown(); } // Test workflow and activities @WorkflowInterface public interface TestWorkflow { @WorkflowMethod void execute(); } public static class TestWorkflowImpl implements TestWorkflow { TestActivities activities = Workflow.newActivityStub( TestActivities.class, ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(2)).build()); @Override public void execute() { activities.activityOne(); } } @ActivityInterface public interface TestActivities { void activityOne(); void activityTwo(); void activityThree(); } public static class TestActivitiesImpl implements TestActivities { @Override public void activityOne() { System.out.println("Activities one done"); } @Override public void activityTwo() { System.out.println("Activities two done"); } @Override public void activityThree() { System.out.println("Activities three done"); } } // Test worker and workflow interceptors public static class TestWorkerInterceptor extends WorkerInterceptorBase { @Override public WorkflowInboundCallsInterceptor interceptWorkflow(WorkflowInboundCallsInterceptor next) { return new TestWorkflowInboundCallsInterceptor(next); } } public static class TestWorkflowInboundCallsInterceptor extends WorkflowInboundCallsInterceptorBase { TestActivities activities = Workflow.newActivityStub( TestActivities.class, ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(2)).build()); public TestWorkflowInboundCallsInterceptor(WorkflowInboundCallsInterceptor next) { super(next); } @Override public void init(WorkflowOutboundCallsInterceptor outboundCalls) { super.init(new TestWorkflowOutboundCallsInterceptor(outboundCalls)); } @Override public WorkflowOutput execute(WorkflowInput input) { WorkflowOutput output = super.execute(input); // Run activity three before completing execution activities.activityThree(); return output; } } public static class TestWorkflowOutboundCallsInterceptor extends WorkflowOutboundCallsInterceptorBase { TestActivities activities = Workflow.newActivityStub( TestActivities.class, ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(2)).build()); public TestWorkflowOutboundCallsInterceptor(WorkflowOutboundCallsInterceptor next) { super(next); } @Override public ActivityOutput executeActivity(ActivityInput input) { ActivityOutput output = super.executeActivity(input); // we only want to intercept ActivityOne here if (input.getActivityName().equals("ActivityOne")) { activities.activityTwo(); } return output; } } } ================================================ FILE: core/src/test/java/io/temporal/samples/listworkflows/ListWorkflowsTest.java ================================================ package io.temporal.samples.listworkflows; import static org.junit.Assert.assertEquals; import io.temporal.api.workflow.v1.WorkflowExecutionInfo; import io.temporal.api.workflowservice.v1.ListOpenWorkflowExecutionsRequest; import io.temporal.api.workflowservice.v1.ListOpenWorkflowExecutionsResponse; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.testing.TestWorkflowRule; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Rule; import org.junit.Test; public class ListWorkflowsTest { @Rule public TestWorkflowRule testWorkflowRule = TestWorkflowRule.newBuilder() .setWorkflowTypes(CustomerWorkflowImpl.class) .setActivityImplementations(new CustomerActivitiesImpl()) .build(); @Test public void testActivityImpl() { // create some fake customers List customers = new ArrayList<>(); customers.add(new Customer("c1", "John", "john@john.com", "new")); customers.add(new Customer("c2", "Mary", "mary@mary.com", "established")); customers.add(new Customer("c3", "Richard", "richard@richard.com", "established")); customers.add(new Customer("c4", "Anna", "anna@anna.com", "new")); customers.add(new Customer("c5", "Michael", "michael@michael.com", "established")); startWorkflows(customers); List openExecutions = getExecutionsResponse(); assertEquals(5, openExecutions.size()); // signal exit to all customer workflows stopWorkflows(customers); } private void startWorkflows(List customers) { // start a workflow for each customer that we need to add message to account for (Customer c : customers) { String message = "New message for: " + c.getName(); WorkflowOptions newCustomerWorkflowOptions = WorkflowOptions.newBuilder() .setWorkflowId(c.getAccountNum()) .setTaskQueue(testWorkflowRule.getTaskQueue()) // set the search attributes for this customer workflow .setSearchAttributes(generateSearchAttributesFor(c)) .build(); CustomerWorkflow newCustomerWorkflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub(CustomerWorkflow.class, newCustomerWorkflowOptions); // start async WorkflowClient.start(newCustomerWorkflow::updateAccountMessage, c, message); } } private Map generateSearchAttributesFor(Customer customer) { Map searchAttributes = new HashMap<>(); searchAttributes.put("CustomStringField", customer.getCustomerType()); return searchAttributes; } private List getExecutionsResponse() { // List open workflows and validate their types ListOpenWorkflowExecutionsRequest listRequest = ListOpenWorkflowExecutionsRequest.newBuilder() .setNamespace(testWorkflowRule.getTestEnvironment().getNamespace()) .build(); ListOpenWorkflowExecutionsResponse listResponse = testWorkflowRule .getTestEnvironment() .getWorkflowService() .blockingStub() .listOpenWorkflowExecutions(listRequest); return listResponse.getExecutionsList(); } private void stopWorkflows(List customers) { for (Customer c : customers) { CustomerWorkflow existingCustomerWorkflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub(CustomerWorkflow.class, c.getAccountNum()); // signal the exist method to stop execution existingCustomerWorkflow.exit(); } } } ================================================ FILE: core/src/test/java/io/temporal/samples/metrics/MetricsTest.java ================================================ package io.temporal.samples.metrics; import static junit.framework.TestCase.assertEquals; import com.google.common.collect.ImmutableMap; import com.uber.m3.tally.RootScopeBuilder; import com.uber.m3.tally.Scope; import com.uber.m3.tally.StatsReporter; import com.uber.m3.util.Duration; import io.micrometer.core.instrument.Counter; import io.micrometer.core.instrument.ImmutableTag; import io.micrometer.core.instrument.Tag; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.common.reporter.MicrometerClientStatsReporter; import io.temporal.samples.metrics.activities.MetricsActivitiesImpl; import io.temporal.samples.metrics.workflow.MetricsWorkflow; import io.temporal.samples.metrics.workflow.MetricsWorkflowImpl; import io.temporal.serviceclient.MetricsTag; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.serviceclient.WorkflowServiceStubsOptions; import io.temporal.testing.TestWorkflowRule; import io.temporal.worker.WorkerOptions; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.jetbrains.annotations.NotNull; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; public class MetricsTest { private static final long REPORTING_FLUSH_TIME = 50; private static List TAGS_NAMESPACE_QUEUE; private final String SDK_CUSTOM_KEY = "sdkCustomTag1Key"; private final String SDK_CUSTOM_VALUE = "sdkCustomTag1Value"; private final SimpleMeterRegistry registry = new SimpleMeterRegistry(); private final StatsReporter reporter = new MicrometerClientStatsReporter(registry); private final Scope metricsScope = new RootScopeBuilder() .tags(ImmutableMap.of(SDK_CUSTOM_KEY, SDK_CUSTOM_VALUE)) .reporter(reporter) .reportEvery(Duration.ofMillis(REPORTING_FLUSH_TIME >> 1)); private final String TEST_NAMESPACE = "UnitTest"; @Rule public TestWorkflowRule testWorkflowRule = TestWorkflowRule.newBuilder() .setWorkflowTypes(MetricsWorkflowImpl.class) .setMetricsScope(metricsScope) .setWorkerOptions(WorkerOptions.newBuilder().build()) .setActivityImplementations(new MetricsActivitiesImpl()) .build(); private WorkflowServiceStubs clientStubs; private WorkflowClient workflowClient; private static List replaceTags(List tags, String... nameValuePairs) { for (int i = 0; i < nameValuePairs.length; i += 2) { tags = replaceTag(tags, nameValuePairs[i], nameValuePairs[i + 1]); } return tags; } private static List replaceTag(List tags, String name, String value) { List result = tags.stream().filter(tag -> !name.equals(tag.getKey())).collect(Collectors.toList()); result.add(new ImmutableTag(name, value)); return result; } @Before public void setUp() { final WorkflowServiceStubsOptions options = testWorkflowRule.getWorkflowClient().getWorkflowServiceStubs().getOptions(); this.clientStubs = WorkflowServiceStubs.newServiceStubs(options); this.workflowClient = WorkflowClient.newInstance(clientStubs, testWorkflowRule.getWorkflowClient().getOptions()); final Map stringStringMap = MetricsTag.defaultTags(TEST_NAMESPACE); final List TAGS_NAMESPACE = stringStringMap.entrySet().stream() .map( nameValueEntry -> new ImmutableTag(nameValueEntry.getKey(), nameValueEntry.getValue())) .collect(Collectors.toList()); TAGS_NAMESPACE_QUEUE = replaceTags(TAGS_NAMESPACE, MetricsTag.TASK_QUEUE, testWorkflowRule.getTaskQueue()); } @After public void tearDown() { this.clientStubs.shutdownNow(); this.registry.close(); } @Test public void testCountActivityRetriesMetric() throws InterruptedException { final MetricsWorkflow metricsWorkflow = workflowClient.newWorkflowStub( MetricsWorkflow.class, WorkflowOptions.newBuilder() .setTaskQueue(testWorkflowRule.getTaskQueue()) .validateBuildWithDefaults()); metricsWorkflow.exec("hello metrics"); Thread.sleep(REPORTING_FLUSH_TIME); assertIntCounter(4, countMetricActivityRetriesForActivity("PerformB")); assertIntCounter(2, countMetricActivityRetriesForActivity("PerformA")); } @NotNull private Counter countMetricActivityRetriesForActivity(String performB) { final List tags = replaceTags( TAGS_NAMESPACE_QUEUE, MetricsTag.ACTIVITY_TYPE, performB, MetricsTag.WORKFLOW_TYPE, "MetricsWorkflow", MetricsTag.WORKER_TYPE, "ActivityWorker", SDK_CUSTOM_KEY, SDK_CUSTOM_VALUE); return registry.counter("custom_activity_retries", tags); } private void assertIntCounter(int expectedValue, Counter counter) { assertEquals(expectedValue, Math.round(counter.count())); } } ================================================ FILE: core/src/test/java/io/temporal/samples/moneybatch/TransferWorkflowTest.java ================================================ package io.temporal.samples.moneybatch; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.client.WorkflowStub; import io.temporal.testing.TestWorkflowRule; import java.util.Random; import java.util.UUID; import org.junit.Rule; import org.junit.Test; public class TransferWorkflowTest { @Rule public TestWorkflowRule testWorkflowRule = TestWorkflowRule.newBuilder() .setWorkflowTypes(AccountTransferWorkflowImpl.class) .setDoNotStart(true) .build(); @Test public void testTransfer() { Account activities = mock(Account.class); testWorkflowRule.getWorker().registerActivitiesImplementations(activities); testWorkflowRule.getTestEnvironment().start(); String from = "account1"; String to = "account2"; int batchSize = 5; WorkflowOptions options = WorkflowOptions.newBuilder() .setTaskQueue(testWorkflowRule.getTaskQueue()) .setWorkflowId(to) .build(); AccountTransferWorkflow transferWorkflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub(AccountTransferWorkflow.class, options); WorkflowClient.start(transferWorkflow::deposit, to, batchSize); Random random = new Random(); int total = 0; for (int i = 0; i < batchSize; i++) { int amountCents = random.nextInt(1000); transferWorkflow.withdraw(from, UUID.randomUUID().toString(), amountCents); total += amountCents; } // Wait for workflow to finish WorkflowStub.fromTyped(transferWorkflow).getResult(Void.class); verify(activities).deposit(eq("account2"), any(), eq(total)); testWorkflowRule.getTestEnvironment().shutdown(); } } ================================================ FILE: core/src/test/java/io/temporal/samples/moneytransfer/TransferWorkflowTest.java ================================================ package io.temporal.samples.moneytransfer; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import io.temporal.client.WorkflowOptions; import io.temporal.testing.TestWorkflowRule; import org.junit.Rule; import org.junit.Test; public class TransferWorkflowTest { @Rule public TestWorkflowRule testWorkflowRule = TestWorkflowRule.newBuilder() .setWorkflowTypes(AccountTransferWorkflowImpl.class) .setDoNotStart(true) .build(); @Test public void testTransfer() { Account activities = mock(Account.class); testWorkflowRule.getWorker().registerActivitiesImplementations(activities); testWorkflowRule.getTestEnvironment().start(); WorkflowOptions options = WorkflowOptions.newBuilder().setTaskQueue(testWorkflowRule.getTaskQueue()).build(); AccountTransferWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub(AccountTransferWorkflow.class, options); long start = testWorkflowRule.getTestEnvironment().currentTimeMillis(); workflow.transfer("account1", "account2", "reference1", 123); long duration = testWorkflowRule.getTestEnvironment().currentTimeMillis() - start; System.out.println("Duration hours: " + duration / 3600000); verify(activities).withdraw(eq("account1"), eq("reference1"), eq(123)); verify(activities).deposit(eq("account2"), eq("reference1"), eq(123)); testWorkflowRule.getTestEnvironment().shutdown(); } } ================================================ FILE: core/src/test/java/io/temporal/samples/nexus/caller/CallerWorkflowJunit5MockTest.java ================================================ package io.temporal.samples.nexus.caller; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.*; import io.temporal.samples.nexus.handler.EchoClient; import io.temporal.samples.nexus.handler.HelloHandlerWorkflow; import io.temporal.samples.nexus.handler.SampleNexusServiceImpl; import io.temporal.samples.nexus.service.SampleNexusService; import io.temporal.testing.TestWorkflowEnvironment; import io.temporal.testing.TestWorkflowExtension; import io.temporal.worker.Worker; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; // This is an example of how to unit test Nexus services in JUnit5. The handlers are mocked, // so that the caller classes interact with the mocks and not the handler classes themselves. // @@@SNIPSTART java-nexus-sample-junit5-mock public class CallerWorkflowJunit5MockTest { // Sync Nexus operations run inline in the handler thread — there is no backing workflow to // register a factory for. To mock one, inject a mock dependency into the service implementation. private static final EchoClient mockEchoClient = mock(EchoClient.class); @RegisterExtension public static final TestWorkflowExtension testWorkflowExtension = TestWorkflowExtension.newBuilder() // If a Nexus service is registered as part of the test as in the following line of code, // the TestWorkflowExtension will, by default, automatically create a Nexus service // endpoint and workflows registered as part of the TestWorkflowExtension will // automatically inherit the endpoint if none is set. .setNexusServiceImplementation(new SampleNexusServiceImpl(mockEchoClient)) // The Echo Nexus handler service just makes a call to a class, so no extra setup is // needed. But the Hello Nexus service needs a worker for both the caller and handler // in order to run, and the Echo Nexus caller service needs a worker. // // registerWorkflowImplementationTypes will take the classes given and create workers for // them, enabling workflows to run. .registerWorkflowImplementationTypes( HelloCallerWorkflowImpl.class, EchoCallerWorkflowImpl.class) .setDoNotStart(true) .build(); @Test public void testHelloWorkflow( TestWorkflowEnvironment testEnv, Worker worker, HelloCallerWorkflow workflow) { // Workflows started by a Nexus service can be mocked just like any other workflow worker.registerWorkflowImplementationFactory( HelloHandlerWorkflow.class, () -> { HelloHandlerWorkflow mockHandler = mock(HelloHandlerWorkflow.class); when(mockHandler.hello(any())) .thenReturn(new SampleNexusService.HelloOutput("Hello Mock World 👋")); return mockHandler; }); testEnv.start(); // Execute a workflow waiting for it to complete. String greeting = workflow.hello("World", SampleNexusService.Language.EN); assertEquals("Hello Mock World 👋", greeting); testEnv.shutdown(); } @Test public void testEchoWorkflow( TestWorkflowEnvironment testEnv, Worker worker, EchoCallerWorkflow workflow) { // Sync Nexus operations run inline in the handler thread — there is no backing workflow to // register a factory for. Instead, stub the injected EchoClient dependency directly. when(mockEchoClient.echo(any())).thenReturn(new SampleNexusService.EchoOutput("mocked echo")); testEnv.start(); // Execute a workflow waiting for it to complete. String greeting = workflow.echo("Hello"); assertEquals("mocked echo", greeting); testEnv.shutdown(); } } // @@@SNIPEND ================================================ FILE: core/src/test/java/io/temporal/samples/nexus/caller/CallerWorkflowJunit5Test.java ================================================ package io.temporal.samples.nexus.caller; import static org.junit.jupiter.api.Assertions.assertEquals; import io.temporal.samples.nexus.handler.HelloHandlerWorkflowImpl; import io.temporal.samples.nexus.handler.SampleNexusServiceImpl; import io.temporal.samples.nexus.service.SampleNexusService; import io.temporal.testing.TestWorkflowEnvironment; import io.temporal.testing.TestWorkflowExtension; import io.temporal.worker.Worker; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; // This is an example of how to unit test Nexus services in JUnit5. The handlers are not mocked, // but are actually called by the testing framework by the caller classes. public class CallerWorkflowJunit5Test { @RegisterExtension public static final TestWorkflowExtension testWorkflowExtension = TestWorkflowExtension.newBuilder() // If a Nexus service is registered as part of the test as in the following line of code, // the TestWorkflowExtension will, by default, automatically create a Nexus service // endpoint and workflows registered as part of the TestWorkflowExtension will // automatically inherit the endpoint if none is set. .setNexusServiceImplementation(new SampleNexusServiceImpl()) // The Echo Nexus handler service just makes a call to a class, so no extra setup is // needed. But the Hello Nexus service needs a worker for both the caller and handler // in order to run, and the Echo Nexus caller service needs a worker. // // registerWorkflowImplementationTypes will take the classes given and create workers for // them, enabling workflows to run. .registerWorkflowImplementationTypes( HelloCallerWorkflowImpl.class, HelloHandlerWorkflowImpl.class, EchoCallerWorkflowImpl.class) // The workflow will start before each test, and will shut down after each test. // See CallerWorkflowTest for an example of how to control this differently if needed. .build(); // The TestWorkflowExtension extension in the Temporal testing library creates the // arguments to the test cases and initializes them from the extension setup call above. @Test public void testHelloWorkflow( TestWorkflowEnvironment testEnv, Worker worker, HelloCallerWorkflow workflow) { // Execute a workflow waiting for it to complete. String greeting = workflow.hello("World", SampleNexusService.Language.EN); assertEquals("Hello World 👋", greeting); } @Test public void testEchoWorkflow( TestWorkflowEnvironment testEnv, Worker worker, EchoCallerWorkflow workflow) { // Execute a workflow waiting for it to complete. String greeting = workflow.echo("Hello"); assertEquals("Hello", greeting); } } ================================================ FILE: core/src/test/java/io/temporal/samples/nexus/caller/CallerWorkflowMockTest.java ================================================ package io.temporal.samples.nexus.caller; import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import io.temporal.client.WorkflowOptions; import io.temporal.samples.nexus.handler.EchoClient; import io.temporal.samples.nexus.handler.HelloHandlerWorkflow; import io.temporal.samples.nexus.handler.SampleNexusServiceImpl; import io.temporal.samples.nexus.service.SampleNexusService; import io.temporal.testing.TestWorkflowRule; import org.junit.Rule; import org.junit.Test; // This is an example of how to unit test Nexus services in JUnit4. The handlers are mocked, // so that the caller classes interact with the mocks and not the handler classes themselves. // @@@SNIPSTART java-nexus-sample-junit4-mock public class CallerWorkflowMockTest { // Inject a mock EchoClient so sync Nexus operations can be stubbed per test. // JUnit 4 creates a new test class instance per test method, so this mock is fresh each time. private final EchoClient mockEchoClient = mock(EchoClient.class); @Rule public TestWorkflowRule testWorkflowRule = TestWorkflowRule.newBuilder() // If a Nexus service is registered as part of the test as in the following line of code, // the TestWorkflowRule will, by default, automatically create a Nexus service endpoint // and workflows registered as part of the TestWorkflowRule // will automatically inherit the endpoint if none is set. .setNexusServiceImplementation(new SampleNexusServiceImpl(mockEchoClient)) // The Echo Nexus handler service just makes a call to a class, so no extra setup is // needed. But the Hello Nexus service needs a worker for both the caller and handler // in order to run. // setWorkflowTypes will take the classes given and create workers for them, enabling // workflows to run. This creates caller workflows, the handler workflows // will be mocked in the test methods. .setWorkflowTypes(HelloCallerWorkflowImpl.class, EchoCallerWorkflowImpl.class) // Disable automatic worker startup as we are going to register some workflows manually // per test .setDoNotStart(true) .build(); @Test public void testHelloWorkflow() { testWorkflowRule .getWorker() // Workflows started by a Nexus service can be mocked just like any other workflow .registerWorkflowImplementationFactory( HelloHandlerWorkflow.class, () -> { HelloHandlerWorkflow wf = mock(HelloHandlerWorkflow.class); when(wf.hello(any())) .thenReturn(new SampleNexusService.HelloOutput("Hello Mock World 👋")); return wf; }); testWorkflowRule.getTestEnvironment().start(); // Now create the caller workflow HelloCallerWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub( HelloCallerWorkflow.class, WorkflowOptions.newBuilder().setTaskQueue(testWorkflowRule.getTaskQueue()).build()); String greeting = workflow.hello("World", SampleNexusService.Language.EN); assertEquals("Hello Mock World 👋", greeting); testWorkflowRule.getTestEnvironment().shutdown(); } @Test public void testEchoWorkflow() { // Sync Nexus operations run inline in the handler thread — there is no backing workflow to // register a factory for. Instead, stub the injected EchoCient dependency directly. when(mockEchoClient.echo(any())).thenReturn(new SampleNexusService.EchoOutput("mocked echo")); testWorkflowRule.getTestEnvironment().start(); EchoCallerWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub( EchoCallerWorkflow.class, WorkflowOptions.newBuilder().setTaskQueue(testWorkflowRule.getTaskQueue()).build()); String greeting = workflow.echo("Hello"); assertEquals("mocked echo", greeting); testWorkflowRule.getTestEnvironment().shutdown(); } } // @@@SNIPEND ================================================ FILE: core/src/test/java/io/temporal/samples/nexus/caller/CallerWorkflowTest.java ================================================ package io.temporal.samples.nexus.caller; import static org.junit.Assert.assertEquals; import io.temporal.client.WorkflowOptions; import io.temporal.samples.nexus.handler.HelloHandlerWorkflowImpl; import io.temporal.samples.nexus.handler.SampleNexusServiceImpl; import io.temporal.samples.nexus.service.SampleNexusService; import io.temporal.testing.TestWorkflowRule; import io.temporal.worker.WorkflowImplementationOptions; import io.temporal.workflow.NexusServiceOptions; import java.util.Collections; import org.junit.Rule; import org.junit.Test; // This is an example of how to unit test Nexus services in JUnit4. The handlers are not mocked, // but are actually called by the testing framework by the caller classes. public class CallerWorkflowTest { @Rule public TestWorkflowRule testWorkflowRule = TestWorkflowRule.newBuilder() // If a Nexus service is registered as part of the test as in the following line of code, // the TestWorkflowRule will, by default, automatically create a Nexus service endpoint // and workflows registered as part of the TestWorkflowRule // will automatically inherit the endpoint if none is set. .setNexusServiceImplementation(new SampleNexusServiceImpl()) // The Echo Nexus handler service just makes a call to a class, so no extra setup is // needed. But the Hello Nexus service needs a worker for both the caller and handler // in order to run. // setWorkflowTypes will take the classes given and create workers for them, enabling // workflows to run. This is not adding an EchoCallerWorkflow though - // see the testEchoWorkflow test method below for an example of an alternate way // to supply a worker that gives you more flexibility if needed. .setWorkflowTypes(HelloCallerWorkflowImpl.class, HelloHandlerWorkflowImpl.class) // Disable automatic worker startup as we are going to register some workflows manually // per test .setDoNotStart(true) .build(); @Test public void testHelloWorkflow() { testWorkflowRule.getTestEnvironment().start(); HelloCallerWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub( HelloCallerWorkflow.class, WorkflowOptions.newBuilder().setTaskQueue(testWorkflowRule.getTaskQueue()).build()); String greeting = workflow.hello("World", SampleNexusService.Language.EN); assertEquals("Hello World 👋", greeting); testWorkflowRule.getTestEnvironment().shutdown(); } @Test public void testEchoWorkflow() { // If Workflows are registered later than the endpoint can be set manually // either by setting the endpoint in the NexusServiceOptions in the Workflow implementation or // by setting the NexusServiceOptions on the WorkflowImplementationOptions when registering // the Workflow. To demonstrate, this is creating the Nexus service for Echo, // and registering a EchoCallerWorkflowImpl worker. // // It is much simpler to use the setWorkflowTypes in the rule definition above - and as // this isn't easily do-able in JUnit5 (the nexus endpoint isn't exposed) should be // used with caution. testWorkflowRule .getWorker() .registerWorkflowImplementationTypes( WorkflowImplementationOptions.newBuilder() .setNexusServiceOptions( Collections.singletonMap( "SampleNexusService", NexusServiceOptions.newBuilder() .setEndpoint(testWorkflowRule.getNexusEndpoint().getSpec().getName()) .build())) .build(), EchoCallerWorkflowImpl.class); testWorkflowRule.getTestEnvironment().start(); EchoCallerWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub( EchoCallerWorkflow.class, WorkflowOptions.newBuilder().setTaskQueue(testWorkflowRule.getTaskQueue()).build()); String greeting = workflow.echo("Hello"); assertEquals("Hello", greeting); testWorkflowRule.getTestEnvironment().shutdown(); } } ================================================ FILE: core/src/test/java/io/temporal/samples/nexus/caller/NexusServiceJunit5Test.java ================================================ package io.temporal.samples.nexus.caller; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import io.nexusrpc.handler.OperationHandler; import io.nexusrpc.handler.OperationImpl; import io.nexusrpc.handler.ServiceImpl; import io.temporal.samples.nexus.service.SampleNexusService; import io.temporal.testing.TestWorkflowEnvironment; import io.temporal.testing.TestWorkflowExtension; import io.temporal.worker.Worker; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; // This unit test example shows how to mock the Nexus service itself in JUnit4. // This is the path to take when you don't have access to the service implementation so // cannot mock it. Since the SampleNexusService itself is mocked, // no handlers need to be set up or mocked. // @@@SNIPSTART java-nexus-service-sample-junit5-mock public class NexusServiceJunit5Test { private final SampleNexusService mockNexusService = mock(SampleNexusService.class); /** * A test-only Nexus service implementation that delegates to the Mockito mock defined above. Both * operations are implemented as synchronous handlers that forward calls to the mock, allowing * full control over return values and verification of inputs. */ @ServiceImpl(service = SampleNexusService.class) public class TestNexusServiceImpl { @OperationImpl @SuppressWarnings("DirectInvocationOnMock") public OperationHandler echo() { return OperationHandler.sync((ctx, details, input) -> mockNexusService.echo(input)); } @OperationImpl @SuppressWarnings("DirectInvocationOnMock") public OperationHandler hello() { return OperationHandler.sync((ctx, details, input) -> mockNexusService.hello(input)); } } // Using OperationHandler.sync for both operations bypasses the need for a backing workflow, // returning results inline just like a synchronous call. // // Note that the Mocks need to be done before the extension // is defined, as creating the rule will fail if either call is still null. @RegisterExtension public final TestWorkflowExtension testWorkflowExtension = TestWorkflowExtension.newBuilder() // If a Nexus service is registered as part of the test as in the following line of code, // the TestWorkflowExtension will, by default, automatically create a Nexus service // endpoint and workflows registered as part of the TestWorkflowExtension will // automatically inherit the endpoint if none is set. .setNexusServiceImplementation(new TestNexusServiceImpl()) // The Echo Nexus handler service just makes a call to a class, so no extra setup is // needed. But the Hello Nexus service needs a worker for both the caller and handler // in order to run, and the Echo Nexus caller service needs a worker. // // registerWorkflowImplementationTypes will take the classes given and create workers for // them, enabling workflows to run. // Since both operations are mocked with OperationHandler.sync, no backing workflow is // needed for hello — only the caller workflow types need to be registered. .registerWorkflowImplementationTypes( HelloCallerWorkflowImpl.class, EchoCallerWorkflowImpl.class) // The workflow will start before each test, and will shut down after each test. // See CallerWorkflowTest for an example of how to control this differently if needed. .build(); // The TestWorkflowExtension extension in the Temporal testing library creates the // arguments to the test cases and initializes them from the extension setup call above. @Test public void testHelloWorkflow( TestWorkflowEnvironment testEnv, Worker worker, HelloCallerWorkflow workflow) { // Set the mock value to return when(mockNexusService.hello(any())) .thenReturn(new SampleNexusService.HelloOutput("Hello Mock World 👋")); // Execute a workflow waiting for it to complete. String greeting = workflow.hello("World", SampleNexusService.Language.EN); assertEquals("Hello Mock World 👋", greeting); } @Test public void testEchoWorkflow( TestWorkflowEnvironment testEnv, Worker worker, EchoCallerWorkflow workflow) { when(mockNexusService.echo(any())) .thenReturn(new SampleNexusService.EchoOutput("echo response")); // Execute a workflow waiting for it to complete. String greeting = workflow.echo("echo input"); assertEquals("echo response", greeting); // Verify the echo operation was called exactly once and no other operations were invoked verify(mockNexusService, times(1)).echo(any()); // Verify the Nexus service was called with the correct input verify(mockNexusService).echo(argThat(input -> "echo input".equals(input.getMessage()))); verifyNoMoreInteractions(mockNexusService); } } // @@@SNIPEND ================================================ FILE: core/src/test/java/io/temporal/samples/nexus/caller/NexusServiceMockTest.java ================================================ package io.temporal.samples.nexus.caller; import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import io.nexusrpc.handler.OperationHandler; import io.nexusrpc.handler.OperationImpl; import io.nexusrpc.handler.ServiceImpl; import io.temporal.client.WorkflowOptions; import io.temporal.samples.nexus.service.SampleNexusService; import io.temporal.testing.TestWorkflowRule; import org.junit.Rule; import org.junit.Test; // This unit test example shows how to mock the Nexus service itself in JUnit4. // This is the path to take when you don't have access to the service implementation so // cannot mock it. Since the SampleNexusService itself is mocked, // no handlers need to be set up or mocked. // @@@SNIPSTART java-nexus-service-sample-junit4-mock public class NexusServiceMockTest { private final SampleNexusService mockNexusService = mock(SampleNexusService.class); /** * A test-only Nexus service implementation that delegates to the Mockito mock defined above. Both * operations are implemented as synchronous handlers that forward calls to the mock, allowing * full control over return values and verification of inputs. */ @ServiceImpl(service = SampleNexusService.class) public class TestNexusServiceImpl { @OperationImpl @SuppressWarnings("DirectInvocationOnMock") public OperationHandler echo() { return OperationHandler.sync((ctx, details, input) -> mockNexusService.echo(input)); } @OperationImpl @SuppressWarnings("DirectInvocationOnMock") public OperationHandler hello() { return OperationHandler.sync((ctx, details, input) -> mockNexusService.hello(input)); } } // Using OperationHandler.sync for both operations bypasses the need for a backing workflow, // returning results inline just like a synchronous call. // // Note that the Mocks need to be done before the rule // is defined, as creating the rule will fail if either call is still null. @Rule public TestWorkflowRule testWorkflowRule = TestWorkflowRule.newBuilder() .setNexusServiceImplementation(new TestNexusServiceImpl()) .setWorkflowTypes(EchoCallerWorkflowImpl.class, HelloCallerWorkflowImpl.class) .build(); @Test public void testHelloCallerWithMockedService() { when(mockNexusService.hello(any())) .thenReturn(new SampleNexusService.HelloOutput("Bonjour World")); HelloCallerWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub( HelloCallerWorkflow.class, WorkflowOptions.newBuilder().setTaskQueue(testWorkflowRule.getTaskQueue()).build()); String result = workflow.hello("World", SampleNexusService.Language.FR); assertEquals("Bonjour World", result); // Verify the Nexus service was called with the correct name and language verify(mockNexusService) .hello( argThat( input -> "World".equals(input.getName()) && SampleNexusService.Language.FR == input.getLanguage())); } @Test public void testEchoCallerWithMockedService() { when(mockNexusService.echo(any())) .thenReturn(new SampleNexusService.EchoOutput("echo response")); EchoCallerWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub( EchoCallerWorkflow.class, WorkflowOptions.newBuilder().setTaskQueue(testWorkflowRule.getTaskQueue()).build()); String echoOutput = workflow.echo("echo input"); assertEquals("echo response", echoOutput); // Verify the echo operation was called exactly once and no other operations were invoked verify(mockNexusService, times(1)).echo(any()); // Verify the Nexus service was called with the correct input verify(mockNexusService).echo(argThat(input -> "echo input".equals(input.getMessage()))); verifyNoMoreInteractions(mockNexusService); } } // @@@SNIPEND ================================================ FILE: core/src/test/java/io/temporal/samples/payloadconverter/CloudEventsPayloadConverterTest.java ================================================ package io.temporal.samples.payloadconverter; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import io.cloudevents.CloudEvent; import io.cloudevents.core.builder.CloudEventBuilder; import io.cloudevents.jackson.JsonCloudEventData; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowClientOptions; import io.temporal.client.WorkflowOptions; import io.temporal.common.converter.DefaultDataConverter; import io.temporal.samples.payloadconverter.cloudevents.CEWorkflow; import io.temporal.samples.payloadconverter.cloudevents.CEWorkflowImpl; import io.temporal.samples.payloadconverter.cloudevents.CloudEventsPayloadConverter; import io.temporal.testing.TestWorkflowRule; import java.net.URI; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import org.junit.Rule; import org.junit.Test; public class CloudEventsPayloadConverterTest { private DefaultDataConverter ddc = DefaultDataConverter.newDefaultInstance() .withPayloadConverterOverrides(new CloudEventsPayloadConverter()); private WorkflowClientOptions workflowClientOptions = WorkflowClientOptions.newBuilder().setDataConverter(ddc).build(); @Rule public TestWorkflowRule testWorkflowRule = TestWorkflowRule.newBuilder() .setWorkflowClientOptions(workflowClientOptions) .setWorkflowTypes(CEWorkflowImpl.class) .build(); @Test public void testActivityImpl() { List cloudEventList = new ArrayList<>(); for (int i = 0; i < 10; i++) { cloudEventList.add( CloudEventBuilder.v1() .withId(String.valueOf(100 + i)) .withType("example.demo") .withSource(URI.create("http://temporal.io")) .withData( "application/json", ("{\n" + "\"greeting\": \"hello " + i + "\"\n" + "}") .getBytes(Charset.defaultCharset())) .build()); } WorkflowOptions workflowOptions = WorkflowOptions.newBuilder().setTaskQueue(testWorkflowRule.getTaskQueue()).build(); CEWorkflow workflow = testWorkflowRule.getWorkflowClient().newWorkflowStub(CEWorkflow.class, workflowOptions); // start async WorkflowClient.start(workflow::exec, cloudEventList.get(0)); for (int j = 1; j < 10; j++) { workflow.addEvent(cloudEventList.get(j)); } // Get the CE result and get its data (JSON) String result = ((JsonCloudEventData) workflow.getLastEvent().getData()).getNode().get("greeting").asText(); assertNotNull(result); assertEquals("hello 9", result); } } ================================================ FILE: core/src/test/java/io/temporal/samples/payloadconverter/CryptoPayloadConverterTest.java ================================================ package io.temporal.samples.payloadconverter; import static org.junit.Assert.*; import com.codingrodent.jackson.crypto.CryptoModule; import com.codingrodent.jackson.crypto.EncryptionService; import com.codingrodent.jackson.crypto.PasswordCryptoContext; import com.fasterxml.jackson.databind.ObjectMapper; import io.temporal.client.WorkflowClientOptions; import io.temporal.client.WorkflowOptions; import io.temporal.common.converter.DefaultDataConverter; import io.temporal.common.converter.JacksonJsonPayloadConverter; import io.temporal.samples.payloadconverter.crypto.CryptoWorkflow; import io.temporal.samples.payloadconverter.crypto.CryptoWorkflowImpl; import io.temporal.samples.payloadconverter.crypto.MyCustomer; import io.temporal.testing.TestWorkflowRule; import org.junit.Rule; import org.junit.Test; public class CryptoPayloadConverterTest { private static final String encryptDecryptPassword = "encryptDecryptPassword"; @Rule public TestWorkflowRule testWorkflowRule = TestWorkflowRule.newBuilder() .setWorkflowClientOptions( WorkflowClientOptions.newBuilder() .setDataConverter( DefaultDataConverter.newDefaultInstance() .withPayloadConverterOverrides(getCryptoJacksonJsonPayloadConverter())) .build()) .setWorkflowTypes(CryptoWorkflowImpl.class) .build(); @Test public void testEncryptedWorkflowData() { WorkflowOptions workflowOptions = WorkflowOptions.newBuilder().setTaskQueue(testWorkflowRule.getTaskQueue()).build(); CryptoWorkflow workflow = testWorkflowRule.getWorkflowClient().newWorkflowStub(CryptoWorkflow.class, workflowOptions); MyCustomer customer = workflow.exec(new MyCustomer("John", 22)); assertNotNull(customer); assertTrue(customer.isApproved()); } private JacksonJsonPayloadConverter getCryptoJacksonJsonPayloadConverter() { ObjectMapper objectMapper = new ObjectMapper(); // Create the Crypto Context (password based) PasswordCryptoContext cryptoContext = new PasswordCryptoContext( encryptDecryptPassword, // decrypt password encryptDecryptPassword, // encrypt password PasswordCryptoContext.CIPHER_NAME, // cipher name PasswordCryptoContext.KEY_NAME); // key generator names EncryptionService encryptionService = new EncryptionService(objectMapper, cryptoContext); objectMapper.registerModule(new CryptoModule().addEncryptionService(encryptionService)); return new JacksonJsonPayloadConverter(objectMapper); } } ================================================ FILE: core/src/test/java/io/temporal/samples/peractivityoptions/PerActivityOptionsTest.java ================================================ package io.temporal.samples.peractivityoptions; import static org.junit.Assert.*; import com.google.common.collect.ImmutableMap; import io.temporal.activity.ActivityOptions; import io.temporal.api.common.v1.WorkflowExecution; import io.temporal.api.enums.v1.WorkflowExecutionStatus; import io.temporal.api.workflowservice.v1.DescribeWorkflowExecutionRequest; import io.temporal.api.workflowservice.v1.DescribeWorkflowExecutionResponse; import io.temporal.client.WorkflowOptions; import io.temporal.client.WorkflowStub; import io.temporal.common.RetryOptions; import io.temporal.testing.TestWorkflowRule; import io.temporal.worker.WorkflowImplementationOptions; import java.time.Duration; import org.junit.Rule; import org.junit.Test; public class PerActivityOptionsTest { WorkflowImplementationOptions options = WorkflowImplementationOptions.newBuilder() .setActivityOptions( ImmutableMap.of( "ActivityTypeA", ActivityOptions.newBuilder() .setScheduleToCloseTimeout(Duration.ofSeconds(5)) .build(), "ActivityTypeB", ActivityOptions.newBuilder() .setStartToCloseTimeout(Duration.ofSeconds(2)) .setRetryOptions( RetryOptions.newBuilder() .setDoNotRetry(NullPointerException.class.getName()) .build()) .build())) .build(); @Rule public TestWorkflowRule testWorkflowRule = TestWorkflowRule.newBuilder() .setWorkflowTypes(options, PerActivityOptionsWorkflowImpl.class) .setActivityImplementations(new FailingActivitiesImpl()) .build(); @Test public void testPerActivityTypeWorkflow() { PerActivityOptionsWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub( PerActivityOptionsWorkflow.class, WorkflowOptions.newBuilder().setTaskQueue(testWorkflowRule.getTaskQueue()).build()); WorkflowStub untyped = WorkflowStub.fromTyped(workflow); WorkflowExecution execution = untyped.start(); // wait until workflow completes untyped.getResult(Void.class); DescribeWorkflowExecutionResponse resp = testWorkflowRule .getWorkflowClient() .getWorkflowServiceStubs() .blockingStub() .describeWorkflowExecution( DescribeWorkflowExecutionRequest.newBuilder() .setNamespace(testWorkflowRule.getTestEnvironment().getNamespace()) .setExecution(execution) .build()); assertEquals( WorkflowExecutionStatus.WORKFLOW_EXECUTION_STATUS_COMPLETED, resp.getWorkflowExecutionInfo().getStatus()); } } ================================================ FILE: core/src/test/java/io/temporal/samples/polling/FrequentPollingTest.java ================================================ package io.temporal.samples.polling; import static org.junit.Assert.assertEquals; import io.temporal.client.WorkflowOptions; import io.temporal.samples.polling.frequent.FrequentPollingActivityImpl; import io.temporal.samples.polling.frequent.FrequentPollingWorkflowImpl; import io.temporal.testing.TestWorkflowRule; import org.junit.Rule; import org.junit.Test; public class FrequentPollingTest { @Rule public TestWorkflowRule testWorkflowRule = TestWorkflowRule.newBuilder() .setWorkflowTypes(FrequentPollingWorkflowImpl.class) .setActivityImplementations(new FrequentPollingActivityImpl(new TestService())) .build(); @Test public void testInfrequentPoll() { PollingWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub( PollingWorkflow.class, WorkflowOptions.newBuilder().setTaskQueue(testWorkflowRule.getTaskQueue()).build()); assertEquals("OK", workflow.exec()); } } ================================================ FILE: core/src/test/java/io/temporal/samples/polling/InfrequentPollingTest.java ================================================ package io.temporal.samples.polling; import static org.junit.Assert.*; import io.temporal.client.WorkflowOptions; import io.temporal.samples.polling.infrequent.InfrequentPollingActivityImpl; import io.temporal.samples.polling.infrequent.InfrequentPollingWorkflowImpl; import io.temporal.testing.TestWorkflowRule; import org.junit.Rule; import org.junit.Test; public class InfrequentPollingTest { @Rule public TestWorkflowRule testWorkflowRule = TestWorkflowRule.newBuilder() .setWorkflowTypes(InfrequentPollingWorkflowImpl.class) .setActivityImplementations(new InfrequentPollingActivityImpl(new TestService())) .build(); @Test public void testInfrequentPoll() { PollingWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub( PollingWorkflow.class, WorkflowOptions.newBuilder().setTaskQueue(testWorkflowRule.getTaskQueue()).build()); assertEquals("OK", workflow.exec()); } } ================================================ FILE: core/src/test/java/io/temporal/samples/polling/PeriodicPollingTest.java ================================================ package io.temporal.samples.polling; import static org.junit.Assert.assertEquals; import io.temporal.client.WorkflowOptions; import io.temporal.samples.polling.periodicsequence.PeriodicPollingActivityImpl; import io.temporal.samples.polling.periodicsequence.PeriodicPollingChildWorkflowImpl; import io.temporal.samples.polling.periodicsequence.PeriodicPollingWorkflowImpl; import io.temporal.testing.TestWorkflowRule; import org.junit.Rule; import org.junit.Test; public class PeriodicPollingTest { @Rule public TestWorkflowRule testWorkflowRule = TestWorkflowRule.newBuilder() .setWorkflowTypes( PeriodicPollingWorkflowImpl.class, PeriodicPollingChildWorkflowImpl.class) .setActivityImplementations(new PeriodicPollingActivityImpl(new TestService())) .build(); @Test public void testInfrequentPoll() { PollingWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub( PollingWorkflow.class, WorkflowOptions.newBuilder().setTaskQueue(testWorkflowRule.getTaskQueue()).build()); assertEquals("OK", workflow.exec()); } } ================================================ FILE: core/src/test/java/io/temporal/samples/retryonsignalinterceptor/RetryOnSignalInterceptorTest.java ================================================ package io.temporal.samples.retryonsignalinterceptor; import static org.junit.Assert.*; import io.temporal.api.common.v1.WorkflowExecution; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowStub; import io.temporal.failure.ActivityFailure; import io.temporal.failure.ApplicationFailure; import io.temporal.testing.TestWorkflowEnvironment; import io.temporal.testing.TestWorkflowRule; import io.temporal.worker.WorkerFactoryOptions; import java.time.Duration; import java.util.concurrent.atomic.AtomicInteger; import org.junit.Rule; import org.junit.Test; public class RetryOnSignalInterceptorTest { static class TestActivityImpl implements MyActivity { final AtomicInteger count = new AtomicInteger(); @Override public void execute() { if (count.incrementAndGet() < 5) { throw ApplicationFailure.newFailure("simulated", "type1"); } } } private final TestActivityImpl testActivity = new TestActivityImpl(); @Rule public TestWorkflowRule testWorkflowRule = TestWorkflowRule.newBuilder() .setWorkerFactoryOptions( WorkerFactoryOptions.newBuilder() .setWorkerInterceptors(new RetryOnSignalWorkerInterceptor()) .validateAndBuildWithDefaults()) .setWorkflowTypes(MyWorkflowImpl.class) .setActivityImplementations(testActivity) .build(); @Test public void testRetryThenFail() { testActivity.count.set(0); TestWorkflowEnvironment testEnvironment = testWorkflowRule.getTestEnvironment(); MyWorkflow workflow = testWorkflowRule.newWorkflowStub(MyWorkflow.class); WorkflowExecution execution = WorkflowClient.start(workflow::execute); // Get stub to the dynamically registered interface RetryOnSignalInterceptorListener listener = testWorkflowRule .getWorkflowClient() .newWorkflowStub(RetryOnSignalInterceptorListener.class, execution.getWorkflowId()); testEnvironment.sleep(Duration.ofMinutes(10)); listener.retry(); testEnvironment.sleep(Duration.ofMinutes(10)); listener.retry(); testEnvironment.sleep(Duration.ofMinutes(10)); listener.retry(); testEnvironment.sleep(Duration.ofMinutes(10)); listener.fail(); WorkflowStub untyped = testWorkflowRule.getWorkflowClient().newUntypedWorkflowStub(execution.getWorkflowId()); try { untyped.getResult(Void.class); fail("unreachable"); } catch (Exception e) { assertTrue(e.getCause() instanceof ActivityFailure); assertTrue(e.getCause().getCause() instanceof ApplicationFailure); assertEquals( "message='simulated', type='type1', nonRetryable=false", e.getCause().getCause().getMessage()); } assertEquals(4, testActivity.count.get()); } @Test public void testRetryUntilSucceeds() { testActivity.count.set(0); TestWorkflowEnvironment testEnvironment = testWorkflowRule.getTestEnvironment(); MyWorkflow workflow = testWorkflowRule.newWorkflowStub(MyWorkflow.class); WorkflowExecution execution = WorkflowClient.start(workflow::execute); // Get stub to the dynamically registered interface RetryOnSignalInterceptorListener listener = testWorkflowRule .getWorkflowClient() .newWorkflowStub(RetryOnSignalInterceptorListener.class, execution.getWorkflowId()); for (int i = 0; i < 4; i++) { testEnvironment.sleep(Duration.ofMinutes(10)); listener.retry(); } WorkflowStub untyped = testWorkflowRule.getWorkflowClient().newUntypedWorkflowStub(execution.getWorkflowId()); untyped.getResult(Void.class); assertEquals(5, testActivity.count.get()); } } ================================================ FILE: core/src/test/java/io/temporal/samples/safemessagepassing/ClusterManagerWorkflowWorkerTest.java ================================================ package io.temporal.samples.safemessagepassing; import io.temporal.client.*; import io.temporal.failure.ApplicationFailure; import io.temporal.testing.TestWorkflowRule; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; public class ClusterManagerWorkflowWorkerTest { @Rule public TestWorkflowRule testWorkflowRule = TestWorkflowRule.newBuilder() .setWorkflowTypes(ClusterManagerWorkflowImpl.class) .setActivityImplementations(new ClusterManagerActivitiesImpl()) .build(); @Test public void testSafeMessageHandler() throws ExecutionException, InterruptedException { ClusterManagerWorkflow cluster = testWorkflowRule .getWorkflowClient() .newWorkflowStub( ClusterManagerWorkflow.class, WorkflowOptions.newBuilder().setTaskQueue(testWorkflowRule.getTaskQueue()).build()); CompletableFuture result = WorkflowClient.execute( cluster::run, new ClusterManagerWorkflow.ClusterManagerInput(Optional.empty(), false)); cluster.startCluster(); List> assignJobs = new ArrayList<>(); for (int i = 0; i < 6; i++) { assignJobs.add( WorkflowStub.fromTyped(cluster) .startUpdate( "assignNodesToJobs", WorkflowUpdateStage.ACCEPTED, ClusterManagerWorkflow.ClusterManagerAssignNodesToJobResult.class, new ClusterManagerWorkflow.ClusterManagerAssignNodesToJobInput(2, "job-" + i)) .getResultAsync()); } assignJobs.forEach( (f) -> { try { Assert.assertEquals(2, f.get().getNodesAssigned().size()); } catch (InterruptedException e) { throw new RuntimeException(e); } catch (ExecutionException e) { throw new RuntimeException(e); } }); testWorkflowRule.getTestEnvironment().sleep(Duration.ofSeconds(1)); List> deleteJobs = new ArrayList<>(); for (int i = 0; i < 6; i++) { deleteJobs.add( WorkflowStub.fromTyped(cluster) .startUpdate( "deleteJob", WorkflowUpdateStage.ACCEPTED, Void.class, new ClusterManagerWorkflow.ClusterManagerDeleteJobInput("job-" + i)) .getResultAsync()); } deleteJobs.forEach(CompletableFuture::join); cluster.stopCluster(); Assert.assertEquals(0, result.get().getNumCurrentlyAssignedNodes()); } @Test public void testUpdateIdempotency() { ClusterManagerWorkflow cluster = testWorkflowRule .getWorkflowClient() .newWorkflowStub( ClusterManagerWorkflow.class, WorkflowOptions.newBuilder().setTaskQueue(testWorkflowRule.getTaskQueue()).build()); WorkflowClient.execute( cluster::run, new ClusterManagerWorkflow.ClusterManagerInput(Optional.empty(), false)); cluster.startCluster(); ClusterManagerWorkflow.ClusterManagerAssignNodesToJobResult result1 = cluster.assignNodesToJobs( new ClusterManagerWorkflow.ClusterManagerAssignNodesToJobInput(5, "test-job")); ClusterManagerWorkflow.ClusterManagerAssignNodesToJobResult result2 = cluster.assignNodesToJobs( new ClusterManagerWorkflow.ClusterManagerAssignNodesToJobInput(5, "test-job")); Assert.assertTrue(result1.getNodesAssigned().size() >= result2.getNodesAssigned().size()); } @Test public void testUpdateFailure() throws ExecutionException, InterruptedException { ClusterManagerWorkflow cluster = testWorkflowRule .getWorkflowClient() .newWorkflowStub( ClusterManagerWorkflow.class, WorkflowOptions.newBuilder().setTaskQueue(testWorkflowRule.getTaskQueue()).build()); CompletableFuture result = WorkflowClient.execute( cluster::run, new ClusterManagerWorkflow.ClusterManagerInput(Optional.empty(), false)); cluster.startCluster(); cluster.assignNodesToJobs( new ClusterManagerWorkflow.ClusterManagerAssignNodesToJobInput(24, "big-job")); WorkflowUpdateException updateFailure = Assert.assertThrows( WorkflowUpdateException.class, () -> cluster.assignNodesToJobs( new ClusterManagerWorkflow.ClusterManagerAssignNodesToJobInput( 3, "little-job"))); Assert.assertTrue(updateFailure.getCause() instanceof ApplicationFailure); Assert.assertEquals( "Cannot assign nodes to a job: Not enough nodes available", ((ApplicationFailure) updateFailure.getCause()).getOriginalMessage()); cluster.stopCluster(); Assert.assertEquals( 24, result.get().getNumCurrentlyAssignedNodes() + result.get().getNumBadNodes()); } } ================================================ FILE: core/src/test/java/io/temporal/samples/sleepfordays/SleepForDaysJUnit5Test.java ================================================ package io.temporal.samples.sleepfordays; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.*; import io.temporal.client.WorkflowClient; import io.temporal.testing.TestWorkflowEnvironment; import io.temporal.testing.TestWorkflowExtension; import io.temporal.worker.Worker; import java.time.Duration; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import org.junit.jupiter.api.extension.RegisterExtension; public class SleepForDaysJUnit5Test { @RegisterExtension public TestWorkflowExtension testWorkflowRule = TestWorkflowExtension.newBuilder() .registerWorkflowImplementationTypes(SleepForDaysImpl.class) .setDoNotStart(true) .build(); @Test @Timeout(8) public void testSleepForDays( TestWorkflowEnvironment testEnv, Worker worker, SleepForDaysWorkflow workflow) { // Mock activity SendEmailActivity activities = mock(SendEmailActivity.class); worker.registerActivitiesImplementations(activities); // Start environment testEnv.start(); // Start workflow WorkflowClient.start(workflow::sleepForDays); long startTime = testEnv.currentTimeMillis(); // Time-skip 5 minutes. testEnv.sleep(Duration.ofMinutes(5)); // Check that the activity has been called, we're now waiting for the sleep to finish. verify(activities, times(1)).sendEmail(anyString()); // Time-skip 3 days. testEnv.sleep(Duration.ofDays(90)); // Expect 3 more activity calls. verify(activities, times(4)).sendEmail(anyString()); // Send the signal to complete the workflow. workflow.complete(); // Expect no more activity calls to have been made - workflow is complete. workflow.sleepForDays(); verify(activities, times(4)).sendEmail(anyString()); // Expect more than 90 days to have passed. long endTime = testEnv.currentTimeMillis(); assertEquals(true, endTime - startTime > Duration.ofDays(90).toMillis()); } } ================================================ FILE: core/src/test/java/io/temporal/samples/sleepfordays/SleepForDaysTest.java ================================================ package io.temporal.samples.sleepfordays; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.testing.TestWorkflowRule; import java.time.Duration; import org.junit.Rule; import org.junit.Test; public class SleepForDaysTest { @Rule public TestWorkflowRule testWorkflowRule = TestWorkflowRule.newBuilder() .setWorkflowTypes(SleepForDaysImpl.class) .setDoNotStart(true) .build(); @Test(timeout = 8000) public void testSleepForDays() { // Mock activity SendEmailActivity activities = mock(SendEmailActivity.class); testWorkflowRule.getWorker().registerActivitiesImplementations(activities); // Start environment testWorkflowRule.getTestEnvironment().start(); // Create a workflow WorkflowOptions workflowOptions = WorkflowOptions.newBuilder().setTaskQueue(testWorkflowRule.getTaskQueue()).build(); SleepForDaysWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub(SleepForDaysWorkflow.class, workflowOptions); // Start workflow WorkflowClient.start(workflow::sleepForDays); long startTime = testWorkflowRule.getTestEnvironment().currentTimeMillis(); // Time-skip 5 minutes. testWorkflowRule.getTestEnvironment().sleep(Duration.ofMinutes(5)); // Check that the activity has been called, we're now waiting for the sleep to finish. verify(activities, times(1)).sendEmail(anyString()); // Time-skip 3 days. testWorkflowRule.getTestEnvironment().sleep(Duration.ofDays(90)); // Expect 3 more activity calls. verify(activities, times(4)).sendEmail(anyString()); // Send the signal to complete the workflow. workflow.complete(); // Expect no more activity calls to have been made - workflow is complete. verify(activities, times(4)).sendEmail(anyString()); // Expect more than 90 days to have passed. long endTime = testWorkflowRule.getTestEnvironment().currentTimeMillis(); assertEquals(true, endTime - startTime > Duration.ofDays(90).toMillis()); } } ================================================ FILE: core/src/test/java/io/temporal/samples/standaloneactivities/StandaloneActivitiesTest.java ================================================ package io.temporal.samples.standaloneactivities; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.Mockito.withSettings; import io.temporal.activity.ActivityOptions; import io.temporal.client.WorkflowOptions; import io.temporal.testing.TestWorkflowRule; import io.temporal.workflow.Workflow; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; import java.time.Duration; import org.junit.Rule; import org.junit.Test; /** * Unit tests for the standaloneactivities sample. Uses an embedded Temporal test server so no * external service is required. * *

Standalone Activities do not use a Workflow at runtime, but the embedded test server only * supports Activity execution through a Workflow. These tests therefore drive the Activity through * a minimal wrapper Workflow so the Activity logic is exercised against the real SDK worker stack. */ public class StandaloneActivitiesTest { @WorkflowInterface public interface TestWorkflow { @WorkflowMethod String run(String greeting, String name); } public static class TestWorkflowImpl implements TestWorkflow { private final GreetingActivities activities = Workflow.newActivityStub( GreetingActivities.class, ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(5)).build()); @Override public String run(String greeting, String name) { return activities.composeGreeting(greeting, name); } } @Rule public TestWorkflowRule testWorkflowRule = TestWorkflowRule.newBuilder() .setWorkflowTypes(TestWorkflowImpl.class) .setDoNotStart(true) .build(); @Test public void testActivityImpl() { testWorkflowRule.getWorker().registerActivitiesImplementations(new GreetingActivitiesImpl()); testWorkflowRule.getTestEnvironment().start(); TestWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub( TestWorkflow.class, WorkflowOptions.newBuilder().setTaskQueue(testWorkflowRule.getTaskQueue()).build()); assertEquals("Hello, World!", workflow.run("Hello", "World")); testWorkflowRule.getTestEnvironment().shutdown(); } @Test public void testMockedActivity() { // withoutAnnotations() prevents Mockito from copying @ActivityMethod from the interface onto // the mock, which would cause worker registration to fail. GreetingActivities activities = mock(GreetingActivities.class, withSettings().withoutAnnotations()); when(activities.composeGreeting("Hello", "World")).thenReturn("Hello, World!"); testWorkflowRule.getWorker().registerActivitiesImplementations(activities); testWorkflowRule.getTestEnvironment().start(); TestWorkflow workflow = testWorkflowRule .getWorkflowClient() .newWorkflowStub( TestWorkflow.class, WorkflowOptions.newBuilder().setTaskQueue(testWorkflowRule.getTaskQueue()).build()); assertEquals("Hello, World!", workflow.run("Hello", "World")); verify(activities).composeGreeting("Hello", "World"); testWorkflowRule.getTestEnvironment().shutdown(); } } ================================================ FILE: core/src/test/java/io/temporal/samples/terminateworkflow/TerminateWorkflowTest.java ================================================ package io.temporal.samples.terminateworkflow; import static org.junit.Assert.*; import static org.junit.Assert.assertEquals; import io.temporal.client.WorkflowFailedException; import io.temporal.client.WorkflowOptions; import io.temporal.client.WorkflowStub; import io.temporal.failure.TerminatedFailure; import io.temporal.testing.TestWorkflowRule; import org.junit.Rule; import org.junit.Test; public class TerminateWorkflowTest { @Rule public TestWorkflowRule testWorkflowRule = TestWorkflowRule.newBuilder().setWorkflowTypes(MyWorkflowImpl.class).build(); @Test public void testTerminateWorkflow() { WorkflowStub wfs = testWorkflowRule .getWorkflowClient() .newUntypedWorkflowStub( "MyWorkflow", WorkflowOptions.newBuilder().setTaskQueue(testWorkflowRule.getTaskQueue()).build()); wfs.start(testWorkflowRule.getTaskQueue()); try { Thread.sleep(1000); } catch (Exception e) { fail(e.getMessage()); } wfs.terminate("Test Reasons"); try { wfs.getResult(String.class); fail("unreachable"); } catch (WorkflowFailedException ignored) { assertTrue(ignored.getCause() instanceof TerminatedFailure); assertEquals("Test Reasons", ((TerminatedFailure) ignored.getCause()).getOriginalMessage()); } } } ================================================ FILE: core/src/test/java/io/temporal/samples/tracing/TracingTest.java ================================================ package io.temporal.samples.tracing; import static org.junit.Assert.*; import io.jaegertracing.internal.JaegerSpan; import io.jaegertracing.internal.JaegerTracer; import io.jaegertracing.internal.reporters.InMemoryReporter; import io.jaegertracing.internal.samplers.ConstSampler; import io.jaegertracing.spi.Sampler; import io.opentracing.Tracer; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowClientOptions; import io.temporal.client.WorkflowOptions; import io.temporal.client.WorkflowStub; import io.temporal.opentracing.OpenTracingClientInterceptor; import io.temporal.opentracing.OpenTracingOptions; import io.temporal.opentracing.OpenTracingSpanContextCodec; import io.temporal.opentracing.OpenTracingWorkerInterceptor; import io.temporal.samples.tracing.workflow.TracingActivitiesImpl; import io.temporal.samples.tracing.workflow.TracingChildWorkflowImpl; import io.temporal.samples.tracing.workflow.TracingWorkflow; import io.temporal.samples.tracing.workflow.TracingWorkflowImpl; import io.temporal.testing.TestWorkflowRule; import io.temporal.worker.WorkerFactoryOptions; import java.util.List; import org.junit.After; import org.junit.Rule; import org.junit.Test; public class TracingTest { private final InMemoryReporter reporter = new InMemoryReporter(); private final Sampler sampler = new ConstSampler(true); private final Tracer tracer = new JaegerTracer.Builder("temporal-test").withReporter(reporter).withSampler(sampler).build(); private final OpenTracingOptions JAEGER_COMPATIBLE_CONFIG = OpenTracingOptions.newBuilder() .setSpanContextCodec(OpenTracingSpanContextCodec.TEXT_MAP_CODEC) .setTracer(tracer) .build(); @Rule public TestWorkflowRule testWorkflowRule = TestWorkflowRule.newBuilder() .setWorkflowClientOptions( WorkflowClientOptions.newBuilder() .setInterceptors(new OpenTracingClientInterceptor(JAEGER_COMPATIBLE_CONFIG)) .validateAndBuildWithDefaults()) .setWorkerFactoryOptions( WorkerFactoryOptions.newBuilder() .setWorkerInterceptors(new OpenTracingWorkerInterceptor(JAEGER_COMPATIBLE_CONFIG)) .validateAndBuildWithDefaults()) .setWorkflowTypes(TracingWorkflowImpl.class, TracingChildWorkflowImpl.class) .setActivityImplementations(new TracingActivitiesImpl()) .build(); @After public void tearDown() { reporter.close(); sampler.close(); tracer.close(); } @Test public void testReportSpans() { WorkflowClient client = testWorkflowRule.getWorkflowClient(); WorkflowOptions workflowOptions = WorkflowOptions.newBuilder().setTaskQueue(testWorkflowRule.getTaskQueue()).build(); TracingWorkflow workflow = client.newWorkflowStub(TracingWorkflow.class, workflowOptions); // Convert to untyped and start it with signalWithStart WorkflowStub untyped = WorkflowStub.fromTyped(workflow); untyped.signalWithStart("setLanguage", new Object[] {"Spanish"}, new Object[] {"John"}); String greeting = untyped.getResult(String.class); assertEquals("Hola John", greeting); List reportedSpans = reporter.getSpans(); assertNotNull(reportedSpans); assertEquals(7, reportedSpans.size()); } } ================================================ FILE: core/src/test/resources/dsl/sampleflow.json ================================================ { "id": "sampleFlow", "name": "Sample Flow One", "description": "Sample Flow Definition", "actions": [ { "action": "One", "retries": 10, "startToCloseSec": 3 }, { "action": "Two", "retries": 8, "startToCloseSec": 3 }, { "action": "Three", "retries": 10, "startToCloseSec": 4 }, { "action": "Four", "retries": 9, "startToCloseSec": 5 } ] } ================================================ FILE: docker/github/Dockerfile ================================================ FROM eclipse-temurin:17-jammy # Git is needed in order to update the dls submodule RUN apt-get update && apt-get install -y wget protobuf-compiler git RUN mkdir /temporal-java-samples WORKDIR /temporal-java-samples ================================================ FILE: docker/github/README.md ================================================ # Using Github Actions Github action simply runs Docker containers. So it is easy to perform the same build locally that Github will do. To handle this, there are two different docker-compose files: one for Github and one for local. The Dockerfile is the same for both. ## Testing the build locally To run the build locally, start from the root folder of this repo and run the following command: ```bash docker-compose -f docker/github/docker-compose.yaml run unit-test ``` Note that Github action will run basically the same commands. ## Testing the build in Github Actions Creating a PR against the main branch will trigger the Github action. ================================================ FILE: docker/github/docker-compose.yaml ================================================ version: '3.5' services: unit-test: build: context: ../../ dockerfile: ./docker/github/Dockerfile command: "./gradlew --no-daemon test" environment: - "USER=unittest" volumes: - "../../:/temporal-java-samples" ================================================ FILE: gradle/springai.gradle ================================================ // Shared configuration for all Spring AI sample modules. // Applied via: apply from: "$rootDir/gradle/springai.gradle" // // Note on Spring Boot version skew: the root build.gradle pins the // org.springframework.boot Gradle plugin at $springBootPluginVersion (currently // 2.7.13) for the legacy springboot/ samples. Spring AI 1.1.0 requires Spring // Boot 3.5.x, which we get by importing the spring-boot-dependencies BOM at // $springBootVersionForSpringAi below. The plugin and the BOM are independent — // the plugin contributes bootJar/bootRun task wiring, the BOM dictates // dependency versions — so this works in practice even though the two version // numbers don't match. Long-term fix is to either move the plugin declaration // out of the root plugins block (so each module applies its own version) or // migrate the legacy springboot/ samples to Spring Boot 3.x; until one of those // happens, this skew is intentional. apply plugin: 'org.springframework.boot' apply plugin: 'io.spring.dependency-management' ext { springBootVersionForSpringAi = '3.5.3' springAiVersion = '1.1.0' } java { sourceCompatibility = JavaVersion.VERSION_17 targetCompatibility = JavaVersion.VERSION_17 } dependencyManagement { imports { mavenBom "org.springframework.boot:spring-boot-dependencies:$springBootVersionForSpringAi" mavenBom "org.springframework.ai:spring-ai-bom:$springAiVersion" } } dependencies { implementation "io.temporal:temporal-spring-boot-starter:$javaSDKVersion" implementation "io.temporal:temporal-spring-ai:$javaSDKVersion" // temporal-spring-ai declares temporal-sdk as compileOnly, so bring it in explicitly. implementation "io.temporal:temporal-sdk:$javaSDKVersion" // Spring Boot implementation 'org.springframework.boot:spring-boot-starter' dependencies { errorproneJavac('com.google.errorprone:javac:9+181-r4173-1') errorprone('com.google.errorprone:error_prone_core:2.28.0') } } bootJar { enabled = false } jar { enabled = true } bootRun { standardInput = System.in } ================================================ FILE: gradle/wrapper/gradle-wrapper.properties ================================================ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-bin.zip networkTimeout=10000 validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists ================================================ FILE: gradle.properties ================================================ springBootPluginVersion=2.7.13 # use this for spring boot 3 support #springBootPluginVersion=3.2.0 ================================================ FILE: gradlew ================================================ #!/bin/sh # # Copyright © 2015-2021 the original authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # SPDX-License-Identifier: Apache-2.0 # ############################################################################## # # Gradle start up script for POSIX generated by Gradle. # # Important for running: # # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is # noncompliant, but you have some other compliant shell such as ksh or # bash, then to run this script, type that shell name before the whole # command line, like: # # ksh Gradle # # Busybox and similar reduced shells will NOT work, because this script # requires all of these POSIX shell features: # * functions; # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», # «${var#prefix}», «${var%suffix}», and «$( cmd )»; # * compound commands having a testable exit status, especially «case»; # * various built-in commands including «command», «set», and «ulimit». # # Important for patching: # # (2) This script targets any POSIX shell, so it avoids extensions provided # by Bash, Ksh, etc; in particular arrays are avoided. # # The "traditional" practice of packing multiple parameters into a # space-separated string is a well documented source of bugs and security # problems, so this is (mostly) avoided, by progressively accumulating # options in "$@", and eventually passing that to Java. # # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; # see the in-line comments for details. # # There are tweaks for specific operating systems such as AIX, CygWin, # Darwin, MinGW, and NonStop. # # (3) This script is generated from the Groovy template # https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt # within the Gradle project. # # You can find Gradle at https://github.com/gradle/gradle/. # ############################################################################## # Attempt to set APP_HOME # Resolve links: $0 may be a link app_path=$0 # Need this for daisy-chained symlinks. while APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path [ -h "$app_path" ] do ls=$( ls -ld "$app_path" ) link=${ls#*' -> '} case $link in #( /*) app_path=$link ;; #( *) app_path=$APP_HOME$link ;; esac done # This is normally unused # shellcheck disable=SC2034 APP_BASE_NAME=${0##*/} # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s ' "$PWD" ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD=maximum warn () { echo "$*" } >&2 die () { echo echo "$*" echo exit 1 } >&2 # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false nonstop=false case "$( uname )" in #( CYGWIN* ) cygwin=true ;; #( Darwin* ) darwin=true ;; #( MSYS* | MINGW* ) msys=true ;; #( NONSTOP* ) nonstop=true ;; esac CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables JAVACMD=$JAVA_HOME/jre/sh/java else JAVACMD=$JAVA_HOME/bin/java fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else JAVACMD=java if ! command -v java >/dev/null 2>&1 then die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi fi # Increase the maximum file descriptors if we can. if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then case $MAX_FD in #( max*) # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. # shellcheck disable=SC2039,SC3045 MAX_FD=$( ulimit -H -n ) || warn "Could not query maximum file descriptor limit" esac case $MAX_FD in #( '' | soft) :;; #( *) # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. # shellcheck disable=SC2039,SC3045 ulimit -n "$MAX_FD" || warn "Could not set maximum file descriptor limit to $MAX_FD" esac fi # Collect all arguments for the java command, stacking in reverse order: # * args from the command line # * the main class name # * -classpath # * -D...appname settings # * --module-path (only if needed) # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. # For Cygwin or MSYS, switch paths to Windows format before running java if "$cygwin" || "$msys" ; then APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) JAVACMD=$( cygpath --unix "$JAVACMD" ) # Now convert the arguments - kludge to limit ourselves to /bin/sh for arg do if case $arg in #( -*) false ;; # don't mess with options #( /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath [ -e "$t" ] ;; #( *) false ;; esac then arg=$( cygpath --path --ignore --mixed "$arg" ) fi # Roll the args list around exactly as many times as the number of # args, so each arg winds up back in the position where it started, but # possibly modified. # # NB: a `for` loop captures its iteration list before it begins, so # changing the positional parameters here affects neither the number of # iterations, nor the values presented in `arg`. shift # remove old arg set -- "$@" "$arg" # push replacement arg done fi # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' # Collect all arguments for the java command: # * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, # and any embedded shellness will be escaped. # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be # treated as '${Hostname}' itself on the command line. set -- \ "-Dorg.gradle.appname=$APP_BASE_NAME" \ -classpath "$CLASSPATH" \ org.gradle.wrapper.GradleWrapperMain \ "$@" # Stop when "xargs" is not available. if ! command -v xargs >/dev/null 2>&1 then die "xargs is not available" fi # Use "xargs" to parse quoted args. # # With -n1 it outputs one arg per line, with the quotes and backslashes removed. # # In Bash we could simply go: # # readarray ARGS < <( xargs -n1 <<<"$var" ) && # set -- "${ARGS[@]}" "$@" # # but POSIX shell has neither arrays nor command substitution, so instead we # post-process each arg (as a line of input to sed) to backslash-escape any # character that might be a shell metacharacter, then use eval to reverse # that process (while maintaining the separation between arguments), and wrap # the whole thing up as a single "set" statement. # # This will of course break if any of these variables contains a newline or # an unmatched quote. # eval "set -- $( printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | xargs -n1 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | tr '\n' ' ' )" '"$@"' exec "$JAVACMD" "$@" ================================================ FILE: gradlew.bat ================================================ @rem @rem Copyright 2015 the original author or authors. @rem @rem Licensed under the Apache License, Version 2.0 (the "License"); @rem you may not use this file except in compliance with the License. @rem You may obtain a copy of the License at @rem @rem https://www.apache.org/licenses/LICENSE-2.0 @rem @rem Unless required by applicable law or agreed to in writing, software @rem distributed under the License is distributed on an "AS IS" BASIS, @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @rem See the License for the specific language governing permissions and @rem limitations under the License. @rem @rem SPDX-License-Identifier: Apache-2.0 @rem @if "%DEBUG%"=="" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @rem @rem ########################################################################## @rem Set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" setlocal set DIRNAME=%~dp0 if "%DIRNAME%"=="" set DIRNAME=. @rem This is normally unused set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @rem Resolve any "." and ".." in APP_HOME to make it shorter. for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 if %ERRORLEVEL% equ 0 goto execute echo. 1>&2 echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 echo. 1>&2 echo Please set the JAVA_HOME variable in your environment to match the 1>&2 echo location of your Java installation. 1>&2 goto fail :findJavaFromJavaHome set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto execute echo. 1>&2 echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 echo. 1>&2 echo Please set the JAVA_HOME variable in your environment to match the 1>&2 echo location of your Java installation. 1>&2 goto fail :execute @rem Setup the command line set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar @rem Execute Gradle "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* :end @rem End local scope for the variables with windows NT shell if %ERRORLEVEL% equ 0 goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! set EXIT_CODE=%ERRORLEVEL% if %EXIT_CODE% equ 0 set EXIT_CODE=1 if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% exit /b %EXIT_CODE% :mainEnd if "%OS%"=="Windows_NT" endlocal :omega ================================================ FILE: settings.gradle ================================================ rootProject.name = 'temporal-java-samples' include 'core' include 'springai:basic' include 'springai:mcp' include 'springai:multimodel' include 'springai:rag' include 'springboot' include 'springboot-basic' ================================================ FILE: springai/basic/build.gradle ================================================ apply from: "$rootDir/gradle/springai.gradle" dependencies { implementation 'org.springframework.ai:spring-ai-starter-model-openai' } ================================================ FILE: springai/basic/src/main/java/io/temporal/samples/springai/chat/ChatExampleApplication.java ================================================ package io.temporal.samples.springai.chat; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import java.util.Scanner; import java.util.UUID; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.context.event.EventListener; import org.springframework.stereotype.Component; /** * Example application demonstrating the Spring AI Temporal plugin. * *

Starts an interactive chat workflow where each AI call is a durable Temporal activity with * automatic retries and timeout handling. */ @SpringBootApplication public class ChatExampleApplication { public static void main(String[] args) { SpringApplication.run(ChatExampleApplication.class, args); } } @Component class ChatRunner { private final WorkflowClient workflowClient; ChatRunner(WorkflowClient workflowClient) { this.workflowClient = workflowClient; } @EventListener(ApplicationReadyEvent.class) public void run() { String workflowId = "chat-" + UUID.randomUUID().toString().substring(0, 8); System.out.println("\n==========================================="); System.out.println(" Spring AI + Temporal Chat Demo"); System.out.println("==========================================="); System.out.println("Workflow ID: " + workflowId); System.out.println("Type messages, or 'quit' to exit.\n"); // Start the chat workflow ChatWorkflow workflow = workflowClient.newWorkflowStub( ChatWorkflow.class, WorkflowOptions.newBuilder() .setWorkflowId(workflowId) .setTaskQueue("spring-ai-example") .build()); WorkflowClient.start(workflow::run, "You are a helpful assistant. Be concise."); // Get stub for the running workflow ChatWorkflow chat = workflowClient.newWorkflowStub(ChatWorkflow.class, workflowId); // Interactive loop try (Scanner scanner = new Scanner(System.in, java.nio.charset.StandardCharsets.UTF_8)) { while (true) { System.out.print("You: "); String input = scanner.nextLine().trim(); if (input.equalsIgnoreCase("quit") || input.equalsIgnoreCase("exit")) { chat.end(); break; } if (input.isEmpty()) { continue; } try { String response = chat.chat(input); System.out.println("Assistant: " + response + "\n"); } catch (Exception e) { System.err.println("Error: " + e.getMessage() + "\n"); } } } System.out.println("Goodbye!"); System.exit(0); } } ================================================ FILE: springai/basic/src/main/java/io/temporal/samples/springai/chat/ChatWorkflow.java ================================================ package io.temporal.samples.springai.chat; import io.temporal.workflow.SignalMethod; import io.temporal.workflow.UpdateMethod; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; /** * A chat workflow that maintains a conversation with an AI model. * *

The workflow runs until explicitly ended via the {@link #end()} signal. Messages can be sent * via the {@link #chat(String)} update method, which returns the AI's response synchronously. */ @WorkflowInterface public interface ChatWorkflow { /** * Starts the chat workflow and waits until ended. * * @param systemPrompt the system prompt that defines the AI's behavior * @return a summary when the chat ends */ @WorkflowMethod String run(String systemPrompt); /** * Sends a message to the AI and returns its response. * * @param message the user's message * @return the AI's response */ @UpdateMethod String chat(String message); /** Ends the chat session. */ @SignalMethod void end(); } ================================================ FILE: springai/basic/src/main/java/io/temporal/samples/springai/chat/ChatWorkflowImpl.java ================================================ package io.temporal.samples.springai.chat; import io.temporal.activity.ActivityOptions; import io.temporal.common.RetryOptions; import io.temporal.springai.chat.TemporalChatClient; import io.temporal.springai.model.ActivityChatModel; import io.temporal.workflow.Workflow; import io.temporal.workflow.WorkflowInit; import java.time.Duration; import org.springframework.ai.chat.client.ChatClient; import org.springframework.ai.chat.client.advisor.PromptChatMemoryAdvisor; import org.springframework.ai.chat.memory.ChatMemory; import org.springframework.ai.chat.memory.InMemoryChatMemoryRepository; import org.springframework.ai.chat.memory.MessageWindowChatMemory; /** * Implementation of the chat workflow using Spring AI's ChatClient with Temporal tools. * *

This demonstrates how to use the Spring AI plugin within a Temporal workflow: * *

    *
  1. Build an {@link ActivityChatModel} via its factory to get a standard Spring AI ChatModel * backed by a durable Temporal activity *
  2. Create activity stubs for tools (e.g., {@link WeatherActivity}) *
  3. Create deterministic tools (e.g., {@link StringTools}) *
  4. Create side-effect tools (e.g., {@link TimestampTools}) *
  5. Use {@link TemporalChatClient} to build a tool-aware chat client *
* *

The AI model can call: * *

    *
  • {@code getWeather(city)} - Executes as a durable Temporal activity *
  • {@code getForecast(city, days)} - Executes as a durable Temporal activity *
  • {@code reverse(text)}, {@code countWords(text)}, etc. - Execute directly in workflow (plain * workflow tool) *
  • {@code getCurrentDateTime()}, {@code generateUuid()}, etc. - Wrapped in sideEffect * (@SideEffectTool) *
*/ public class ChatWorkflowImpl implements ChatWorkflow { private final ChatClient chatClient; private boolean ended = false; private int messageCount = 0; // @@@SNIPSTART samples-java-spring-ai-chat-workflow-init @WorkflowInit public ChatWorkflowImpl(String systemPrompt) { // Build an activity-backed chat model. The factory creates the activity stub // internally and registers per-call Summaries on the Temporal UI. ActivityChatModel activityChatModel = ActivityChatModel.forDefault(); // Create an activity stub for weather tools - these execute as durable activities WeatherActivity weatherTool = Workflow.newActivityStub( WeatherActivity.class, ActivityOptions.newBuilder() .setStartToCloseTimeout(Duration.ofSeconds(30)) .setRetryOptions(RetryOptions.newBuilder().setMaximumAttempts(3).build()) .build()); // Create deterministic tools - these execute directly in the workflow StringTools stringTools = new StringTools(); // Create side-effect tools - these are wrapped in Workflow.sideEffect() // The result is recorded in history, making replay deterministic TimestampTools timestampTools = new TimestampTools(); // Create chat memory - uses in-memory storage that gets rebuilt on replay ChatMemory chatMemory = MessageWindowChatMemory.builder() .chatMemoryRepository(new InMemoryChatMemoryRepository()) .maxMessages(20) .build(); // Build a TemporalChatClient with tools and memory // - Activity stubs (weatherTool) become durable AI tools // - plain workflow tool classes (stringTools) execute directly in workflow // - @SideEffectTool classes (timestampTools) are wrapped in sideEffect() // - PromptChatMemoryAdvisor maintains conversation history this.chatClient = TemporalChatClient.builder(activityChatModel) .defaultSystem(systemPrompt) .defaultTools(weatherTool, stringTools, timestampTools) .defaultAdvisors(PromptChatMemoryAdvisor.builder(chatMemory).build()) .build(); } // @@@SNIPEND @Override public String run(String systemPrompt) { // systemPrompt is unused here on purpose — @WorkflowInit requires the constructor // and the @WorkflowMethod to share a parameter list, and the constructor above // already consumed it to build the chat client. Workflow.await(() -> ended); return "Chat ended after " + messageCount + " messages."; } @Override public String chat(String message) { messageCount++; return chatClient.prompt().user(message).call().content(); } @Override public void end() { ended = true; } } ================================================ FILE: springai/basic/src/main/java/io/temporal/samples/springai/chat/StringTools.java ================================================ package io.temporal.samples.springai.chat; import org.springframework.ai.tool.annotation.Tool; import org.springframework.ai.tool.annotation.ToolParam; /** * Deterministic string manipulation tools. * *

These tools execute directly in workflow context. Since they are pure functions (same output * for same input, no side effects), they are safe for Temporal replay without any wrapping. */ // @@@SNIPSTART samples-java-spring-ai-plain-tool public class StringTools { @Tool(description = "Reverse a string, returning the characters in opposite order") public String reverse(@ToolParam(description = "The string to reverse") String input) { if (input == null) { return null; } return new StringBuilder(input).reverse().toString(); } @Tool(description = "Count the number of words in a text") public int countWords(@ToolParam(description = "The text to count words in") String text) { if (text == null || text.isBlank()) { return 0; } return text.trim().split("\\s+").length; } @Tool(description = "Convert text to all uppercase letters") public String toUpperCase(@ToolParam(description = "The text to convert") String text) { if (text == null) { return null; } return text.toUpperCase(java.util.Locale.ROOT); } @Tool(description = "Convert text to all lowercase letters") public String toLowerCase(@ToolParam(description = "The text to convert") String text) { if (text == null) { return null; } return text.toLowerCase(java.util.Locale.ROOT); } @Tool(description = "Check if a string is a palindrome (reads the same forwards and backwards)") public boolean isPalindrome(@ToolParam(description = "The text to check") String text) { if (text == null) { return false; } String normalized = text.toLowerCase(java.util.Locale.ROOT).replaceAll("\\s+", ""); String reversed = new StringBuilder(normalized).reverse().toString(); return normalized.equals(reversed); } } // @@@SNIPEND ================================================ FILE: springai/basic/src/main/java/io/temporal/samples/springai/chat/TimestampTools.java ================================================ package io.temporal.samples.springai.chat; import io.temporal.springai.tool.SideEffectTool; import java.time.Instant; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.UUID; import org.springframework.ai.tool.annotation.Tool; import org.springframework.ai.tool.annotation.ToolParam; /** * Side-effect tools that return non-deterministic values. * *

This class demonstrates the use of {@link SideEffectTool} annotation for tools that are * non-deterministic but don't need the full durability of an activity. * *

Side-effect tools are wrapped in {@code Workflow.sideEffect()}, which: * *

    *
  • Records the result in workflow history on first execution *
  • Returns the recorded result on replay (deterministic) *
  • Does not create activity tasks (lightweight) *
* *

Use {@code @SideEffectTool} for: * *

    *
  • Getting current time/date *
  • Generating random values (UUIDs, random numbers) *
  • Any non-deterministic operation that doesn't need retry/durability *
* *

Example usage: * *

{@code
 * TimestampTools timestampTools = new TimestampTools();
 * this.chatClient = TemporalChatClient.builder(activityChatModel)
 *         .defaultTools(timestampTools)  // Wrapped in sideEffect()
 *         .build();
 * }
*/ // @@@SNIPSTART samples-java-spring-ai-side-effect-tool @SideEffectTool public class TimestampTools { private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss z").withZone(ZoneId.systemDefault()); /** * Gets the current date and time. * *

This is non-deterministic (returns different values each time), but wrapped in sideEffect() * it becomes safe for workflow replay. * * @return the current date and time as a formatted string */ @Tool(description = "Get the current date and time") public String getCurrentDateTime() { return FORMATTER.format(Instant.now()); } /** * Gets the current Unix timestamp in milliseconds. * * @return the current time in milliseconds since epoch */ @Tool(description = "Get the current Unix timestamp in milliseconds") public long getCurrentTimestamp() { return System.currentTimeMillis(); } /** * Generates a random UUID. * * @return a new random UUID string */ @Tool(description = "Generate a random UUID") public String generateUuid() { return UUID.randomUUID().toString(); } /** * Gets the current date and time in a specific timezone. * * @param timezone the timezone ID (e.g., "America/New_York", "UTC", "Europe/London") * @return the current date and time in the specified timezone */ @Tool(description = "Get the current date and time in a specific timezone") public String getDateTimeInTimezone( @ToolParam(description = "Timezone ID (e.g., 'America/New_York', 'UTC', 'Europe/London')") String timezone) { try { ZoneId zoneId = ZoneId.of(timezone); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss z").withZone(zoneId); return formatter.format(Instant.now()); } catch (Exception e) { return "Invalid timezone: " + timezone + ". Use formats like 'America/New_York' or 'UTC'."; } } } // @@@SNIPEND ================================================ FILE: springai/basic/src/main/java/io/temporal/samples/springai/chat/WeatherActivity.java ================================================ package io.temporal.samples.springai.chat; import io.temporal.activity.ActivityInterface; import io.temporal.activity.ActivityMethod; import org.springframework.ai.tool.annotation.Tool; import org.springframework.ai.tool.annotation.ToolParam; /** * Activity interface for weather-related operations. * *

This demonstrates how to combine Temporal's {@link ActivityInterface} with Spring AI's {@link * Tool} annotation to create activity-based AI tools. * *

When passed to {@code TemporalChatClient.builder().defaultTools(weatherActivity)}, the AI * model can call these methods, and they will execute as durable Temporal activities with automatic * retries and timeout handling. */ // @@@SNIPSTART samples-java-spring-ai-activity-tool @ActivityInterface public interface WeatherActivity { /** * Gets the current weather for a city. * *

The {@code @Tool} annotation makes this method available to the AI model, while the * {@code @ActivityInterface} ensures it executes as a Temporal activity. * * @param city the name of the city * @return a description of the current weather */ @Tool( description = "Get the current weather for a city. Returns temperature, conditions, and humidity.") @ActivityMethod String getWeather( @ToolParam(description = "The name of the city (e.g., 'Seattle', 'New York')") String city); /** * Gets the weather forecast for a city. * * @param city the name of the city * @param days the number of days to forecast (1-7) * @return the weather forecast */ @Tool(description = "Get the weather forecast for a city for the specified number of days.") @ActivityMethod String getForecast( @ToolParam(description = "The name of the city") String city, @ToolParam(description = "Number of days to forecast (1-7)") int days); } // @@@SNIPEND ================================================ FILE: springai/basic/src/main/java/io/temporal/samples/springai/chat/WeatherActivityImpl.java ================================================ package io.temporal.samples.springai.chat; import java.util.Map; import java.util.Random; import org.springframework.stereotype.Component; /** * Implementation of {@link WeatherActivity}. * *

This is a mock implementation that returns simulated weather data. In a real application, this * would call an external weather API. * *

Note: This class is registered as a Spring {@code @Component} so it can be auto-discovered. * The {@code SpringAiPlugin} will register it with Temporal workers. */ @Component public class WeatherActivityImpl implements WeatherActivity { // Mock weather data for demo purposes private static final Map WEATHER_DATA = Map.of( "seattle", new String[] {"Rainy", "55"}, "new york", new String[] {"Partly Cloudy", "62"}, "los angeles", new String[] {"Sunny", "78"}, "chicago", new String[] {"Windy", "48"}, "miami", new String[] {"Hot and Humid", "88"}, "denver", new String[] {"Clear", "45"}, "boston", new String[] {"Overcast", "52"}); @Override public String getWeather(String city) { String normalizedCity = city.toLowerCase(java.util.Locale.ROOT).trim(); String[] weather = WEATHER_DATA.getOrDefault(normalizedCity, new String[] {"Unknown", "60"}); int humidity = 40 + new Random().nextInt(40); // 40-80% return String.format( "Weather in %s: %s, Temperature: %s°F, Humidity: %d%%", city, weather[0], weather[1], humidity); } @Override public String getForecast(String city, int days) { if (days < 1 || days > 7) { return "Error: Days must be between 1 and 7"; } StringBuilder forecast = new StringBuilder(); forecast.append(String.format("%d-day forecast for %s:\n", days, city)); String[] conditions = {"Sunny", "Partly Cloudy", "Cloudy", "Rainy", "Clear"}; Random random = new Random(); for (int i = 1; i <= days; i++) { String condition = conditions[random.nextInt(conditions.length)]; int high = 50 + random.nextInt(30); int low = high - 10 - random.nextInt(10); forecast.append( String.format(" Day %d: %s, High: %d°F, Low: %d°F\n", i, condition, high, low)); } return forecast.toString(); } } ================================================ FILE: springai/basic/src/main/resources/application.yaml ================================================ spring: application: name: spring-ai-temporal-example main: web-application-type: none ai: openai: api-key: ${OPENAI_API_KEY} chat: options: model: gpt-4o-mini temperature: 0.7 temporal: connection: target: localhost:7233 workers: - task-queue: spring-ai-example workflow-classes: - io.temporal.samples.springai.chat.ChatWorkflowImpl activity-beans: - weatherActivityImpl logging: level: io.temporal.springai: DEBUG ================================================ FILE: springai/mcp/build.gradle ================================================ apply from: "$rootDir/gradle/springai.gradle" dependencies { implementation 'org.springframework.ai:spring-ai-starter-model-openai' implementation 'org.springframework.ai:spring-ai-starter-mcp-client' implementation 'org.springframework.ai:spring-ai-rag' implementation 'org.springframework.boot:spring-boot-starter-webflux' } ================================================ FILE: springai/mcp/src/main/java/io/temporal/samples/springai/mcp/McpApplication.java ================================================ package io.temporal.samples.springai.mcp; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import java.nio.file.Files; import java.nio.file.Path; import java.util.Scanner; import java.util.UUID; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.context.event.EventListener; /** * Example application demonstrating MCP (Model Context Protocol) integration. * *

This application shows how to use tools from MCP servers within Temporal workflows. It * connects to a filesystem MCP server and provides an AI assistant that can read and write files. * *

Usage

* *
 * Commands:
 *   tools                - List available MCP tools
 *   <any message>       - Chat with the AI (it can use file tools)
 *   quit                 - End the chat
 * 
* *

Example Interactions

* *
 * > List files in the current directory
 * [AI uses list_directory tool and returns results]
 *
 * > Create a file called hello.txt with "Hello from MCP!"
 * [AI uses write_file tool]
 *
 * > Read the contents of hello.txt
 * [AI uses read_file tool]
 * 
* *

Prerequisites

* *
    *
  1. Start a Temporal dev server: {@code temporal server start-dev} *
  2. Set OPENAI_API_KEY environment variable *
  3. Ensure Node.js/npx is available (for MCP server) *
  4. Optionally set MCP_ALLOWED_PATH (defaults to /tmp/mcp-example) *
  5. Run: {@code ./gradlew :springai:mcp:bootRun} *
*/ @SpringBootApplication public class McpApplication { private static final String TASK_QUEUE = "mcp-example-queue"; @Autowired private WorkflowClient workflowClient; public static void main(String[] args) throws Exception { // The filesystem MCP server refuses to start if the allowed path doesn't // exist, so create it up front. Must happen before SpringApplication.run — // the MCP client connects during context startup. String allowedPath = System.getenv().getOrDefault("MCP_ALLOWED_PATH", "/tmp/mcp-example"); Files.createDirectories(Path.of(allowedPath)); SpringApplication.run(McpApplication.class, args); } /** Runs after workers are started (ApplicationReadyEvent fires after CommandLineRunner). */ @EventListener(ApplicationReadyEvent.class) public void onReady() throws Exception { // Start a new workflow String workflowId = "mcp-example-" + UUID.randomUUID().toString().substring(0, 8); McpWorkflow workflow = workflowClient.newWorkflowStub( McpWorkflow.class, WorkflowOptions.newBuilder() .setTaskQueue(TASK_QUEUE) .setWorkflowId(workflowId) .build()); // Start the workflow asynchronously WorkflowClient.start(workflow::run); // Give the workflow time to initialize (first workflow task must complete) Thread.sleep(1000); System.out.println("\n=== MCP Tools Demo ==="); System.out.println("Workflow ID: " + workflowId); System.out.println("\nThis demo uses the filesystem MCP server."); System.out.println("The AI can read, write, and list files in the allowed directory."); System.out.println("\nCommands:"); System.out.println(" tools - List available MCP tools"); System.out.println(" - Chat with the AI"); System.out.println(" quit - End the chat"); System.out.println(); // Get a workflow stub for sending signals/queries McpWorkflow workflowStub = workflowClient.newWorkflowStub(McpWorkflow.class, workflowId); // Note: tools command may take a moment to work while workflow initializes System.out.println("Type 'tools' to list available MCP tools.\n"); Scanner scanner = new Scanner(System.in, java.nio.charset.StandardCharsets.UTF_8); while (true) { System.out.print("> "); String input = scanner.nextLine().trim(); if (input.equalsIgnoreCase("quit")) { workflowStub.end(); System.out.println("Chat ended. Goodbye!"); break; } if (input.equalsIgnoreCase("tools")) { System.out.println(workflowStub.listTools()); continue; } if (input.isEmpty()) { continue; } System.out.println("[Processing...]"); // Capture current response BEFORE sending, so we can detect when it changes String previousResponse = workflowStub.getLastResponse(); // Send the message via signal workflowStub.chat(input); // Poll until the response changes (workflow has processed our message) for (int i = 0; i < 600; i++) { // Wait up to 60 seconds (MCP tools can be slow) String response = workflowStub.getLastResponse(); if (!response.equals(previousResponse)) { System.out.println("\n[AI]: " + response + "\n"); break; } Thread.sleep(100); } } } } ================================================ FILE: springai/mcp/src/main/java/io/temporal/samples/springai/mcp/McpWorkflow.java ================================================ package io.temporal.samples.springai.mcp; import io.temporal.workflow.QueryMethod; import io.temporal.workflow.SignalMethod; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; /** * Workflow interface demonstrating MCP (Model Context Protocol) integration. * *

This workflow shows how to use tools from MCP servers within Temporal workflows. The AI model * can call MCP tools (like file system operations) as durable activities. */ @WorkflowInterface public interface McpWorkflow { /** * Runs the workflow until ended. * * @return summary of the chat session */ @WorkflowMethod String run(); /** * Sends a message to the AI assistant with MCP tools available. * * @param message the user message */ @SignalMethod void chat(String message); /** * Gets the last response from the AI. * * @return the last response */ @QueryMethod String getLastResponse(); /** * Lists the available MCP tools. * * @return list of available tools */ @QueryMethod String listTools(); /** Ends the chat session. */ @SignalMethod void end(); } ================================================ FILE: springai/mcp/src/main/java/io/temporal/samples/springai/mcp/McpWorkflowImpl.java ================================================ package io.temporal.samples.springai.mcp; import io.temporal.springai.chat.TemporalChatClient; import io.temporal.springai.mcp.ActivityMcpClient; import io.temporal.springai.mcp.McpToolCallback; import io.temporal.springai.model.ActivityChatModel; import io.temporal.workflow.Workflow; import java.util.List; import java.util.stream.Collectors; import org.springframework.ai.chat.client.ChatClient; import org.springframework.ai.chat.client.advisor.PromptChatMemoryAdvisor; import org.springframework.ai.chat.memory.ChatMemory; import org.springframework.ai.chat.memory.InMemoryChatMemoryRepository; import org.springframework.ai.chat.memory.MessageWindowChatMemory; import org.springframework.ai.tool.ToolCallback; /** * Implementation of the MCP workflow. * *

This demonstrates how to use MCP tools from external servers within a Temporal workflow. The * workflow: * *

    *
  1. Creates an MCP client that wraps the McpClientActivity *
  2. Discovers tools from connected MCP servers *
  3. Registers those tools with the chat client *
  4. When the AI calls an MCP tool, it executes as a durable activity *
* *

This example uses the filesystem MCP server which provides tools like: * *

    *
  • {@code read_file} - Read contents of a file *
  • {@code write_file} - Write content to a file *
  • {@code list_directory} - List directory contents *
  • {@code create_directory} - Create a new directory *
*/ public class McpWorkflowImpl implements McpWorkflow { private ChatClient chatClient; private List mcpTools; private String lastResponse = ""; private boolean ended = false; private int messageCount = 0; private boolean initialized = false; @Override public String run() { // Discover MCP tools at the start of workflow execution (not in constructor) // This avoids the "root workflow thread yielding" warning ActivityMcpClient mcpClient = ActivityMcpClient.create(); mcpTools = McpToolCallback.fromMcpClient(mcpClient); // Create the chat model (uses the default ChatModel bean) ActivityChatModel chatModel = ActivityChatModel.forDefault(); // Create chat memory - uses in-memory storage that gets rebuilt on replay // since the same messages will be added in the same order ChatMemory chatMemory = MessageWindowChatMemory.builder() .chatMemoryRepository(new InMemoryChatMemoryRepository()) .maxMessages(20) .build(); // Build the chat client with MCP tools and memory advisor this.chatClient = TemporalChatClient.builder(chatModel) .defaultSystem( """ You are a helpful assistant with access to file system tools. You can read files, write files, list directories, and more. When asked to perform file operations, use your tools. Always confirm what you did after completing an operation. """) .defaultToolCallbacks(mcpTools) .defaultAdvisors(PromptChatMemoryAdvisor.builder(chatMemory).build()) .build(); initialized = true; // Wait until the chat is ended Workflow.await(() -> ended); return "Chat ended after " + messageCount + " messages."; } @Override public void chat(String message) { // The signal can land before run() has finished setting up the chat client (MCP tool // discovery is an activity, so initialization yields). Block in workflow time until // init completes, then process the message — the client's signal RPC has already // returned, so this only delays the workflow-side handling. Workflow.await(() -> initialized); messageCount++; // PromptChatMemoryAdvisor automatically handles conversation history lastResponse = chatClient.prompt().user(message).call().content(); } @Override public String getLastResponse() { return lastResponse; } @Override public String listTools() { if (!initialized || mcpTools == null) { return "Workflow is still initializing. Please wait a moment and try again."; } if (mcpTools.isEmpty()) { return "No MCP tools available. Check MCP server configuration."; } return mcpTools.stream() .map( tool -> " - " + tool.getToolDefinition().name() + ": " + tool.getToolDefinition().description()) .collect(Collectors.joining("\n", "Available MCP tools:\n", "")); } @Override public void end() { ended = true; } } ================================================ FILE: springai/mcp/src/main/resources/application.yaml ================================================ spring: main: banner-mode: off web-application-type: none ai: openai: api-key: ${OPENAI_API_KEY} chat: options: model: gpt-4o-mini mcp: client: stdio: connections: # Filesystem MCP server - provides read_file, write_file, list_directory tools filesystem: command: npx args: - "-y" - "@modelcontextprotocol/server-filesystem" - "${MCP_ALLOWED_PATH:/tmp/mcp-example}" temporal: connection: target: localhost:7233 workers: - task-queue: mcp-example-queue workflow-classes: - io.temporal.samples.springai.mcp.McpWorkflowImpl logging: level: io.temporal.springai: DEBUG ================================================ FILE: springai/multimodel/build.gradle ================================================ apply from: "$rootDir/gradle/springai.gradle" dependencies { implementation 'org.springframework.ai:spring-ai-starter-model-openai' implementation 'org.springframework.ai:spring-ai-starter-model-anthropic' } ================================================ FILE: springai/multimodel/src/main/java/io/temporal/samples/springai/multimodel/ChatModelConfig.java ================================================ package io.temporal.samples.springai.multimodel; import io.temporal.activity.ActivityOptions; import io.temporal.springai.autoconfigure.ChatModelActivityOptions; import io.temporal.springai.model.ActivityChatModel; import java.time.Duration; import java.util.Map; import org.springframework.ai.anthropic.AnthropicChatModel; import org.springframework.ai.anthropic.AnthropicChatOptions; import org.springframework.ai.anthropic.api.AnthropicApi; import org.springframework.ai.chat.model.ChatModel; import org.springframework.ai.openai.OpenAiChatModel; import org.springframework.ai.openai.OpenAiChatOptions; import org.springframework.ai.openai.api.OpenAiApi; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; /** * Configuration for multiple chat models from different providers. * *

This demonstrates how to configure multiple AI providers in a Spring Boot application. Each * model is registered as a separate bean with a unique name. * *

In workflows, these can be accessed via: * *

    *
  • {@code ActivityChatModel.forDefault()} - Uses the @Primary model (openAiChatModel) *
  • {@code ActivityChatModel.forModel("openAiChatModel")} - Uses OpenAI gpt-4o-mini *
  • {@code ActivityChatModel.forModel("anthropicChatModel")} - Uses Anthropic Claude *
*/ @Configuration public class ChatModelConfig { @Value("${spring.ai.openai.api-key}") private String openAiApiKey; @Value("${spring.ai.anthropic.api-key}") private String anthropicApiKey; /** * OpenAI model using gpt-4o-mini for quick, cost-effective responses. Marked as @Primary so it's * used when no specific model is requested. */ @Bean @Primary public ChatModel openAiChatModel() { OpenAiApi api = OpenAiApi.builder().apiKey(openAiApiKey).build(); OpenAiChatOptions options = OpenAiChatOptions.builder().model("gpt-4o-mini").temperature(0.7).build(); return OpenAiChatModel.builder().openAiApi(api).defaultOptions(options).build(); } /** Anthropic model using Claude for complex reasoning tasks. */ @Bean public ChatModel anthropicChatModel() { AnthropicApi api = AnthropicApi.builder().apiKey(anthropicApiKey).build(); AnthropicChatOptions options = AnthropicChatOptions.builder() .model("claude-sonnet-4-20250514") .temperature(0.3) // Lower temperature for more focused reasoning .build(); return AnthropicChatModel.builder().anthropicApi(api).defaultOptions(options).build(); } /** * Per-model {@link ActivityOptions} overrides, declared as a single Spring bean. When present, * {@link ActivityChatModel#forModel(String)} and {@link ActivityChatModel#forDefault()} consult * this map before falling back to the plugin's defaults — so workflows can build a * fully-configured chat model with nothing more than {@code ActivityChatModel.forModel(name)}. * *

The Anthropic entry bumps the start-to-close timeout (reasoning models can take minutes) and * caps the schedule-to-close so a stuck request can't keep re-attempting forever. Building on * {@link ActivityChatModel#defaultActivityOptions()} preserves the plugin's * non-retryable-AI-error classification without having to restate it. * *

The workflow still uses the per-call {@code ChatClient.defaultOptions(...)} path for things * that change per prompt (see the {@code think:} route in {@code MultiModelWorkflowImpl} — * extended thinking is enabled per call, not globally). */ // @@@SNIPSTART samples-java-spring-ai-per-model-options @Bean public ChatModelActivityOptions chatModelActivityOptions() { return new ChatModelActivityOptions( Map.of( "anthropicChatModel", ActivityOptions.newBuilder(ActivityChatModel.defaultActivityOptions()) .setStartToCloseTimeout(Duration.ofMinutes(5)) .setScheduleToCloseTimeout(Duration.ofMinutes(15)) .build())); } // @@@SNIPEND } ================================================ FILE: springai/multimodel/src/main/java/io/temporal/samples/springai/multimodel/MultiModelApplication.java ================================================ package io.temporal.samples.springai.multimodel; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import java.util.Scanner; import java.util.UUID; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * Example application demonstrating multi-model support with different AI providers. * *

This application shows how to use different AI providers (OpenAI and Anthropic) within the * same Temporal workflow. It provides an interactive CLI where you can send messages to different * models. * *

Usage

* *
 * Commands:
 *   openai: <message>    - Send to OpenAI (gpt-4o-mini)
 *   anthropic: <message> - Send to Anthropic (Claude)
 *   think: <message>     - Send to Anthropic with extended thinking enabled
 *   <message>            - No prefix routes to the default model (the @Primary bean)
 *   quit                  - End the chat
 * 
* *

Prerequisites

* *
    *
  1. Start a Temporal dev server: {@code temporal server start-dev} *
  2. Set OPENAI_API_KEY environment variable *
  3. Set ANTHROPIC_API_KEY environment variable *
  4. Run: {@code ./gradlew :springai:multimodel:bootRun} *
*/ @SpringBootApplication public class MultiModelApplication implements CommandLineRunner { private static final String TASK_QUEUE = "multi-model-queue"; @Autowired private WorkflowClient workflowClient; public static void main(String[] args) { SpringApplication.run(MultiModelApplication.class, args); } @Override public void run(String... args) throws Exception { // Start a new workflow String workflowId = "multi-model-" + UUID.randomUUID().toString().substring(0, 8); MultiModelWorkflow workflow = workflowClient.newWorkflowStub( MultiModelWorkflow.class, WorkflowOptions.newBuilder() .setTaskQueue(TASK_QUEUE) .setWorkflowId(workflowId) .build()); // Start the workflow asynchronously WorkflowClient.start(workflow::run); System.out.println("\n=== Multi-Provider Chat Demo ==="); System.out.println("Workflow ID: " + workflowId); System.out.println("\nAvailable models:"); System.out.println(" openai: OpenAI gpt-4o-mini"); System.out.println(" anthropic: Anthropic Claude"); System.out.println(" think: Anthropic Claude with extended thinking (per-call options)"); System.out.println(" default: no prefix — routes to the @Primary model (OpenAI)"); System.out.println("\nCommands:"); System.out.println(" openai: - Send to OpenAI"); System.out.println(" anthropic: - Send to Anthropic"); System.out.println(" think: - Send to Anthropic with extended thinking enabled"); System.out.println(" - No prefix routes to the default model"); System.out.println(" quit - End the chat"); System.out.println(); // Get a workflow stub for sending signals MultiModelWorkflow workflowStub = workflowClient.newWorkflowStub(MultiModelWorkflow.class, workflowId); Scanner scanner = new Scanner(System.in, java.nio.charset.StandardCharsets.UTF_8); while (true) { System.out.print("> "); String input = scanner.nextLine().trim(); if (input.equalsIgnoreCase("quit")) { workflowStub.end(); System.out.println("Chat ended. Goodbye!"); break; } // Parse the model and message String modelName; String message; if (input.startsWith("openai:")) { modelName = "openai"; message = input.substring(7).trim(); } else if (input.startsWith("anthropic:")) { modelName = "anthropic"; message = input.substring(10).trim(); } else if (input.startsWith("think:")) { modelName = "think"; message = input.substring(6).trim(); } else { // No prefix — route to the workflow's "default" model (the @Primary bean, // resolved by ActivityChatModel.forDefault() inside the workflow). modelName = "default"; message = input; } if (message.isEmpty()) { System.out.println("Please enter a message."); continue; } // Capture current response BEFORE sending so we can detect the change against // the pre-signal baseline (not against an empty string — the workflow may already // hold the previous prompt's reply). String previousResponse = workflowStub.getLastResponse(); System.out.println("[Sending to " + modelName + " model...]"); workflowStub.chat(modelName, message); // Poll until the response changes from the pre-signal baseline. for (int i = 0; i < 300; i++) { // Wait up to 30 seconds String response = workflowStub.getLastResponse(); if (!response.equals(previousResponse)) { System.out.println( "\n[" + modelName.toUpperCase(java.util.Locale.ROOT) + "]: " + response + "\n"); break; } Thread.sleep(100); } } } } ================================================ FILE: springai/multimodel/src/main/java/io/temporal/samples/springai/multimodel/MultiModelWorkflow.java ================================================ package io.temporal.samples.springai.multimodel; import io.temporal.workflow.QueryMethod; import io.temporal.workflow.SignalMethod; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; /** * Workflow interface demonstrating multiple chat models. * *

This workflow shows how to use different AI models for different purposes within the same * workflow. */ @WorkflowInterface public interface MultiModelWorkflow { /** * Runs the workflow until ended. * * @return summary of the chat session */ @WorkflowMethod String run(); /** * Sends a message to a specific model. * * @param modelName the name of the model to use ("openai", "anthropic", "think", or "default") * @param message the user message */ @SignalMethod void chat(String modelName, String message); /** * Gets the last response. * * @return the last response from any model */ @QueryMethod String getLastResponse(); /** Ends the chat session. */ @SignalMethod void end(); } ================================================ FILE: springai/multimodel/src/main/java/io/temporal/samples/springai/multimodel/MultiModelWorkflowImpl.java ================================================ package io.temporal.samples.springai.multimodel; import io.temporal.springai.chat.TemporalChatClient; import io.temporal.springai.model.ActivityChatModel; import io.temporal.workflow.Workflow; import io.temporal.workflow.WorkflowInit; import java.util.LinkedHashMap; import java.util.Map; import org.springframework.ai.anthropic.AnthropicChatOptions; import org.springframework.ai.anthropic.api.AnthropicApi; import org.springframework.ai.chat.client.ChatClient; /** * Implementation of the multi-model workflow. * *

This demonstrates how to use multiple AI providers in a single workflow: * *

    *
  • openai - Uses OpenAI gpt-4o-mini for quick, cost-effective responses *
  • anthropic - Uses Anthropic Claude for complex reasoning tasks *
  • think - Uses Anthropic Claude with extended thinking enabled for hard * problems. This demonstrates {@code temporal-spring-ai}'s provider-specific ChatOptions * pass-through: an {@link AnthropicChatOptions} instance with a {@code thinking} * configuration is attached per call, and every field survives the round-trip across the * activity boundary. *
  • default - Uses the primary/default model (OpenAI) *
* *

The workflow uses two patterns for wiring activity options: * *

    *
  • Bean-based overrides (declarative, static) — {@code ChatModelConfig} declares a * {@code ChatModelActivityOptions} bean with per-model {@code ActivityOptions}. The workflow * then just calls {@link ActivityChatModel#forDefault()} / {@link * ActivityChatModel#forModel(String)}, which consult that bean automatically. That covers * static per-model config (Anthropic needs a longer timeout because reasoning models are * slow; OpenAI uses plugin defaults). *
  • Per-call {@code ChatClient.defaultOptions(...)} (imperative, dynamic) — the {@code * think:} route builds an {@link AnthropicChatOptions} instance with {@code thinking=ENABLED} * and attaches it via {@code defaultOptions(...)}. That exercises the plugin's * provider-specific ChatOptions pass-through: every field survives the round-trip across the * activity boundary. *
*/ public class MultiModelWorkflowImpl implements MultiModelWorkflow { private final Map chatClients; private String lastResponse = ""; private boolean ended = false; private int messageCount = 0; @WorkflowInit public MultiModelWorkflowImpl() { // LinkedHashMap (not HashMap) so the keySet() rendering in the unknown-model error // path is deterministic across replays. HashMap iteration order is unspecified and // can differ between JVM versions or workers. chatClients = new LinkedHashMap<>(); // The "default" and "openai" entries below both end up calling OpenAI in this sample — // ChatModelConfig declares @Primary on openAiChatModel, so ActivityChatModel.forDefault() // resolves to it. They're registered as two entries on purpose: "default" demonstrates // the forDefault() / @Primary-resolution path (no bean name needed in workflow code), // and "openai" demonstrates the forModel(name) explicit-lookup path. In a workflow that // only uses one model, you'd typically pick one of these two patterns and stop there. ActivityChatModel defaultModel = ActivityChatModel.forDefault(); chatClients.put( "default", TemporalChatClient.builder(defaultModel) .defaultSystem("You are a helpful assistant. You are the DEFAULT model.") .build()); ActivityChatModel openAiModel = ActivityChatModel.forModel("openAiChatModel"); chatClients.put( "openai", TemporalChatClient.builder(openAiModel) .defaultSystem("You are a helpful assistant powered by OpenAI. Keep answers concise.") .build()); // Create a chat client using Anthropic Claude. The per-model ActivityOptions (longer // start-to-close + schedule-to-close caps) live on the ChatModelActivityOptions bean in // ChatModelConfig; forModel(name) consults that bean automatically. The workflow stays // free of infrastructure wiring — ideal for static per-model config. ActivityChatModel anthropicModel = ActivityChatModel.forModel("anthropicChatModel"); chatClients.put( "anthropic", TemporalChatClient.builder(anthropicModel) .defaultSystem( "You are a helpful assistant powered by Anthropic. " + "You excel at careful reasoning and nuanced responses.") .build()); // Create a chat client that turns on Anthropic's extended-thinking mode. This exercises // the plugin's provider-specific ChatOptions pass-through end to end: the // AnthropicChatOptions (with thinking=ENABLED + budget_tokens) is passed via // .defaultOptions(...) on the ChatClient, crosses the activity boundary serialized as // (class name, JSON), and is rehydrated by ChatModelActivityImpl before the prompt is // sent to Claude. Required side effects for extended thinking: temperature must be 1.0 // and max_tokens must exceed budget_tokens. // @@@SNIPSTART samples-java-spring-ai-provider-options AnthropicChatOptions thinkingOptions = AnthropicChatOptions.builder() .thinking(AnthropicApi.ThinkingType.ENABLED, 1024) .temperature(1.0) .maxTokens(4096) .build(); chatClients.put( "think", TemporalChatClient.builder(anthropicModel) .defaultSystem( "You are a helpful assistant powered by Anthropic with extended thinking. " + "Use the thinking budget to reason carefully, then give a crisp answer " + "that reflects the reasoning you did.") .defaultOptions(thinkingOptions) .build()); // @@@SNIPEND } @Override public String run() { // Wait until the chat is ended Workflow.await(() -> ended); return "Chat ended after " + messageCount + " messages."; } @Override public void chat(String modelName, String message) { messageCount++; ChatClient client = chatClients.get(modelName); if (client == null) { lastResponse = "Unknown model: " + modelName + ". Available: " + chatClients.keySet(); return; } lastResponse = client.prompt().user(message).call().content(); } @Override public String getLastResponse() { return lastResponse; } @Override public void end() { ended = true; } } ================================================ FILE: springai/multimodel/src/main/resources/application.yaml ================================================ spring: main: banner-mode: off web-application-type: none autoconfigure: exclude: - org.springframework.ai.model.openai.autoconfigure.OpenAiChatAutoConfiguration - org.springframework.ai.model.anthropic.autoconfigure.AnthropicChatAutoConfiguration ai: openai: api-key: ${OPENAI_API_KEY} anthropic: api-key: ${ANTHROPIC_API_KEY} # Note: The actual models are configured in ChatModelConfig.java temporal: connection: target: localhost:7233 workers: - task-queue: multi-model-queue workflow-classes: - io.temporal.samples.springai.multimodel.MultiModelWorkflowImpl logging: level: io.temporal.springai: DEBUG ================================================ FILE: springai/rag/build.gradle ================================================ apply from: "$rootDir/gradle/springai.gradle" dependencies { implementation 'org.springframework.ai:spring-ai-starter-model-openai' implementation 'org.springframework.ai:spring-ai-rag' } ================================================ FILE: springai/rag/src/main/java/io/temporal/samples/springai/rag/RagApplication.java ================================================ package io.temporal.samples.springai.rag; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import java.util.Scanner; import java.util.UUID; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * Example application demonstrating RAG with a Spring AI VectorStore. * *

This application shows how to use the plugin's VectorStoreActivity to build a durable * knowledge base within Temporal workflows. Embeddings are produced by whichever {@code * EmbeddingModel} the configured Spring AI {@code VectorStore} uses internally — this sample does * not invoke {@code EmbeddingModelActivity} directly. * *

Usage

* *
 * Commands:
 *   add <id> <content>  - Add a document to the knowledge base
 *   ask <question>      - Ask a question (uses RAG)
 *   search <query>      - Search for similar documents
 *   count               - Show document count
 *   quit                - End the session
 * 
* *

Prerequisites

* *
    *
  1. Start a Temporal dev server: {@code temporal server start-dev} *
  2. Set OPENAI_API_KEY environment variable *
  3. Run: {@code ./gradlew :springai:rag:bootRun} *
*/ @SpringBootApplication public class RagApplication implements CommandLineRunner { private static final String TASK_QUEUE = "rag-example-queue"; @Autowired private WorkflowClient workflowClient; public static void main(String[] args) { SpringApplication.run(RagApplication.class, args); } @Override public void run(String... args) throws Exception { // Start a new workflow String workflowId = "rag-example-" + UUID.randomUUID().toString().substring(0, 8); RagWorkflow workflow = workflowClient.newWorkflowStub( RagWorkflow.class, WorkflowOptions.newBuilder() .setTaskQueue(TASK_QUEUE) .setWorkflowId(workflowId) .build()); // Start the workflow asynchronously WorkflowClient.start(workflow::run); System.out.println("\n=== RAG (Retrieval-Augmented Generation) Demo ==="); System.out.println("Workflow ID: " + workflowId); System.out.println("\nThis demo uses VectorStoreActivity to build a durable knowledge"); System.out.println("base with semantic search (embeddings are handled by the configured"); System.out.println("Spring AI VectorStore)."); System.out.println("\nCommands:"); System.out.println(" add - Add a document"); System.out.println(" ask - Ask a question (RAG)"); System.out.println(" search - Search documents"); System.out.println(" count - Show document count"); System.out.println(" quit - End session"); System.out.println("\nTry adding some documents first, then ask questions about them!"); System.out.println(); // Get a workflow stub for sending signals/queries RagWorkflow workflowStub = workflowClient.newWorkflowStub(RagWorkflow.class, workflowId); Scanner scanner = new Scanner(System.in, java.nio.charset.StandardCharsets.UTF_8); while (true) { System.out.print("> "); String input = scanner.nextLine().trim(); if (input.equalsIgnoreCase("quit")) { workflowStub.end(); System.out.println("Session ended. Goodbye!"); break; } if (input.equalsIgnoreCase("count")) { System.out.println("Documents in knowledge base: " + workflowStub.getDocumentCount()); continue; } if (input.equals("add") || input.startsWith("add ")) { String rest = input.length() > 3 ? input.substring(4).trim() : ""; int spaceIndex = rest.indexOf(' '); if (spaceIndex == -1) { System.out.println("Usage: add "); continue; } String id = rest.substring(0, spaceIndex); String content = rest.substring(spaceIndex + 1).trim(); // Capture current response BEFORE sending so waitForResponse can detect when it changes. String previousResponse = workflowStub.getLastResponse(); System.out.println("[Adding document...]"); workflowStub.addDocument(id, content); waitForResponse(workflowStub, previousResponse); continue; } if (input.equals("ask") || input.startsWith("ask ")) { String question = input.length() > 3 ? input.substring(4).trim() : ""; if (question.isEmpty()) { System.out.println("Usage: ask "); continue; } String previousResponse = workflowStub.getLastResponse(); System.out.println("[Searching and generating answer...]"); workflowStub.ask(question); waitForResponse(workflowStub, previousResponse); continue; } if (input.equals("search") || input.startsWith("search ")) { String query = input.length() > 6 ? input.substring(7).trim() : ""; if (query.isEmpty()) { System.out.println("Usage: search "); continue; } String previousResponse = workflowStub.getLastResponse(); System.out.println("[Searching...]"); workflowStub.search(query, 5); waitForResponse(workflowStub, previousResponse); continue; } if (!input.isEmpty()) { System.out.println("Unknown command. Use: add, ask, search, count, or quit"); } } } private void waitForResponse(RagWorkflow workflowStub, String previousResponse) throws InterruptedException { for (int i = 0; i < 600; i++) { // Wait up to 60 seconds Thread.sleep(100); String response = workflowStub.getLastResponse(); if (!response.equals(previousResponse)) { System.out.println("\n" + response + "\n"); return; } } System.out.println("[Timeout waiting for response]"); } } ================================================ FILE: springai/rag/src/main/java/io/temporal/samples/springai/rag/RagWorkflow.java ================================================ package io.temporal.samples.springai.rag; import io.temporal.workflow.QueryMethod; import io.temporal.workflow.SignalMethod; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; /** * Workflow interface demonstrating RAG (Retrieval-Augmented Generation). * *

This workflow shows how to use VectorStoreActivity and EmbeddingModelActivity to build a * durable knowledge base that can be queried with natural language. */ @WorkflowInterface public interface RagWorkflow { /** * Runs the workflow until ended. * * @return summary of the session */ @WorkflowMethod String run(); /** * Adds a document to the knowledge base. * * @param id unique identifier for the document * @param content the document content */ @SignalMethod void addDocument(String id, String content); /** * Asks a question using RAG - retrieves relevant documents and generates an answer. * * @param question the question to answer */ @SignalMethod void ask(String question); /** * Searches for similar documents without generating an answer. * * @param query the search query * @param topK number of results to return */ @SignalMethod void search(String query, int topK); /** * Gets the last response from the AI or search. * * @return the last response */ @QueryMethod String getLastResponse(); /** * Gets the current document count. * * @return number of documents in the knowledge base */ @QueryMethod int getDocumentCount(); /** Ends the session. */ @SignalMethod void end(); } ================================================ FILE: springai/rag/src/main/java/io/temporal/samples/springai/rag/RagWorkflowImpl.java ================================================ package io.temporal.samples.springai.rag; import io.temporal.activity.ActivityOptions; import io.temporal.common.RetryOptions; import io.temporal.springai.activity.VectorStoreActivity; import io.temporal.springai.chat.TemporalChatClient; import io.temporal.springai.model.ActivityChatModel; import io.temporal.springai.model.VectorStoreTypes; import io.temporal.workflow.Workflow; import io.temporal.workflow.WorkflowInit; import java.time.Duration; import java.util.List; import java.util.stream.Collectors; import org.springframework.ai.chat.client.ChatClient; /** * Implementation of the RAG workflow. * *

This demonstrates: * *

    *
  • Using {@link VectorStoreActivity} to store and search documents (the configured {@code * VectorStore} handles embedding internally) *
  • Combining vector search with chat for RAG *
* *

All operations are durable Temporal activities - if the worker restarts, the workflow will * continue from where it left off. */ public class RagWorkflowImpl implements RagWorkflow { private final VectorStoreActivity vectorStore; private final ChatClient chatClient; private String lastResponse = ""; private int documentCount = 0; private boolean ended = false; @WorkflowInit public RagWorkflowImpl() { // Create activity stubs with appropriate timeouts ActivityOptions activityOptions = ActivityOptions.newBuilder() .setStartToCloseTimeout(Duration.ofMinutes(2)) .setRetryOptions(RetryOptions.newBuilder().setMaximumAttempts(3).build()) .build(); this.vectorStore = Workflow.newActivityStub(VectorStoreActivity.class, activityOptions); // Create the chat client ActivityChatModel chatModel = ActivityChatModel.forDefault(); this.chatClient = TemporalChatClient.builder(chatModel) .defaultSystem( """ You are a helpful assistant that answers questions based on the provided context. When answering: - Use only the information from the context provided - If the context doesn't contain relevant information, say so - Be concise and direct """) .build(); } @Override public String run() { Workflow.await(() -> ended); return "Session ended. Processed " + documentCount + " documents."; } @Override public void addDocument(String id, String content) { // Create a document and add it to the vector store // The vector store will use the embedding model to generate embeddings VectorStoreTypes.Document doc = new VectorStoreTypes.Document(id, content); vectorStore.addDocuments(new VectorStoreTypes.AddDocumentsInput(List.of(doc))); documentCount++; lastResponse = "Added document '" + id + "' to knowledge base. Total documents: " + documentCount; } @Override public void ask(String question) { // Step 1: Search for relevant documents VectorStoreTypes.SearchOutput searchResults = vectorStore.similaritySearch(new VectorStoreTypes.SearchInput(question, 3)); if (searchResults.documents().isEmpty()) { lastResponse = "No relevant documents found in the knowledge base."; return; } // Step 2: Build context from search results String context = searchResults.documents().stream() .map(result -> result.document().text()) .collect(Collectors.joining("\n\n---\n\n")); // Step 3: Generate answer using the context lastResponse = chatClient .prompt() .user( u -> u.text( """ Context: {context} Question: {question} Answer based on the context above: """) .param("context", context) .param("question", question)) .call() .content(); } @Override public void search(String query, int topK) { VectorStoreTypes.SearchOutput searchResults = vectorStore.similaritySearch(new VectorStoreTypes.SearchInput(query, topK)); if (searchResults.documents().isEmpty()) { lastResponse = "No matching documents found."; return; } StringBuilder sb = new StringBuilder("Search results:\n\n"); for (int i = 0; i < searchResults.documents().size(); i++) { VectorStoreTypes.SearchResult result = searchResults.documents().get(i); sb.append( String.format( "%d. [Score: %.3f] %s\n %s\n\n", i + 1, result.score(), result.document().id(), truncate(result.document().text(), 100))); } lastResponse = sb.toString(); } @Override public String getLastResponse() { return lastResponse; } @Override public int getDocumentCount() { return documentCount; } @Override public void end() { ended = true; } private String truncate(String text, int maxLength) { if (text.length() <= maxLength) { return text; } return text.substring(0, maxLength) + "..."; } } ================================================ FILE: springai/rag/src/main/java/io/temporal/samples/springai/rag/VectorStoreConfig.java ================================================ package io.temporal.samples.springai.rag; import org.springframework.ai.embedding.EmbeddingModel; import org.springframework.ai.vectorstore.SimpleVectorStore; import org.springframework.ai.vectorstore.VectorStore; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * Configuration for the vector store. * *

This example uses Spring AI's SimpleVectorStore, an in-memory vector store that's perfect for * demos and testing. In production, you'd use a real vector database like Pinecone, Weaviate, * Milvus, or pgvector. */ @Configuration public class VectorStoreConfig { /** * Creates an in-memory vector store using the provided embedding model. * *

The SimpleVectorStore stores vectors in memory and uses the embedding model to convert text * to vectors when documents are added. * * @param embeddingModel the embedding model to use for vectorization * @return the configured vector store */ @Bean public VectorStore vectorStore(EmbeddingModel embeddingModel) { return SimpleVectorStore.builder(embeddingModel).build(); } } ================================================ FILE: springai/rag/src/main/resources/application.yaml ================================================ spring: main: banner-mode: off web-application-type: none ai: openai: api-key: ${OPENAI_API_KEY} chat: options: model: gpt-4o-mini embedding: options: model: text-embedding-3-small temporal: connection: target: localhost:7233 workers: - task-queue: rag-example-queue workflow-classes: - io.temporal.samples.springai.rag.RagWorkflowImpl logging: level: io.temporal.springai: DEBUG ================================================ FILE: springboot/build.gradle ================================================ apply plugin: 'org.springframework.boot' dependencies { implementation "org.springframework.boot:spring-boot-starter-web" implementation "org.springframework.boot:spring-boot-starter-thymeleaf" implementation "org.springframework.boot:spring-boot-starter-actuator" implementation "org.springframework.boot:spring-boot-starter-data-jpa" implementation "org.springframework.kafka:spring-kafka" // we set this as impl depends to use embedded kafka in samples not just tests implementation "org.springframework.kafka:spring-kafka-test" implementation "io.temporal:temporal-spring-boot-starter:$javaSDKVersion" // Environment configuration implementation "io.temporal:temporal-envconfig:$javaSDKVersion" implementation "org.apache.camel.springboot:camel-spring-boot-starter:$camelVersion" implementation "org.apache.camel.springboot:camel-servlet-starter:$camelVersion" runtimeOnly "io.micrometer:micrometer-registry-prometheus" runtimeOnly "com.h2database:h2" testImplementation "org.springframework.boot:spring-boot-starter-test" dependencies { errorproneJavac('com.google.errorprone:javac:9+181-r4173-1') errorprone('com.google.errorprone:error_prone_core:2.28.0') } } bootJar { enabled = false } jar { enabled = true } ================================================ FILE: springboot/src/main/java/io/temporal/samples/springboot/SamplesController.java ================================================ package io.temporal.samples.springboot; import io.grpc.StatusRuntimeException; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.client.WorkflowStub; import io.temporal.client.WorkflowUpdateException; import io.temporal.samples.springboot.customize.CustomizeWorkflow; import io.temporal.samples.springboot.hello.HelloWorkflow; import io.temporal.samples.springboot.hello.model.Person; import io.temporal.samples.springboot.kafka.MessageWorkflow; import io.temporal.samples.springboot.update.PurchaseWorkflow; import io.temporal.samples.springboot.update.model.ProductRepository; import io.temporal.samples.springboot.update.model.Purchase; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; @Controller public class SamplesController { @Autowired WorkflowClient client; @Autowired ProductRepository productRepository; @GetMapping("/hello") public String hello(Model model) { model.addAttribute("sample", "Say Hello"); return "hello"; } @PostMapping( value = "/hello", consumes = {MediaType.APPLICATION_JSON_VALUE}, produces = {MediaType.TEXT_HTML_VALUE}) ResponseEntity helloSample(@RequestBody Person person) { HelloWorkflow workflow = client.newWorkflowStub( HelloWorkflow.class, WorkflowOptions.newBuilder() .setTaskQueue("HelloSampleTaskQueue") .setWorkflowId("HelloSample") .build()); // bypass thymeleaf, don't return template name just result return new ResponseEntity<>("\"" + workflow.sayHello(person) + "\"", HttpStatus.OK); } @GetMapping("/metrics") public String metrics(Model model) { model.addAttribute("sample", "SDK Metrics"); return "metrics"; } @GetMapping("/update") public String update(Model model) { model.addAttribute("sample", "Synchronous Update"); model.addAttribute("products", productRepository.findAll()); return "update"; } @GetMapping("/update/inventory") public String updateInventory(Model model) { model.addAttribute("products", productRepository.findAll()); return "update :: inventory"; } @PostMapping( value = "/update/purchase", consumes = {MediaType.APPLICATION_JSON_VALUE}, produces = {MediaType.TEXT_HTML_VALUE}) ResponseEntity purchase(@RequestBody Purchase purchase) { PurchaseWorkflow workflow = client.newWorkflowStub( PurchaseWorkflow.class, WorkflowOptions.newBuilder() .setTaskQueue("UpdateSampleTaskQueue") .setWorkflowId("NewPurchase") .build()); WorkflowClient.start(workflow::start); // send update try { boolean isValidPurchase = workflow.makePurchase(purchase); // for sample send exit to workflow exec and wait till it completes workflow.exit(); WorkflowStub.fromTyped(workflow).getResult(Void.class); if (!isValidPurchase) { return new ResponseEntity<>("\"Invalid purchase\"", HttpStatus.NOT_FOUND); } return new ResponseEntity<>("\"" + "Purchase successful" + "\"", HttpStatus.OK); } catch (WorkflowUpdateException | StatusRuntimeException e) { // for sample send exit to workflow exec and wait till it completes workflow.exit(); WorkflowStub.fromTyped(workflow).getResult(Void.class); String message = e.getMessage(); if (e instanceof WorkflowUpdateException) { message = e.getCause().getMessage(); } return new ResponseEntity<>("\"" + message + "\"", HttpStatus.NOT_FOUND); } } @GetMapping("/kafka") public String kafka(Model model) { model.addAttribute("sample", "Kafka Request / Reply"); return "kafka"; } @PostMapping( value = "/kafka", consumes = {MediaType.TEXT_PLAIN_VALUE}, produces = {MediaType.TEXT_HTML_VALUE}) ResponseEntity sendToKafka(@RequestBody String message) { MessageWorkflow workflow = client.newWorkflowStub( MessageWorkflow.class, WorkflowOptions.newBuilder() .setTaskQueue("KafkaSampleTaskQueue") .setWorkflowId("MessageSample") .build()); WorkflowClient.start(workflow::start); workflow.update(message); // wait till exec completes WorkflowStub.fromTyped(workflow).getResult(Void.class); // bypass thymeleaf, don't return template name just result return new ResponseEntity<>("\" Message workflow completed\"", HttpStatus.OK); } @GetMapping("/customize") public String customize(Model model) { model.addAttribute("sample", "Customizing Options"); return "customize"; } @PostMapping( value = "/customize", consumes = {MediaType.APPLICATION_JSON_VALUE}, produces = {MediaType.TEXT_HTML_VALUE}) ResponseEntity customizeSample() { CustomizeWorkflow workflow = client.newWorkflowStub( CustomizeWorkflow.class, WorkflowOptions.newBuilder() .setTaskQueue("CustomizeTaskQueue") .setWorkflowId("CustomizeSample") .build()); // bypass thymeleaf, don't return template name just result return new ResponseEntity<>("\"" + workflow.execute() + "\"", HttpStatus.OK); } @GetMapping("/camel") public String camel(Model model) { model.addAttribute("sample", "Camel Route"); return "camel"; } @GetMapping("/customendpoint") public String customEndpoint(Model model) { model.addAttribute("sample", "Custom Actuator Worker Info Endpoint"); return "actuator"; } } ================================================ FILE: springboot/src/main/java/io/temporal/samples/springboot/TemporalSpringbootSamplesApplication.java ================================================ package io.temporal.samples.springboot; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class TemporalSpringbootSamplesApplication { public static void main(String[] args) { SpringApplication.run(TemporalSpringbootSamplesApplication.class, args); } } ================================================ FILE: springboot/src/main/java/io/temporal/samples/springboot/actuator/README.md ================================================ # SpringBoot Actuator Worker Info Endpoint - Sample 1. Start SpringBoot from main samples repo directory: ./gradlew bootRun 2. In your browser navigate to: http://localhost:3030/actuator/temporalworkerinfo This sample shows how to create a custom Actuator Endpoint that displays registered workflow and activity implementations per task queue. This information comes from actually registered workers done by autoconfig module. ================================================ FILE: springboot/src/main/java/io/temporal/samples/springboot/actuator/WorkerActuatorEndpoint.java ================================================ package io.temporal.samples.springboot.actuator; import io.temporal.common.metadata.*; import io.temporal.spring.boot.autoconfigure.template.WorkersTemplate; import java.lang.reflect.Method; import java.util.Map; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.actuate.endpoint.annotation.Endpoint; import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; import org.springframework.stereotype.Component; @Component @Endpoint(id = "temporalworkerinfo") public class WorkerActuatorEndpoint { @Autowired @Qualifier("temporalWorkersTemplate") private WorkersTemplate workersTemplate; @ReadOperation public String workerInfo() { StringBuilder sb = new StringBuilder(); Map registeredInfo = workersTemplate.getRegisteredInfo(); sb.append("Worker Info:"); registeredInfo.forEach( (taskQueue, info) -> { sb.append("\n\n\tTask Queue: ").append(taskQueue); info.getRegisteredWorkflowInfo() .forEach( (workflowInfo) -> { sb.append("\n\t\t Workflow Interface: ").append(workflowInfo.getClassName()); POJOWorkflowImplMetadata metadata = workflowInfo.getMetadata(); sb.append("\n\t\t\t Workflow Methods: "); sb.append( metadata.getWorkflowMethods().stream() .map(POJOWorkflowMethodMetadata::getWorkflowMethod) .map(Method::getName) .collect(Collectors.joining(", "))); sb.append("\n\t\t\t Query Methods: "); sb.append( metadata.getQueryMethods().stream() .map(POJOWorkflowMethodMetadata::getWorkflowMethod) .map(Method::getName) .collect(Collectors.joining(", "))); sb.append("\n\t\t\t Signal Methods: "); sb.append( metadata.getSignalMethods().stream() .map(POJOWorkflowMethodMetadata::getWorkflowMethod) .map(Method::getName) .collect(Collectors.joining(", "))); sb.append("\n\t\t\t Update Methods: "); sb.append( metadata.getUpdateMethods().stream() .map(POJOWorkflowMethodMetadata::getWorkflowMethod) .map(Method::getName) .collect(Collectors.joining(","))); sb.append("\n\t\t\t Update Validator Methods: "); sb.append( metadata.getUpdateValidatorMethods().stream() .map(POJOWorkflowMethodMetadata::getWorkflowMethod) .map(Method::getName) .collect(Collectors.joining(", "))); }); info.getRegisteredActivityInfo() .forEach( (activityInfo) -> { sb.append("\n\t\t Activity Impl: ").append(activityInfo.getClassName()); POJOActivityImplMetadata metadata = activityInfo.getMetadata(); sb.append("\n\t\t\t Activity Interfaces: "); sb.append( metadata.getActivityInterfaces().stream() .map(POJOActivityInterfaceMetadata::getInterfaceClass) .map(Class::getName) .collect(Collectors.joining(","))); sb.append("\n\t\t\t Activity Methods: "); sb.append( metadata.getActivityMethods().stream() .map(POJOActivityMethodMetadata::getMethod) .map(Method::getName) .collect(Collectors.joining(", "))); }); }); return sb.toString(); } } ================================================ FILE: springboot/src/main/java/io/temporal/samples/springboot/camel/CamelConfig.java ================================================ package io.temporal.samples.springboot.camel; import org.apache.camel.CamelContext; import org.apache.camel.ConsumerTemplate; import org.apache.camel.ProducerTemplate; import org.apache.camel.component.servlet.CamelHttpTransportServlet; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; @Configuration() @Profile("!test") public class CamelConfig { @Autowired private CamelContext camelContext; @Bean ServletRegistrationBean servletRegistrationBean() { String contextPath = "/temporalapp"; ServletRegistrationBean servlet = new ServletRegistrationBean(new CamelHttpTransportServlet(), contextPath + "/*"); servlet.setName("CamelServlet"); return servlet; } @Bean ProducerTemplate producerTemplate() { return camelContext.createProducerTemplate(); } @Bean ConsumerTemplate consumerTemplate() { return camelContext.createConsumerTemplate(); } } ================================================ FILE: springboot/src/main/java/io/temporal/samples/springboot/camel/CamelResource.java ================================================ package io.temporal.samples.springboot.camel; import java.util.List; import org.apache.camel.ProducerTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; @RestController public class CamelResource { @Autowired private ProducerTemplate producerTemplate; @GetMapping("/orders") @ResponseBody public List getProductsByCategory() { producerTemplate.start(); List orders = producerTemplate.requestBody("direct:getOrders", null, List.class); producerTemplate.stop(); return orders; } } ================================================ FILE: springboot/src/main/java/io/temporal/samples/springboot/camel/CamelRoutes.java ================================================ package io.temporal.samples.springboot.camel; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import org.apache.camel.builder.RouteBuilder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class CamelRoutes extends RouteBuilder { @Autowired private WorkflowClient workflowClient; @Autowired OrderRepository repository; @Override public void configure() { from("direct:getOrders") .routeId("direct-getOrders") .tracing() .process( exchange -> { OrderWorkflow workflow = workflowClient.newWorkflowStub( OrderWorkflow.class, WorkflowOptions.newBuilder() .setWorkflowId("CamelSampleWorkflow") .setTaskQueue("CamelSampleTaskQueue") .build()); exchange.getIn().setBody(workflow.start()); }) .end(); from("direct:findAllOrders") .routeId("direct-findAllOrders") .process( exchange -> { exchange.getIn().setBody(repository.findAll()); }) .end(); } } ================================================ FILE: springboot/src/main/java/io/temporal/samples/springboot/camel/OfficeOrder.java ================================================ package io.temporal.samples.springboot.camel; import javax.persistence.*; @Entity @Table(name = "officeorder") public class OfficeOrder { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column(nullable = false) private String number; @Column(nullable = false) private String desc; @Column(nullable = false) private String date; @Column(nullable = false) private double price; public OfficeOrder() {} public OfficeOrder(Integer id, String number, String desc, String date, double price) { this.id = id; this.number = number; this.desc = desc; this.date = date; this.price = price; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public String getNumber() { return number; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public void setNumber(String number) { this.number = number; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } } ================================================ FILE: springboot/src/main/java/io/temporal/samples/springboot/camel/OrderActivity.java ================================================ package io.temporal.samples.springboot.camel; import io.temporal.activity.ActivityInterface; import java.util.List; @ActivityInterface public interface OrderActivity { List getOrders(); } ================================================ FILE: springboot/src/main/java/io/temporal/samples/springboot/camel/OrderActivityImpl.java ================================================ package io.temporal.samples.springboot.camel; import io.temporal.spring.boot.ActivityImpl; import java.util.List; import org.apache.camel.ProducerTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component @ActivityImpl(taskQueues = "CamelSampleTaskQueue") public class OrderActivityImpl implements OrderActivity { @Autowired private ProducerTemplate producerTemplate; @Override public List getOrders() { producerTemplate.start(); List orders = producerTemplate.requestBody("direct:findAllOrders", null, List.class); producerTemplate.stop(); return orders; } } ================================================ FILE: springboot/src/main/java/io/temporal/samples/springboot/camel/OrderRepository.java ================================================ package io.temporal.samples.springboot.camel; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface OrderRepository extends JpaRepository {} ================================================ FILE: springboot/src/main/java/io/temporal/samples/springboot/camel/OrderWorkflow.java ================================================ package io.temporal.samples.springboot.camel; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; import java.util.List; @WorkflowInterface public interface OrderWorkflow { @WorkflowMethod public List start(); } ================================================ FILE: springboot/src/main/java/io/temporal/samples/springboot/camel/OrderWorkflowImpl.java ================================================ package io.temporal.samples.springboot.camel; import io.temporal.activity.ActivityOptions; import io.temporal.spring.boot.WorkflowImpl; import io.temporal.workflow.Workflow; import java.time.Duration; import java.util.List; @WorkflowImpl(taskQueues = "CamelSampleTaskQueue") public class OrderWorkflowImpl implements OrderWorkflow { private OrderActivity activity = Workflow.newActivityStub( OrderActivity.class, ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(2)).build()); @Override public List start() { return activity.getOrders(); } } ================================================ FILE: springboot/src/main/java/io/temporal/samples/springboot/camel/README.md ================================================ # SpringBoot Camel Sample 1. Start SpringBoot from main samples repo directory: ./gradlew :springboot:bootRun 2. In your browser navigate to: http://localhost:3030/orders This sample starts an Apache Camel route which starts our orders Workflow. The workflow starts an activity which starts Camel route to get all orders JPA. ================================================ FILE: springboot/src/main/java/io/temporal/samples/springboot/customize/CustomizeActivity.java ================================================ package io.temporal.samples.springboot.customize; import io.temporal.activity.ActivityInterface; @ActivityInterface public interface CustomizeActivity { String run(String input); } ================================================ FILE: springboot/src/main/java/io/temporal/samples/springboot/customize/CustomizeActivityImpl.java ================================================ package io.temporal.samples.springboot.customize; import io.temporal.spring.boot.ActivityImpl; import org.springframework.stereotype.Component; @Component @ActivityImpl(taskQueues = "CustomizeTaskQueue") public class CustomizeActivityImpl implements CustomizeActivity { @Override public String run(String input) { return "Completed as " + input + " activity!"; } } ================================================ FILE: springboot/src/main/java/io/temporal/samples/springboot/customize/CustomizeWorkflow.java ================================================ package io.temporal.samples.springboot.customize; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; @WorkflowInterface public interface CustomizeWorkflow { @WorkflowMethod String execute(); } ================================================ FILE: springboot/src/main/java/io/temporal/samples/springboot/customize/CustomizeWorkflowImpl.java ================================================ package io.temporal.samples.springboot.customize; import io.temporal.activity.ActivityOptions; import io.temporal.activity.LocalActivityOptions; import io.temporal.failure.ActivityFailure; import io.temporal.failure.TimeoutFailure; import io.temporal.spring.boot.WorkflowImpl; import io.temporal.workflow.Workflow; import java.time.Duration; import org.slf4j.Logger; /** * In our custom config we have set that worker polling on CustomizeTaskQueue to be a "local * activity worker", meaning it would not poll for activity tasks. For this sample we will try to * start an activity as "normal" activity which should time out, then invoke it again as local which * should be successful. * * @see io.temporal.samples.springboot.customize.TemporalOptionsConfig */ @WorkflowImpl(taskQueues = "CustomizeTaskQueue") public class CustomizeWorkflowImpl implements CustomizeWorkflow { private CustomizeActivity asNormalActivity = Workflow.newActivityStub( CustomizeActivity.class, ActivityOptions.newBuilder() .setStartToCloseTimeout(Duration.ofSeconds(2)) .setScheduleToCloseTimeout(Duration.ofSeconds(4)) .build()); private CustomizeActivity asLocalActivity = Workflow.newLocalActivityStub( CustomizeActivity.class, LocalActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(2)).build()); private Logger logger = Workflow.getLogger(CustomizeActivity.class.getName()); @Override public String execute() { try { return asNormalActivity.run("Normal"); } catch (ActivityFailure e) { // We should have TimeoutFailure as activity failure cause with StartToClose timeout type TimeoutFailure tf = (TimeoutFailure) e.getCause(); logger.warn("asNormalActivity failed with timeout type: " + tf.getTimeoutType()); } return asLocalActivity.run("Local"); } } ================================================ FILE: springboot/src/main/java/io/temporal/samples/springboot/customize/README.md ================================================ # SpringBoot Customize Options Sample This sample shows how to optimize default options such as * WorkflowServiceStubsOptions * WorkflowClientOption * WorkerFactoryOptions * WorkerOptions WorkerOptions can be optimized per worker/task queue. For this sample we set our specific worker to be "local activity worker" via custom options meaning it would not poll for activity tasks. Click on "Run Workflow" button to start instance of our sample workflow. This workflow will try to invoke our activity as "normal" activity which should time out on ScheduleToClose timeout, then we invoke this activity as local activity which should succeed. ## How to run 1. Start SpringBoot from main samples repo directory: ./gradlew :springboot:bootRun 2. In your browser navigate to: http://localhost:3030/customize 3. Press the "Run Workflow" button to start execution. You will see result show on page in 4 seconds ================================================ FILE: springboot/src/main/java/io/temporal/samples/springboot/customize/TemporalOptionsConfig.java ================================================ package io.temporal.samples.springboot.customize; import io.temporal.client.WorkflowClientOptions; import io.temporal.serviceclient.WorkflowServiceStubsOptions; import io.temporal.spring.boot.TemporalOptionsCustomizer; import io.temporal.spring.boot.WorkerOptionsCustomizer; import io.temporal.worker.WorkerFactoryOptions; import io.temporal.worker.WorkerOptions; import io.temporal.worker.WorkflowImplementationOptions; import javax.annotation.Nonnull; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class TemporalOptionsConfig { // Worker specific options customization @Bean public WorkerOptionsCustomizer customWorkerOptions() { return new WorkerOptionsCustomizer() { @Nonnull @Override public WorkerOptions.Builder customize( @Nonnull WorkerOptions.Builder optionsBuilder, @Nonnull String workerName, @Nonnull String taskQueue) { // For CustomizeTaskQueue (also name of worker) we set worker // to only handle workflow tasks and local activities if (taskQueue.equals("CustomizeTaskQueue")) { optionsBuilder.setLocalActivityWorkerOnly(true); } return optionsBuilder; } }; } // WorkflowServiceStubsOptions customization @Bean public TemporalOptionsCustomizer customServiceStubsOptions() { return new TemporalOptionsCustomizer() { @Nonnull @Override public WorkflowServiceStubsOptions.Builder customize( @Nonnull WorkflowServiceStubsOptions.Builder optionsBuilder) { // set options on optionsBuilder as needed // ... return optionsBuilder; } }; } // WorkflowClientOption customization @Bean public TemporalOptionsCustomizer customClientOptions() { return new TemporalOptionsCustomizer() { @Nonnull @Override public WorkflowClientOptions.Builder customize( @Nonnull WorkflowClientOptions.Builder optionsBuilder) { // set options on optionsBuilder as needed // ... return optionsBuilder; } }; } // WorkerFactoryOptions customization @Bean public TemporalOptionsCustomizer customWorkerFactoryOptions() { return new TemporalOptionsCustomizer() { @Nonnull @Override public WorkerFactoryOptions.Builder customize( @Nonnull WorkerFactoryOptions.Builder optionsBuilder) { // set options on optionsBuilder as needed // ... return optionsBuilder; } }; } // WorkflowImplementationOptions customization @Bean public TemporalOptionsCustomizer customWorkflowImplementationOptions() { return new TemporalOptionsCustomizer<>() { @Nonnull @Override public WorkflowImplementationOptions.Builder customize( @Nonnull WorkflowImplementationOptions.Builder optionsBuilder) { // set options on optionsBuilder such as per-activity options return optionsBuilder; } }; } } ================================================ FILE: springboot/src/main/java/io/temporal/samples/springboot/hello/HelloActivity.java ================================================ package io.temporal.samples.springboot.hello; import io.temporal.activity.ActivityInterface; import io.temporal.samples.springboot.hello.model.Person; @ActivityInterface public interface HelloActivity { String hello(Person person); } ================================================ FILE: springboot/src/main/java/io/temporal/samples/springboot/hello/HelloActivityImpl.java ================================================ package io.temporal.samples.springboot.hello; import io.temporal.samples.springboot.hello.model.Person; import io.temporal.spring.boot.ActivityImpl; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component @ActivityImpl(taskQueues = "HelloSampleTaskQueue") public class HelloActivityImpl implements HelloActivity { @Value("${samples.data.language}") private String language; @Override public String hello(Person person) { String greeting = language.equals("spanish") ? "Hola " : "Hello "; return greeting + person.getFirstName() + " " + person.getLastName() + "!"; } } ================================================ FILE: springboot/src/main/java/io/temporal/samples/springboot/hello/HelloWorkflow.java ================================================ package io.temporal.samples.springboot.hello; import io.temporal.samples.springboot.hello.model.Person; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; @WorkflowInterface public interface HelloWorkflow { @WorkflowMethod String sayHello(Person person); } ================================================ FILE: springboot/src/main/java/io/temporal/samples/springboot/hello/HelloWorkflowImpl.java ================================================ package io.temporal.samples.springboot.hello; import io.temporal.activity.ActivityOptions; import io.temporal.samples.springboot.hello.model.Person; import io.temporal.spring.boot.WorkflowImpl; import io.temporal.workflow.Workflow; import java.time.Duration; @WorkflowImpl(taskQueues = "HelloSampleTaskQueue") public class HelloWorkflowImpl implements HelloWorkflow { private HelloActivity activity = Workflow.newActivityStub( HelloActivity.class, ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(2)).build()); @Override public String sayHello(Person person) { return activity.hello(person); } } ================================================ FILE: springboot/src/main/java/io/temporal/samples/springboot/hello/README.md ================================================ # SpringBoot Hello Sample 1. Start SpringBoot from main samples repo directory: ./gradlew :springboot:bootRun 2. In your browser navigate to: http://localhost:3030/hello Enter in first and last name in the form then click on Run Workflow to start workflow execution. Page will be updated to show the workflow execution results (the greeting). You can try changing the language setting in [application.yaml](../../../../../../resources/application.yaml) file from "english" to "spanish" to get the greeting result in Spanish. ================================================ FILE: springboot/src/main/java/io/temporal/samples/springboot/hello/model/Person.java ================================================ package io.temporal.samples.springboot.hello.model; public class Person { private String firstName; private String lastName; public Person() {} public Person(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } } ================================================ FILE: springboot/src/main/java/io/temporal/samples/springboot/kafka/KafkaActivity.java ================================================ package io.temporal.samples.springboot.kafka; import io.temporal.activity.ActivityInterface; @ActivityInterface public interface KafkaActivity { void sendMessage(String message); } ================================================ FILE: springboot/src/main/java/io/temporal/samples/springboot/kafka/KafkaActivityImpl.java ================================================ package io.temporal.samples.springboot.kafka; import io.temporal.failure.ApplicationFailure; import io.temporal.spring.boot.ActivityImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.kafka.core.KafkaTemplate; import org.springframework.stereotype.Component; @Component @ActivityImpl(taskQueues = "KafkaSampleTaskQueue") public class KafkaActivityImpl implements KafkaActivity { // Setting required to false means we won't fail // if a test does not have kafka enabled @Autowired(required = false) private KafkaTemplate kafkaTemplate; @Value(value = "${samples.message.topic.name}") private String topicName; @Override public void sendMessage(String message) { try { kafkaTemplate.send(topicName, message).get(); } catch (Exception e) { throw ApplicationFailure.newFailure( "Unable to send message.", e.getClass().getName(), e.getMessage()); } } } ================================================ FILE: springboot/src/main/java/io/temporal/samples/springboot/kafka/KafkaConfig.java ================================================ package io.temporal.samples.springboot.kafka; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.apache.kafka.clients.admin.AdminClientConfig; import org.apache.kafka.clients.admin.NewTopic; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import org.springframework.kafka.annotation.KafkaListener; import org.springframework.kafka.core.KafkaAdmin; import org.springframework.kafka.test.EmbeddedKafkaBroker; import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; @Configuration() @Profile("!test") public class KafkaConfig { @Value(value = "${spring.kafka.bootstrap-servers}") private String bootstrapAddress; @Value(value = "${samples.message.topic.name}") private String topicName; @Autowired private MessageController messageController; @Bean EmbeddedKafkaBroker broker() { return new EmbeddedKafkaBroker(1) .kafkaPorts(9092) .brokerListProperty("spring.kafka.bootstrap-servers"); } @Bean public KafkaAdmin kafkaAdmin() { Map configs = new HashMap<>(); configs.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapAddress); return new KafkaAdmin(configs); } @Bean public NewTopic samplesTopic() { return new NewTopic(topicName, 1, (short) 1); } @KafkaListener(id = "samples-topic", topics = "samples-topic") public void kafkaListener(String message) { SseEmitter latestEm = messageController.getLatestEmitter(); try { latestEm.send(message); } catch (IOException e) { latestEm.completeWithError(e); } } } ================================================ FILE: springboot/src/main/java/io/temporal/samples/springboot/kafka/MessageController.java ================================================ package io.temporal.samples.springboot.kafka; import java.util.ArrayList; import java.util.List; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; @RestController public class MessageController { private final List emitters = new ArrayList<>(); @GetMapping("/kafka-messages") public SseEmitter getKafkaMessages() { SseEmitter emitter = new SseEmitter(60 * 1000L); emitters.add(emitter); emitter.onCompletion(() -> emitters.remove(emitter)); emitter.onTimeout(() -> emitters.remove(emitter)); return emitter; } public List getEmitters() { return emitters; } public SseEmitter getLatestEmitter() { return emitters.isEmpty() ? null : emitters.get(emitters.size() - 1); } } ================================================ FILE: springboot/src/main/java/io/temporal/samples/springboot/kafka/MessageWorkflow.java ================================================ package io.temporal.samples.springboot.kafka; import io.temporal.workflow.SignalMethod; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; @WorkflowInterface public interface MessageWorkflow { @WorkflowMethod void start(); @SignalMethod void update(String message); } ================================================ FILE: springboot/src/main/java/io/temporal/samples/springboot/kafka/MessageWorkflowImpl.java ================================================ package io.temporal.samples.springboot.kafka; import io.temporal.activity.ActivityOptions; import io.temporal.spring.boot.WorkflowImpl; import io.temporal.workflow.Workflow; import java.time.Duration; @WorkflowImpl(taskQueues = "KafkaSampleTaskQueue") public class MessageWorkflowImpl implements MessageWorkflow { private KafkaActivity activity = Workflow.newActivityStub( KafkaActivity.class, ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(2)).build()); private String message = null; @Override public void start() { Workflow.await(() -> message != null); // simulate some steps / milestones activity.sendMessage( "Starting execution: " + Workflow.getInfo().getWorkflowId() + " with message: " + message); activity.sendMessage("Step 1 done..."); activity.sendMessage("Step 2 done..."); activity.sendMessage("Step 3 done..."); activity.sendMessage("Completing execution: " + Workflow.getInfo().getWorkflowId()); } @Override public void update(String message) { this.message = message; } } ================================================ FILE: springboot/src/main/java/io/temporal/samples/springboot/kafka/README.md ================================================ # SpringBoot Kafka Request / Reply Sample 1. Start SpringBoot from main samples repo directory: ./gradlew :springboot:bootRun 2. In your browser navigate to: http://localhost:3030/kafka ## Use Case When you start adopting Temporal in your existing applications it can very often become a much better replacement to any queueing techs like Kafka. Even tho we can replace big parts of our unreliable architecture with Temporal often it's not a complete replacement and we still have services that produce messages/events to Kafka topics and workflow results need to be pushed to Kafka in order to be consumed by these existing services. In this sample we show how messages sent to Kafka topics can trigger workflow execution as well as how via activities we can produce messages to Kafka topics that can be consumed by other existing services you might have. ## How to use Enter a message you want to set to Kafka topic. Message consumer when it receives it will start a workflow execution and deliver message to it as signal. Workflow execution performs some sample steps. For each step it executes an activity which uses Kafka producer to send message to Kafka topic. In the UI we listen on this kafka topic and you will see all messages produced by activities show up dynamically as they are happening. ## Note We use embedded (in-memory) Kafka to make it easier to run this sample. You should not use this in your applications outside of tests. ================================================ FILE: springboot/src/main/java/io/temporal/samples/springboot/metrics/README.md ================================================ # SpringBoot Metrics Sample 1. Start SpringBoot from main samples repo directory: ./gradlew :springboot:bootRun 2. In your browser navigate to: http://localhost:3030/metrics This sample involves just SpringBoot and Actuator configurations which are included in the samples already. The page shows information on how to set up SDK metrics in your SpringBoot applications. ================================================ FILE: springboot/src/main/java/io/temporal/samples/springboot/update/ProductNotAvailableForAmountException.java ================================================ package io.temporal.samples.springboot.update; public class ProductNotAvailableForAmountException extends Exception { public ProductNotAvailableForAmountException(String message) { super(message); } } ================================================ FILE: springboot/src/main/java/io/temporal/samples/springboot/update/PurchaseActivities.java ================================================ package io.temporal.samples.springboot.update; import io.temporal.activity.ActivityInterface; import io.temporal.samples.springboot.update.model.Purchase; @ActivityInterface public interface PurchaseActivities { boolean isProductInStockForPurchase(Purchase purchase); boolean makePurchase(Purchase purchase); } ================================================ FILE: springboot/src/main/java/io/temporal/samples/springboot/update/PurchaseActivitiesImpl.java ================================================ package io.temporal.samples.springboot.update; import io.temporal.samples.springboot.update.model.Product; import io.temporal.samples.springboot.update.model.ProductRepository; import io.temporal.samples.springboot.update.model.Purchase; import io.temporal.spring.boot.ActivityImpl; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component @ActivityImpl(taskQueues = "UpdateSampleTaskQueue") public class PurchaseActivitiesImpl implements PurchaseActivities { @Autowired ProductRepository productRepository; @Override public boolean isProductInStockForPurchase(Purchase purchase) { Product product = getProductFor(purchase); return product != null && product.getStock() >= purchase.getAmount(); } @Override public boolean makePurchase(Purchase purchase) { Product product = getProductFor(purchase); if (product != null) { product.setStock(product.getStock() - purchase.getAmount()); productRepository.save(product); return true; } return false; } private Product getProductFor(Purchase purchase) { Optional productOptional = productRepository.findById(purchase.getProduct()); if (productOptional.isPresent()) { return productOptional.get(); } return null; } } ================================================ FILE: springboot/src/main/java/io/temporal/samples/springboot/update/PurchaseWorkflow.java ================================================ package io.temporal.samples.springboot.update; import io.temporal.samples.springboot.update.model.Purchase; import io.temporal.workflow.*; @WorkflowInterface public interface PurchaseWorkflow { @WorkflowMethod void start(); @UpdateMethod boolean makePurchase(Purchase purchase); @UpdateValidatorMethod(updateName = "makePurchase") void makePurchaseValidator(Purchase purchase); @SignalMethod void exit(); } ================================================ FILE: springboot/src/main/java/io/temporal/samples/springboot/update/PurchaseWorkflowImpl.java ================================================ package io.temporal.samples.springboot.update; import io.temporal.activity.LocalActivityOptions; import io.temporal.failure.ApplicationFailure; import io.temporal.samples.springboot.update.model.Purchase; import io.temporal.spring.boot.WorkflowImpl; import io.temporal.workflow.Workflow; import java.time.Duration; @WorkflowImpl(taskQueues = "UpdateSampleTaskQueue") public class PurchaseWorkflowImpl implements PurchaseWorkflow { private boolean newPurchase = false; private boolean exit = false; private PurchaseActivities activities = Workflow.newLocalActivityStub( PurchaseActivities.class, LocalActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(2)).build()); @Override public void start() { // for sake of sample we only wait for a single purchase or exit signal Workflow.await(() -> newPurchase || exit); } @Override public boolean makePurchase(Purchase purchase) { if (!activities.isProductInStockForPurchase(purchase)) { throw ApplicationFailure.newFailure( "Product " + purchase.getProduct() + " is not in stock for amount " + purchase.getAmount(), ProductNotAvailableForAmountException.class.getName(), purchase); } return activities.makePurchase(purchase); } @Override public void makePurchaseValidator(Purchase purchase) { // Not allowed to change workflow state inside validator // So invocations of (local) activities is prohibited // We can validate the purchase with some business logic here // Assume we have some max inventory amount for single item set to 100 if (purchase == null || (purchase.getAmount() < 0 || purchase.getAmount() > 100)) { throw new IllegalArgumentException( "Invalid Product or amount (Product id:" + purchase.getProduct() + ", amount" + purchase.getAmount() + ")"); } } @Override public void exit() { this.exit = true; } } ================================================ FILE: springboot/src/main/java/io/temporal/samples/springboot/update/README.md ================================================ # SpringBoot Synchronous Update Sample 1. Start SpringBoot from main samples repo directory: ./gradlew :springboot:bootRun 2. In your browser navigate to: http://localhost:3030/update Pick one of the fishing items you want to purchase from the inventory drop down list. Next pick the amount of this item you want to purchase. The inventory is presented in the table below the form. For each item you can see the current availble stock count. Try first picking an item and then an amount that is less or equal to the items in inventory. You will see that the purchase goes through and the inventory table is updated dynamically. Now try to pick and item and amount that is greater than what's in our inventory. You will see that the update fails and you see the "Unable to perform purchase" message that shows the underlying "ProductNotAvailableForAmountException" exception raised in the update handler. Updating our inventory is done via local activities. The check if item and amount of the fishing item you want to purchase is in inventory is also done by local activity. ## Note Make sure that you enable the synchronous update feature on your Temporal cluster. This can be done in dynamic config with frontend.enableUpdateWorkflowExecution: - value: true If you don't have this enabled you will see error shown when you try to make any purchase. ================================================ FILE: springboot/src/main/java/io/temporal/samples/springboot/update/ResourceNotFoundException.java ================================================ package io.temporal.samples.springboot.update; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(value = HttpStatus.NOT_FOUND) public class ResourceNotFoundException extends Exception { public ResourceNotFoundException(String message) { super(message); } } ================================================ FILE: springboot/src/main/java/io/temporal/samples/springboot/update/model/Product.java ================================================ package io.temporal.samples.springboot.update.model; import javax.persistence.*; @Entity public class Product { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column(nullable = false) public String name; @Column(nullable = false) public String code; @Column(nullable = false) public String description; @Column(nullable = false) public int price = 0; @Column(nullable = false) private int stock = 20; public Product() {} public Product(Integer id, String name, String code, String description, int price, int stock) { this.id = id; this.name = name; this.code = code; this.description = description; this.price = price; this.stock = stock; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public int getStock() { return stock; } public void setStock(int stock) { this.stock = stock; } public boolean removeStock() { if (this.stock > 0) { this.stock--; return true; } else { return false; } } public boolean removeStock(int value) { if (this.stock > 0) { this.stock -= value; return true; } else { return false; } } public void addStock() { this.stock++; } public void addStock(int value) { this.stock += value; } } ================================================ FILE: springboot/src/main/java/io/temporal/samples/springboot/update/model/ProductRepository.java ================================================ package io.temporal.samples.springboot.update.model; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface ProductRepository extends JpaRepository {} ================================================ FILE: springboot/src/main/java/io/temporal/samples/springboot/update/model/Purchase.java ================================================ package io.temporal.samples.springboot.update.model; public class Purchase { int product; int amount; public Purchase() {} public Purchase(int product, int amount) { this.product = product; this.amount = amount; } public int getProduct() { return product; } public void setProduct(int product) { this.product = product; } public int getAmount() { return amount; } public void setAmount(int amount) { this.amount = amount; } } ================================================ FILE: springboot/src/main/resources/application-tc.yaml ================================================ spring.temporal: namespace: # https://docs.temporal.io/cloud/#temporal-cloud-namespace-id connection: target: .tmprl.cloud:7233 mtls: key-file: /path/to/key.key cert-chain-file: /path/to/cert.pem # more configuration options https://github.com/temporalio/sdk-java/tree/master/temporal-spring-boot-autoconfigure#mtls ================================================ FILE: springboot/src/main/resources/application.yaml ================================================ server: port: 3030 spring: main: allow-bean-definition-overriding: true application: name: temporal-samples # temporal specific configs temporal: namespace: default connection: target: 127.0.0.1:7233 # (Note following configuration are not set by default but serve more as reference) # workers: # - task-queue: DemoTaskQueue # capacity: # max-concurrent-workflow-task-pollers: 6 # max-concurrent-activity-task-pollers: 6 # rate-limits: # max-worker-activities-per-second: 3 # max-task-queue-activities-per-second: 3 # workflow-cache: # max-instances: 10 # max-threads: 10 workersAutoDiscovery: packages: io.temporal.samples.springboot # data source config for some samples that need it datasource: url: jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false; username: sa password: pass driver-class-name: org.h2.Driver jpa: database-platform: org.hibernate.dialect.H2Dialect hibernate: ddl-auto: create-drop defer-datasource-initialization: true ## enable h2 console (h2-console endpoint) for debugging h2: console: enabled: true ## kafka setup for samples kafka: consumer: auto-offset-reset: earliest bootstrap-servers: localhost:9092 # actuator (sdk metrics) management: endpoints: web: exposure: include: prometheus,temporalworkerinfo # specific for samples samples: data: language: english message: topic: name: samples-topic group: name: samples-group ================================================ FILE: springboot/src/main/resources/data.sql ================================================ INSERT INTO product(name, code, description, price, stock) VALUES ('Zoom U-Tale Worm', 'w1', 'The U-Tale Worms are another one of Zooms truly-impressive big bass baits.', 5, 20); INSERT INTO product(name, code, description, price, stock) VALUES ('Yamamoto Baits 5" Senko', 'w2', 'Yamamoto Baits 5" Senko has become a mainstay for bass throughout the United States.', 7, 15); INSERT INTO product(name, code, description, price, stock) VALUES ('Rapala Original Floating Minnow', 'w3', 'The Rapala Original Floating Minnow is the lure that started it all and is still one of the most popular lures around.', 10, 10); INSERT INTO product(name, code, description, price, stock) VALUES ('Z-Man Jackhammer', 'w4', 'Exclusive patented ChatterBait bladed swim jig design and stainless hex-shaped ChatterBlade.', 18, 10); INSERT INTO product(name, code, description, price, stock) VALUES ('Roboworm Straight Tail Worm Bait', 'w5', 'Roboworms are the most consistant poured baits on the market.', 9, 30); INSERT INTO officeorder(number, date, desc, price) VALUES ('OR1', '1/02/2004', 'Office Chair', 120); INSERT INTO officeorder(number, date, desc, price) VALUES ('OR2', '1/05/2004', 'Office Desk', 200); INSERT INTO officeorder(number, date, desc, price) VALUES ('OR3', '1/05/2004', 'Computer Mouse', 30); INSERT INTO officeorder(number, date, desc, price) VALUES ('OR4', '1/08/2004', 'Mouse Pad', 19); INSERT INTO officeorder(number, date, desc, price) VALUES ('OR5', '1/10/2004', 'Office Sofa', 170); INSERT INTO officeorder(number, date, desc, price) VALUES ('OR6', '1/12/2004', 'MacBook Air', 980); INSERT INTO officeorder(number, date, desc, price) VALUES ('OR7', '1/12/2004', 'Pens', 9); INSERT INTO officeorder(number, date, desc, price) VALUES ('OR8', '1/12/2004', 'Printer Paper', 22); INSERT INTO officeorder(number, date, desc, price) VALUES ('OR9', '1/15/2004', 'Printer Cartridge', 110); ================================================ FILE: springboot/src/main/resources/static/js/jquery.sse.js ================================================ /* * jQuery Plugin for Server-Sent Events (SSE) EventSource Polyfill v0.1.3 * https://github.com/byjg/jquery-sse * * This document is licensed as free software under the terms of the * MIT License: http://www.opensource.org/licenses/mit-license.php * * Copyright (c) 2015 by JG (João Gilberto Magalhães). */ (function ($) { $.extend({ SSE: function (url, customSettings) { var sse = {instance: null, type: null}; var settings = { onOpen: function (e) { }, onEnd: function (e) { }, onError: function (e) { }, onMessage: function (e) { }, options: {}, headers: {}, events: {} }; $.extend(settings, customSettings); sse._url = url; sse._settings = settings; // Start the proper EventSource object or Ajax fallback sse._start = sse.start; sse.start = function () { if (this.instance) { return false; } if (!window.EventSource || this._settings.options.forceAjax || (Object.keys(this._settings.headers).length > 0)) { createAjax(this); } else { createEventSource(this); } return true; }; // Stop the proper object sse.stop = function () { if (!this.instance) { return false; } if (!window.EventSource || this._settings.options.forceAjax || (Object.keys(this._settings.headers).length > 0)) { // Nothing to do; } else { this.instance.close(); } this._settings.onEnd(); this.instance = null; this.type = null; return true; }; return sse; } }); // Private Method for Handle EventSource object function createEventSource(me) { me.type = 'event'; me.instance = new EventSource(me._url); me.instance.successCount = 0; me.instance.onmessage = me._settings.onMessage; me.instance.onopen = function (e) { if (me.instance.successCount++ === 0) { me._settings.onOpen(e); } }; me.instance.onerror = function (e) { if (e.target.readyState === EventSource.CLOSED) { me._settings.onError(e); } }; for (var key in me._settings.events) { me.instance.addEventListener(key, me._settings.events[key], false); } } // Handle the Ajax instance (fallback) function createAjax(me) { me.type = 'ajax'; me.instance = {successCount: 0, id: null, retry: 3000, data: "", event: ""}; runAjax(me); } // Handle the continous Ajax request (fallback) function runAjax(me) { if (!me.instance) { return; } var headers = {'Last-Event-ID': me.instance.id}; $.extend(headers, me._settings.headers); $.ajax({ url: me._url, method: 'GET', headers: headers, success: function (receivedData, status, info) { if (!me.instance) { return; } if (me.instance.successCount++ === 0) { me._settings.onOpen(); } var lines = receivedData.split("\n"); // Process the return to generate a compatible SSE response me.instance.data = ""; var countBreakLine = 0; for (var key in lines) { var separatorPos = lines[key].indexOf(":"); var item = [ lines[key].substr(0, separatorPos), lines[key].substr(separatorPos + 1) ]; switch (item[0]) { // If the first part is empty, needed to check another sequence case "": if (!item[1] && countBreakLine++ === 1) { // Avoid comments! eventMessage = { data: me.instance.data, lastEventId: me.instance.id, origin: 'http://' + info.getResponseHeader('Host'), returnValue: true }; // If there are a custom event then call it if (me.instance.event && me._settings.events[me.instance.event]) { me._settings.events[me.instance.event](eventMessage); } else { me._settings.onMessage(eventMessage); } me.instance.data = ""; me.instance.event = ""; countBreakLine = 0; } break; // Define the new retry object; case "retry": countBreakLine = 0; me.instance.retry = parseInt(item[1].trim()); break; // Define the new ID case "id": countBreakLine = 0; me.instance.id = item[1].trim(); break; // Define a custom event case "event": countBreakLine = 0; me.instance.event = item[1].trim(); break; // Define the data to be processed. case "data": countBreakLine = 0; me.instance.data += (me.instance.data !== "" ? "\n" : "") + item[1].trim(); break; default: countBreakLine = 0; } } setTimeout(function () { runAjax(me); }, me.instance.retry); }, error: me._settings.onError }); } })(jQuery); ================================================ FILE: springboot/src/main/resources/static/js/samplessse.js ================================================ $( document ).ready(function() { var sse = $.SSE('/kafka-messages', { onMessage: function(e){ console.log(e); $('#kafka-messages tr:last').after(''+e.data+''); }, onError: function(e){ sse.stop(); console.log("Could not connect..Stopping SSE"); }, onEnd: function(e){ console.log("End"); } }); sse.start(); }); ================================================ FILE: springboot/src/main/resources/templates/actuator.html ================================================

Temporal Java SDK Samples

In this sample we show how to create a custom Actuator Endpoint showing Worker Info.


Spring Actuator allows us to create custom endpoints. This sample shows how to create a Worker Info custom endpoint that shows registered Workflow and Activity impls per task queue.

View the custom endpoint at localhost:3030/actuator/temporalworkerinfo
================================================ FILE: springboot/src/main/resources/templates/camel.html ================================================

Temporal Java SDK Samples

This sample shows how to start Workflow execution from an Apache Camel Route



Apache Camel is an integration framework with a large number of out-of box integrations with many different apis. In this sample we show how to integrate Temporal as part of a Camel Route which define steps of messages from its source to destination. It allows you to bring numerous advantages of Temporal such as high reliability and fault tolerance into your existing Camel applications.

To run the sample navigate to localhost:3030/orders
This endpoint starts a Camel Route which in turn starts our Workflow executipn and delivers results.

================================================ FILE: springboot/src/main/resources/templates/customize.html ================================================

Temporal Java SDK Samples

This sample shows how to optimize default options such as
  • WorkflowServiceStubsOptions
  • WorkflowClientOption
  • WorkerFactoryOptions
  • WorkerOptions

WorkerOptions can be optimized per worker/task queue. For this sample we set our specific worker to be "local activity worker" via custom options meaning it would not poll for activity tasks. Click on "Run Workflow" button to start instance of our sample workflow. This workflow will try to invoke activity as "normal" activity which should timeout on the set ScheduleToClose timeout, we handle this activity failure and then invoke this activity as local activity which should succeed and update the workflow execution result on the page.



Workflow result:
================================================ FILE: springboot/src/main/resources/templates/fragments.html ================================================ ================================================ FILE: springboot/src/main/resources/templates/hello.html ================================================

Temporal Java SDK Samples

This is a simple greeting example. Enter persons first and last name then submit form to start workflow execution. Results will be updated on the page.



Say hello to:

First Name:

Last Name:

Workflow result:
================================================ FILE: springboot/src/main/resources/templates/index.html ================================================ ================================================ FILE: springboot/src/main/resources/templates/kafka.html ================================================

Temporal Java SDK Samples

This sample shows how we can trigger and signal workflow executions by sending messages to Kafka topic. It also shows how workflows can send updates and result to Kafka for other services to consume.
Enter a message in the form and submit. This will trigger a workflow and the messages it sends to Kafka are shown on the page dynamically.



Message:

Kafka Messages:
================================================ FILE: springboot/src/main/resources/templates/metrics.html ================================================
================================================ FILE: springboot/src/main/resources/templates/update.html ================================================

Temporal Java SDK Samples

This sample shows use of Synchronous Update feature. The page shows a form used to make a purchase.
Under the form you can see the total inventory of our fishing items. Inventory has a pre-set stock (number of each item available). Once you make a purchase our workflow is sent an update, meaning we want to make the purchase and respond back when its done.
The workflow update validator checks if the given amount of an item is still available in the inventory.
If it is then the update goes through and the inventory table is dynamically updated. If not then the update is rejected and shown on the screen.

Purchase Form

Select product:





Inventory

Id Name Description Price ($) Stock (Available)
Id Name Description Price Stock
================================================ FILE: springboot/src/test/java/io/temporal/samples/springboot/CamelSampleTest.java ================================================ package io.temporal.samples.springboot; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.samples.springboot.camel.OfficeOrder; import io.temporal.samples.springboot.camel.OrderWorkflow; import io.temporal.testing.TestWorkflowEnvironment; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.test.context.ActiveProfiles; import org.springframework.util.Assert; @SpringBootTest(classes = HelloSampleTest.Configuration.class) @ActiveProfiles("test") @TestInstance(TestInstance.Lifecycle.PER_CLASS) // set this to omit setting up embedded kafka @EnableAutoConfiguration(exclude = {KafkaAutoConfiguration.class}) public class CamelSampleTest { @Autowired ConfigurableApplicationContext applicationContext; @Autowired TestWorkflowEnvironment testWorkflowEnvironment; @Autowired WorkflowClient workflowClient; @BeforeEach void setUp() { applicationContext.start(); } @Test public void testOrdersWorkflow() { OrderWorkflow workflow = workflowClient.newWorkflowStub( OrderWorkflow.class, WorkflowOptions.newBuilder() .setTaskQueue("CamelSampleTaskQueue") .setWorkflowId("CamelSampleWorkflow") .build()); List result = workflow.start(); Assert.notNull(result, "Result should not be null"); Assert.isTrue(result.size() == 9, "Invalid result"); } } ================================================ FILE: springboot/src/test/java/io/temporal/samples/springboot/CustomizeSampleTest.java ================================================ package io.temporal.samples.springboot; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.samples.springboot.customize.CustomizeWorkflow; import io.temporal.testing.TestWorkflowEnvironment; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.ComponentScan; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ActiveProfiles; import org.springframework.util.Assert; @SpringBootTest(classes = CustomizeSampleTest.Configuration.class) @ActiveProfiles("test") @TestInstance(TestInstance.Lifecycle.PER_CLASS) // set this to omit setting up embedded kafka @EnableAutoConfiguration(exclude = {KafkaAutoConfiguration.class}) @DirtiesContext public class CustomizeSampleTest { @Autowired ConfigurableApplicationContext applicationContext; @Autowired TestWorkflowEnvironment testWorkflowEnvironment; @Autowired WorkflowClient workflowClient; @BeforeEach void setUp() { applicationContext.start(); } @Test public void testHello() { CustomizeWorkflow workflow = workflowClient.newWorkflowStub( CustomizeWorkflow.class, WorkflowOptions.newBuilder() .setTaskQueue("CustomizeTaskQueue") .setWorkflowId("CustomizeSampleTest") .build()); String result = workflow.execute(); Assert.notNull(result, "Result should not be null"); Assert.isTrue(result.equals("Completed as Local activity!"), "Invalid result"); } @ComponentScan public static class Configuration {} } ================================================ FILE: springboot/src/test/java/io/temporal/samples/springboot/HelloSampleTest.java ================================================ package io.temporal.samples.springboot; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.samples.springboot.hello.HelloWorkflow; import io.temporal.samples.springboot.hello.model.Person; import io.temporal.testing.TestWorkflowEnvironment; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.ComponentScan; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ActiveProfiles; import org.springframework.util.Assert; @SpringBootTest(classes = HelloSampleTest.Configuration.class) @ActiveProfiles("test") @TestInstance(TestInstance.Lifecycle.PER_CLASS) // set this to omit setting up embedded kafka @EnableAutoConfiguration(exclude = {KafkaAutoConfiguration.class}) @DirtiesContext public class HelloSampleTest { @Autowired ConfigurableApplicationContext applicationContext; @Autowired TestWorkflowEnvironment testWorkflowEnvironment; @Autowired WorkflowClient workflowClient; @BeforeEach void setUp() { applicationContext.start(); } @Test public void testHello() { HelloWorkflow workflow = workflowClient.newWorkflowStub( HelloWorkflow.class, WorkflowOptions.newBuilder() .setTaskQueue("HelloSampleTaskQueue") .setWorkflowId("HelloSampleTest") .build()); String result = workflow.sayHello(new Person("Temporal", "User")); Assert.notNull(result, "Greeting should not be null"); Assert.isTrue(result.equals("Hello Temporal User!"), "Invalid result"); } @ComponentScan public static class Configuration {} } ================================================ FILE: springboot/src/test/java/io/temporal/samples/springboot/HelloSampleTestMockedActivity.java ================================================ package io.temporal.samples.springboot; import static org.mockito.ArgumentMatchers.any; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.samples.springboot.hello.HelloActivity; import io.temporal.samples.springboot.hello.HelloActivityImpl; import io.temporal.samples.springboot.hello.HelloWorkflow; import io.temporal.samples.springboot.hello.model.Person; import io.temporal.testing.TestWorkflowEnvironment; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Primary; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ActiveProfiles; import org.springframework.util.Assert; @SpringBootTest(classes = HelloSampleTestMockedActivity.Configuration.class) @ActiveProfiles("test") @TestInstance(TestInstance.Lifecycle.PER_CLASS) // set this to omit setting up embedded kafka @EnableAutoConfiguration(exclude = {KafkaAutoConfiguration.class}) @DirtiesContext public class HelloSampleTestMockedActivity { @Autowired ConfigurableApplicationContext applicationContext; @Autowired TestWorkflowEnvironment testWorkflowEnvironment; @Autowired WorkflowClient workflowClient; @Captor ArgumentCaptor personArgumentCaptor; @Autowired HelloActivity activity; @BeforeEach void setUp() { applicationContext.start(); } @Test public void testHello() { HelloWorkflow workflow = workflowClient.newWorkflowStub( HelloWorkflow.class, WorkflowOptions.newBuilder() .setTaskQueue("HelloSampleTaskQueue") .setWorkflowId("HelloSampleTest") .build()); String result = workflow.sayHello(new Person("Temporal", "User")); Assert.notNull(result, "Greeting should not be null"); Assert.isTrue(result.equals("Hello from mocked activity"), "Invalid result"); Mockito.verify(activity, Mockito.times(1)).hello(personArgumentCaptor.capture()); Assert.notNull(personArgumentCaptor.getValue(), "Invalid input"); Assert.isTrue( personArgumentCaptor.getValue().getFirstName().equals("Temporal"), "Invalid person first name"); Assert.isTrue( personArgumentCaptor.getValue().getLastName().equals("User"), "invalid person last name"); } @ComponentScan public static class Configuration { @MockBean private HelloActivityImpl helloActivityMock; @Bean @Primary public HelloActivity getTestActivityImpl() { Mockito.when(helloActivityMock.hello(any())).thenReturn("Hello from mocked activity"); return helloActivityMock; } } } ================================================ FILE: springboot/src/test/java/io/temporal/samples/springboot/KafkaConsumerTestHelper.java ================================================ package io.temporal.samples.springboot; import java.util.concurrent.CountDownLatch; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.springframework.kafka.annotation.KafkaListener; import org.springframework.stereotype.Component; @Component public class KafkaConsumerTestHelper { private CountDownLatch latch = new CountDownLatch(5); private String payload = null; @KafkaListener(id = "samples-test-id", topics = "${samples.message.topic.name}") public void receive(ConsumerRecord consumerRecord) { setPayload(consumerRecord.toString()); latch.countDown(); } public CountDownLatch getLatch() { return latch; } public String getPayload() { return payload; } private void setPayload(String payload) { this.payload = payload; } } ================================================ FILE: springboot/src/test/java/io/temporal/samples/springboot/KafkaSampleTest.java ================================================ package io.temporal.samples.springboot; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.client.WorkflowStub; import io.temporal.samples.springboot.kafka.MessageWorkflow; import io.temporal.testing.TestWorkflowEnvironment; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.ComponentScan; import org.springframework.kafka.test.context.EmbeddedKafka; import org.springframework.test.annotation.DirtiesContext; import org.springframework.util.Assert; @SpringBootTest(classes = KafkaSampleTest.Configuration.class) @TestInstance(TestInstance.Lifecycle.PER_CLASS) @EmbeddedKafka( partitions = 1, bootstrapServersProperty = "spring.kafka.bootstrap-servers", controlledShutdown = true) @DirtiesContext public class KafkaSampleTest { @Autowired ConfigurableApplicationContext applicationContext; @Autowired TestWorkflowEnvironment testWorkflowEnvironment; @Autowired WorkflowClient workflowClient; @Autowired KafkaConsumerTestHelper consumer; @BeforeEach void setUp() { applicationContext.start(); } @Test public void testKafkaWorflow() throws Exception { MessageWorkflow workflow = workflowClient.newWorkflowStub( MessageWorkflow.class, WorkflowOptions.newBuilder() .setTaskQueue("KafkaSampleTaskQueue") .setWorkflowId("NewMessageWorkflow") .build()); WorkflowClient.start(workflow::start); workflow.update("This is a test message"); WorkflowStub.fromTyped(workflow).getResult(Void.class); consumer.getLatch().await(); Assert.isTrue(consumer.getLatch().getCount() == 0L, "Invalid latch count"); Assert.isTrue( consumer.getPayload().contains("Completing execution: NewMessageWorkflow"), "Invalid last event payload"); } @ComponentScan public static class Configuration {} } ================================================ FILE: springboot/src/test/java/io/temporal/samples/springboot/UpdateSampleTest.java ================================================ package io.temporal.samples.springboot; import static org.junit.jupiter.api.Assertions.assertThrows; import io.temporal.client.*; import io.temporal.samples.springboot.update.PurchaseWorkflow; import io.temporal.samples.springboot.update.model.Purchase; import io.temporal.testing.TestWorkflowEnvironment; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.ComponentScan; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ActiveProfiles; @SpringBootTest(classes = HelloSampleTest.Configuration.class) @ActiveProfiles("test") @TestInstance(TestInstance.Lifecycle.PER_CLASS) // set this to omit setting up embedded kafka @EnableAutoConfiguration(exclude = {KafkaAutoConfiguration.class}) @DirtiesContext public class UpdateSampleTest { @Autowired ConfigurableApplicationContext applicationContext; @Autowired TestWorkflowEnvironment testWorkflowEnvironment; @Autowired WorkflowClient workflowClient; @BeforeEach void setUp() { applicationContext.start(); } @Test public void testUpdate() { PurchaseWorkflow workflow = workflowClient.newWorkflowStub( PurchaseWorkflow.class, WorkflowOptions.newBuilder() .setTaskQueue("UpdateSampleTaskQueue") .setWorkflowId("NewPurchase") .build()); Purchase purchase = new Purchase(1, 3); WorkflowClient.start(workflow::start); // send update workflow.makePurchase(purchase); workflow.exit(); WorkflowStub.fromTyped(workflow).getResult(Void.class); } @Test() public void testUpdateRejected() { PurchaseWorkflow workflow = workflowClient.newWorkflowStub( PurchaseWorkflow.class, WorkflowOptions.newBuilder() .setTaskQueue("UpdateSampleTaskQueue") .setWorkflowId("NewPurchase") .build()); Purchase purchase = new Purchase(1, 40); WorkflowClient.start(workflow::start); // send update assertThrows( WorkflowUpdateException.class, () -> { workflow.makePurchase(purchase); }); workflow.exit(); WorkflowStub.fromTyped(workflow).getResult(Void.class); } @ComponentScan public static class Configuration {} } ================================================ FILE: springboot/src/test/resources/application.yaml ================================================ server: port: 3030 spring: main: allow-bean-definition-overriding: true application: name: temporal-samples # temporal specific configs temporal: connection: target: 127.0.0.1:7233 target.namespace: default workersAutoDiscovery: packages: io.temporal.samples.springboot # enable test server for testing test-server: enabled: true ignore-duplicate-definitions: true # data source config for tests that need it datasource: url: jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;DB_CLOSE_ON_EXIT=FALSE; username: sa password: pass driver-class-name: org.h2.Driver jpa: database-platform: org.hibernate.dialect.H2Dialect hibernate: ddl-auto: create-drop defer-datasource-initialization: true ## kafka setup for samples kafka: consumer: auto-offset-reset: earliest bootstrap-servers: ${spring.embedded.kafka.brokers} # specific for samples samples: data: language: english message: topic: name: samples-test-topic group: name: samples-group ================================================ FILE: springboot/src/test/resources/data.sql ================================================ INSERT INTO product(name, code, description, price, stock) VALUES ('Zoom U-Tale Worm', 'w1', 'The U-Tale Worms are another one of Zooms truly-impressive big bass baits.', 5, 20); INSERT INTO product(name, code, description, price, stock) VALUES ('Yamamoto Baits 5" Senko', 'w2', 'Yamamoto Baits 5" Senko has become a mainstay for bass throughout the United States.', 7, 15); INSERT INTO product(name, code, description, price, stock) VALUES ('Rapala Original Floating Minnow', 'w3', 'The Rapala Original Floating Minnow is the lure that started it all and is still one of the most popular lures around.', 10, 10); INSERT INTO product(name, code, description, price, stock) VALUES ('Z-Man Jackhammer', 'w4', 'Exclusive patented ChatterBait bladed swim jig design and stainless hex-shaped ChatterBlade.', 18, 10); INSERT INTO product(name, code, description, price, stock) VALUES ('Roboworm Straight Tail Worm Bait', 'w5', 'Roboworms are the most consistant poured baits on the market.', 9, 30); ================================================ FILE: springboot-basic/build.gradle ================================================ apply plugin: 'org.springframework.boot' dependencies { implementation "org.springframework.boot:spring-boot-starter-web" implementation "org.springframework.boot:spring-boot-starter-thymeleaf" implementation "org.springframework.boot:spring-boot-starter-actuator" implementation "io.temporal:temporal-spring-boot-starter:$javaSDKVersion" testImplementation "org.springframework.boot:spring-boot-starter-test" runtimeOnly "io.micrometer:micrometer-registry-prometheus" dependencies { errorproneJavac('com.google.errorprone:javac:9+181-r4173-1') errorprone('com.google.errorprone:error_prone_core:2.28.0') } } bootJar { enabled = false } jar { enabled = true } ================================================ FILE: springboot-basic/src/main/java/io/temporal/samples/springboot/SamplesController.java ================================================ package io.temporal.samples.springboot; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.samples.springboot.hello.HelloWorkflow; import io.temporal.samples.springboot.hello.model.Person; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; @Controller public class SamplesController { @Autowired WorkflowClient client; @GetMapping("/hello") public String hello(Model model) { model.addAttribute("sample", "Say Hello"); return "hello"; } @PostMapping( value = "/hello", consumes = {MediaType.APPLICATION_JSON_VALUE}, produces = {MediaType.TEXT_HTML_VALUE}) ResponseEntity helloSample(@RequestBody Person person) { HelloWorkflow workflow = client.newWorkflowStub( HelloWorkflow.class, WorkflowOptions.newBuilder() .setTaskQueue("HelloSampleTaskQueue") .setWorkflowId("HelloSample") .build()); // bypass thymeleaf, don't return template name just result return new ResponseEntity<>("\"" + workflow.sayHello(person) + "\"", HttpStatus.OK); } } ================================================ FILE: springboot-basic/src/main/java/io/temporal/samples/springboot/TemporalSpringbootSamplesApplication.java ================================================ package io.temporal.samples.springboot; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class TemporalSpringbootSamplesApplication { public static void main(String[] args) { SpringApplication.run(TemporalSpringbootSamplesApplication.class, args).start(); } } ================================================ FILE: springboot-basic/src/main/java/io/temporal/samples/springboot/hello/HelloActivity.java ================================================ package io.temporal.samples.springboot.hello; import io.temporal.activity.ActivityInterface; import io.temporal.samples.springboot.hello.model.Person; @ActivityInterface public interface HelloActivity { String hello(Person person); } ================================================ FILE: springboot-basic/src/main/java/io/temporal/samples/springboot/hello/HelloActivityImpl.java ================================================ package io.temporal.samples.springboot.hello; import io.temporal.samples.springboot.hello.model.Person; import io.temporal.spring.boot.ActivityImpl; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component @ActivityImpl(taskQueues = "HelloSampleTaskQueue") public class HelloActivityImpl implements HelloActivity { @Value("${samples.data.language}") private String language; @Override public String hello(Person person) { String greeting = language.equals("spanish") ? "Hola " : "Hello "; return greeting + person.getFirstName() + " " + person.getLastName() + "!"; } } ================================================ FILE: springboot-basic/src/main/java/io/temporal/samples/springboot/hello/HelloWorkflow.java ================================================ package io.temporal.samples.springboot.hello; import io.temporal.samples.springboot.hello.model.Person; import io.temporal.workflow.WorkflowInterface; import io.temporal.workflow.WorkflowMethod; @WorkflowInterface public interface HelloWorkflow { @WorkflowMethod String sayHello(Person person); } ================================================ FILE: springboot-basic/src/main/java/io/temporal/samples/springboot/hello/HelloWorkflowImpl.java ================================================ package io.temporal.samples.springboot.hello; import io.temporal.activity.ActivityOptions; import io.temporal.samples.springboot.hello.model.Person; import io.temporal.spring.boot.WorkflowImpl; import io.temporal.workflow.Workflow; import java.time.Duration; @WorkflowImpl(taskQueues = "HelloSampleTaskQueue") public class HelloWorkflowImpl implements HelloWorkflow { private HelloActivity activity = Workflow.newActivityStub( HelloActivity.class, ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(2)).build()); @Override public String sayHello(Person person) { return activity.hello(person); } } ================================================ FILE: springboot-basic/src/main/java/io/temporal/samples/springboot/hello/README.md ================================================ # SpringBoot Hello Sample 1. Start SpringBoot from main samples repo directory: ./gradlew :springboot-basic:bootRun 2. In your browser navigate to: http://localhost:3030/hello Enter in first and last name in the form then click on Run Workflow to start workflow execution. Page will be updated to show the workflow execution results (the greeting). You can try changing the language setting in [application.yaml](../../../../../../resources/application.yaml) file from "english" to "spanish" to get the greeting result in Spanish. ================================================ FILE: springboot-basic/src/main/java/io/temporal/samples/springboot/hello/model/Person.java ================================================ package io.temporal.samples.springboot.hello.model; public class Person { private String firstName; private String lastName; public Person() {} public Person(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } } ================================================ FILE: springboot-basic/src/main/resources/application-tc.yaml ================================================ spring.temporal: namespace: # https://docs.temporal.io/cloud/#temporal-cloud-namespace-id connection: target: .tmprl.cloud:7233 mtls: key-file: /path/to/key.key cert-chain-file: /path/to/cert.pem # more configuration options https://github.com/temporalio/sdk-java/tree/master/temporal-spring-boot-autoconfigure#mtls ================================================ FILE: springboot-basic/src/main/resources/application.yaml ================================================ server: port: 3030 spring: main: allow-bean-definition-overriding: true application: name: temporal-samples # temporal specific configs temporal: namespace: default connection: target: 127.0.0.1:7233 workersAutoDiscovery: packages: io.temporal.samples.springboot # specific for samples samples: data: language: english ================================================ FILE: springboot-basic/src/main/resources/static/js/jquery.sse.js ================================================ /* * jQuery Plugin for Server-Sent Events (SSE) EventSource Polyfill v0.1.3 * https://github.com/byjg/jquery-sse * * This document is licensed as free software under the terms of the * MIT License: http://www.opensource.org/licenses/mit-license.php * * Copyright (c) 2015 by JG (João Gilberto Magalhães). */ (function ($) { $.extend({ SSE: function (url, customSettings) { var sse = {instance: null, type: null}; var settings = { onOpen: function (e) { }, onEnd: function (e) { }, onError: function (e) { }, onMessage: function (e) { }, options: {}, headers: {}, events: {} }; $.extend(settings, customSettings); sse._url = url; sse._settings = settings; // Start the proper EventSource object or Ajax fallback sse._start = sse.start; sse.start = function () { if (this.instance) { return false; } if (!window.EventSource || this._settings.options.forceAjax || (Object.keys(this._settings.headers).length > 0)) { createAjax(this); } else { createEventSource(this); } return true; }; // Stop the proper object sse.stop = function () { if (!this.instance) { return false; } if (!window.EventSource || this._settings.options.forceAjax || (Object.keys(this._settings.headers).length > 0)) { // Nothing to do; } else { this.instance.close(); } this._settings.onEnd(); this.instance = null; this.type = null; return true; }; return sse; } }); // Private Method for Handle EventSource object function createEventSource(me) { me.type = 'event'; me.instance = new EventSource(me._url); me.instance.successCount = 0; me.instance.onmessage = me._settings.onMessage; me.instance.onopen = function (e) { if (me.instance.successCount++ === 0) { me._settings.onOpen(e); } }; me.instance.onerror = function (e) { if (e.target.readyState === EventSource.CLOSED) { me._settings.onError(e); } }; for (var key in me._settings.events) { me.instance.addEventListener(key, me._settings.events[key], false); } } // Handle the Ajax instance (fallback) function createAjax(me) { me.type = 'ajax'; me.instance = {successCount: 0, id: null, retry: 3000, data: "", event: ""}; runAjax(me); } // Handle the continous Ajax request (fallback) function runAjax(me) { if (!me.instance) { return; } var headers = {'Last-Event-ID': me.instance.id}; $.extend(headers, me._settings.headers); $.ajax({ url: me._url, method: 'GET', headers: headers, success: function (receivedData, status, info) { if (!me.instance) { return; } if (me.instance.successCount++ === 0) { me._settings.onOpen(); } var lines = receivedData.split("\n"); // Process the return to generate a compatible SSE response me.instance.data = ""; var countBreakLine = 0; for (var key in lines) { var separatorPos = lines[key].indexOf(":"); var item = [ lines[key].substr(0, separatorPos), lines[key].substr(separatorPos + 1) ]; switch (item[0]) { // If the first part is empty, needed to check another sequence case "": if (!item[1] && countBreakLine++ === 1) { // Avoid comments! eventMessage = { data: me.instance.data, lastEventId: me.instance.id, origin: 'http://' + info.getResponseHeader('Host'), returnValue: true }; // If there are a custom event then call it if (me.instance.event && me._settings.events[me.instance.event]) { me._settings.events[me.instance.event](eventMessage); } else { me._settings.onMessage(eventMessage); } me.instance.data = ""; me.instance.event = ""; countBreakLine = 0; } break; // Define the new retry object; case "retry": countBreakLine = 0; me.instance.retry = parseInt(item[1].trim()); break; // Define the new ID case "id": countBreakLine = 0; me.instance.id = item[1].trim(); break; // Define a custom event case "event": countBreakLine = 0; me.instance.event = item[1].trim(); break; // Define the data to be processed. case "data": countBreakLine = 0; me.instance.data += (me.instance.data !== "" ? "\n" : "") + item[1].trim(); break; default: countBreakLine = 0; } } setTimeout(function () { runAjax(me); }, me.instance.retry); }, error: me._settings.onError }); } })(jQuery); ================================================ FILE: springboot-basic/src/main/resources/static/js/samplessse.js ================================================ $( document ).ready(function() { var sse = $.SSE('/kafka-messages', { onMessage: function(e){ console.log(e); $('#kafka-messages tr:last').after(''+e.data+''); }, onError: function(e){ sse.stop(); console.log("Could not connect..Stopping SSE"); }, onEnd: function(e){ console.log("End"); } }); sse.start(); }); ================================================ FILE: springboot-basic/src/main/resources/templates/fragments.html ================================================ ================================================ FILE: springboot-basic/src/main/resources/templates/hello.html ================================================

Temporal Java SDK Samples

This is a simple greeting example. Enter persons first and last name then submit form to start workflow execution. Results will be updated on the page.



Say hello to:

First Name:

Last Name:

Workflow result:
================================================ FILE: springboot-basic/src/main/resources/templates/index.html ================================================
Temporal Java SDK Samples

Click on sample link to run it.

================================================ FILE: springboot-basic/src/test/java/io/temporal/samples/springboot/HelloSampleTest.java ================================================ package io.temporal.samples.springboot; import io.temporal.client.WorkflowClient; import io.temporal.client.WorkflowOptions; import io.temporal.samples.springboot.hello.HelloWorkflow; import io.temporal.samples.springboot.hello.model.Person; import io.temporal.testing.TestWorkflowEnvironment; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.ComponentScan; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ActiveProfiles; import org.springframework.util.Assert; @SpringBootTest(classes = HelloSampleTest.Configuration.class) @ActiveProfiles("test") @TestInstance(TestInstance.Lifecycle.PER_CLASS) @DirtiesContext public class HelloSampleTest { @Autowired ConfigurableApplicationContext applicationContext; @Autowired TestWorkflowEnvironment testWorkflowEnvironment; @Autowired WorkflowClient workflowClient; @BeforeEach void setUp() { applicationContext.start(); } @Test public void testHello() { HelloWorkflow workflow = workflowClient.newWorkflowStub( HelloWorkflow.class, WorkflowOptions.newBuilder() .setTaskQueue("HelloSampleTaskQueue") .setWorkflowId("HelloSampleTest") .build()); String result = workflow.sayHello(new Person("Temporal", "User")); Assert.notNull(result, "Greeting should not be null"); Assert.isTrue(result.equals("Hello Temporal User!"), "Invalid result"); } @ComponentScan public static class Configuration {} } ================================================ FILE: springboot-basic/src/test/resources/application.yaml ================================================ server: port: 3030 spring: main: allow-bean-definition-overriding: true application: name: temporal-samples # temporal specific configs temporal: connection: target: 127.0.0.1:7233 target.namespace: default workersAutoDiscovery: packages: io.temporal.samples.springboot # enable test server for testing test-server: enabled: true # specific for samples samples: data: language: english