Merge pull request #3865 from kaibocai/kaibocai/update-workflow

Fix worflow examples for java
This commit is contained in:
Hannah Hunter 2023-11-13 18:16:41 -05:00 committed by GitHub
commit 4f0c2d1b76
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 88 additions and 87 deletions

View File

@ -109,21 +109,53 @@ catch (TaskFailedException) // Task failures are surfaced as TaskFailedException
<!--java--> <!--java-->
```java ```java
public static void main(String[] args) throws InterruptedException { public class ChainWorkflow extends Workflow {
DaprWorkflowClient client = new DaprWorkflowClient(); @Override
public WorkflowStub create() {
try (client) { return ctx -> {
client.raiseEvent(instanceId, "TestEvent", "TestEventPayload"); StringBuilder sb = new StringBuilder();
String wfInput = ctx.getInput(String.class);
System.out.println(separatorStr); String result1 = ctx.callActivity("Step1", wfInput, String.class).await();
System.out.println("** Registering parallel Events to be captured by allOf(t1,t2,t3) **"); String result2 = ctx.callActivity("Step2", result1, String.class).await();
client.raiseEvent(instanceId, "event1", "TestEvent 1 Payload"); String result3 = ctx.callActivity("Step3", result2, String.class).await();
client.raiseEvent(instanceId, "event2", "TestEvent 2 Payload"); String result = sb.append(result1).append(',').append(result2).append(',').append(result3).toString();
client.raiseEvent(instanceId, "event3", "TestEvent 3 Payload"); ctx.complete(result);
System.out.printf("Events raised for workflow with instanceId: %s\n", instanceId); };
} }
} }
class Step1 implements WorkflowActivity {
@Override
public Object run(WorkflowActivityContext ctx) {
Logger logger = LoggerFactory.getLogger(Step1.class);
logger.info("Starting Activity: " + ctx.getName());
// Do some work
return null;
}
}
class Step2 implements WorkflowActivity {
@Override
public Object run(WorkflowActivityContext ctx) {
Logger logger = LoggerFactory.getLogger(Step2.class);
logger.info("Starting Activity: " + ctx.getName());
// Do some work
return null;
}
}
class Step3 implements WorkflowActivity {
@Override
public Object run(WorkflowActivityContext ctx) {
Logger logger = LoggerFactory.getLogger(Step3.class);
logger.info("Starting Activity: " + ctx.getName());
// Do some work
return null;
}
}
``` ```
{{% /codetab %}} {{% /codetab %}}
@ -225,45 +257,22 @@ await context.CallActivityAsync("PostResults", sum);
<!--java--> <!--java-->
```java ```java
public static void main(String[] args) throws InterruptedException { public class FaninoutWorkflow extends Workflow {
DaprWorkflowClient client = new DaprWorkflowClient(); @Override
public WorkflowStub create() {
try (client) { return ctx -> {
// Get a list of N work items to process in parallel.
System.out.println(separatorStr); Object[] workBatch = ctx.callActivity("GetWorkBatch", Object[].class).await();
System.out.println("**SendExternalMessage**"); // Schedule the parallel tasks, but don't wait for them to complete yet.
client.raiseEvent(instanceId, "TestEvent", "TestEventPayload"); List<Task<Integer>> tasks = Arrays.stream(workBatch)
.map(workItem -> ctx.callActivity("ProcessWorkItem", workItem, int.class))
// Get events to process in parallel .collect(Collectors.toList());
System.out.println(separatorStr); // Everything is scheduled. Wait here until all parallel tasks have completed.
System.out.println("** Registering parallel Events to be captured by allOf(t1,t2,t3) **"); List<Integer> results = ctx.allOf(tasks).await();
client.raiseEvent(instanceId, "event1", "TestEvent 1 Payload"); // Aggregate all N outputs and publish the result.
client.raiseEvent(instanceId, "event2", "TestEvent 2 Payload"); int sum = results.stream().mapToInt(Integer::intValue).sum();
client.raiseEvent(instanceId, "event3", "TestEvent 3 Payload"); ctx.complete(sum);
System.out.printf("Events raised for workflow with instanceId: %s\n", instanceId); };
// Register the raised events to be captured
System.out.println(separatorStr);
System.out.println("** Registering Event to be captured by anyOf(t1,t2,t3) **");
client.raiseEvent(instanceId, "e2", "event 2 Payload");
System.out.printf("Event raised for workflow with instanceId: %s\n", instanceId);
// Wait for all tasks to complete and aggregate results
System.out.println(separatorStr);
System.out.println("**WaitForInstanceCompletion**");
try {
WorkflowInstanceStatus waitForInstanceCompletionResult =
client.waitForInstanceCompletion(instanceId, Duration.ofSeconds(60), true);
System.out.printf("Result: %s%n", waitForInstanceCompletionResult);
} catch (TimeoutException ex) {
System.out.printf("waitForInstanceCompletion has an exception:%s%n", ex);
}
System.out.println(separatorStr);
System.out.println("**purgeInstance**");
boolean purgeResult = client.purgeInstance(instanceId);
System.out.printf("purgeResult: %s%n", purgeResult);
} }
} }
``` ```
@ -640,42 +649,34 @@ public override async Task<OrderResult> RunAsync(WorkflowContext context, OrderP
<!--java--> <!--java-->
```java ```java
public static void main(String[] args) throws InterruptedException { public class ExternalSystemInteractionWorkflow extends Workflow {
DaprWorkflowClient client = new DaprWorkflowClient(); @Override
public WorkflowStub create() {
try (client) { return ctx -> {
String eventInstanceId = client.scheduleNewWorkflow(DemoWorkflow.class); // ...other steps...
System.out.printf("Started new workflow instance with random ID: %s%n", eventInstanceId); Integer orderCost = ctx.getInput(int.class);
client.raiseEvent(eventInstanceId, "TestException", null); // Require orders over a certain threshold to be approved
System.out.printf("Event raised for workflow with instanceId: %s\n", eventInstanceId); if (orderCost > ORDER_APPROVAL_THRESHOLD) {
try {
System.out.println(separatorStr); // Request human approval for this order
String instanceToTerminateId = "terminateMe"; ctx.callActivity("RequestApprovalActivity", orderCost, Void.class).await();
client.scheduleNewWorkflow(DemoWorkflow.class, null, instanceToTerminateId); // Pause and wait for a human to approve the order
System.out.printf("Started new workflow instance with specified ID: %s%n", instanceToTerminateId); boolean approved = ctx.waitForExternalEvent("ManagerApproval", Duration.ofDays(3), boolean.class).await();
if (!approved) {
TimeUnit.SECONDS.sleep(5); // The order was rejected, end the workflow here
System.out.println("Terminate this workflow instance manually before the timeout is reached"); ctx.complete("Process reject");
client.terminateWorkflow(instanceToTerminateId, null);
System.out.println(separatorStr);
String restartingInstanceId = "restarting";
client.scheduleNewWorkflow(DemoWorkflow.class, null, restartingInstanceId);
System.out.printf("Started new workflow instance with ID: %s%n", restartingInstanceId);
System.out.println("Sleeping 30 seconds to restart the workflow");
TimeUnit.SECONDS.sleep(30);
System.out.println("**SendExternalMessage: RestartEvent**");
client.raiseEvent(restartingInstanceId, "RestartEvent", "RestartEventPayload");
System.out.println("Sleeping 30 seconds to terminate the eternal workflow");
TimeUnit.SECONDS.sleep(30);
client.terminateWorkflow(restartingInstanceId, null);
} }
} catch (TaskCanceledException e) {
// An approval timeout results in automatic order cancellation
ctx.complete("Process cancel");
}
}
// ...other steps...
System.out.println("Exiting DemoWorkflowClient."); // End the workflow with a success result
System.exit(0); ctx.complete("Process approved");
};
}
} }
``` ```