diff --git a/api/pom.xml b/api/pom.xml index 429313935..55bb6964c 100644 --- a/api/pom.xml +++ b/api/pom.xml @@ -11,10 +11,7 @@ Open Workflow :: API jar Java SDK for Open Workflow Specification - - 3.6.2 - - + org.openworkflow.sdk @@ -102,7 +99,6 @@ org.codehaus.mojo build-helper-maven-plugin - ${version.build-helper-maven-plugin} add-mixin diff --git a/api/src/main/java/org/openworkflow/sdk/api/ObjectMapperFactory.java b/api/src/main/java/org/openworkflow/sdk/api/ObjectMapperFactory.java index 82922112a..36a8f038d 100644 --- a/api/src/main/java/org/openworkflow/sdk/api/ObjectMapperFactory.java +++ b/api/src/main/java/org/openworkflow/sdk/api/ObjectMapperFactory.java @@ -66,10 +66,9 @@ private static > T configu .disable(SerializationFeature.FAIL_ON_EMPTY_BEANS) .disable(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES) .addModule(validationModule) - .changeDefaultPropertyInclusion( - v -> - v.withValueInclusion(JsonInclude.Include.NON_NULL) - .withContentInclusion(JsonInclude.Include.NON_NULL)) + .changeDefaultPropertyInclusion(v -> + v.withValueInclusion(JsonInclude.Include.NON_NULL) + .withContentInclusion(JsonInclude.Include.NON_NULL)) .addModule(new JacksonMixInModule()) .findAndAddModules(); } diff --git a/fluent/spec/src/main/java/org/openworkflow/sdk/fluent/spec/BaseWorkflowBuilder.java b/fluent/spec/src/main/java/org/openworkflow/sdk/fluent/spec/BaseWorkflowBuilder.java index cc55e4b3a..fac13e771 100644 --- a/fluent/spec/src/main/java/org/openworkflow/sdk/fluent/spec/BaseWorkflowBuilder.java +++ b/fluent/spec/src/main/java/org/openworkflow/sdk/fluent/spec/BaseWorkflowBuilder.java @@ -102,10 +102,9 @@ public final SELF use(Consumer... configurers) { private SELF use(List> configurers) { final UseBuilder builder = new UseBuilder(); - configurers.forEach( - c -> { - if (c != null) c.accept(builder); - }); + configurers.forEach(c -> { + if (c != null) c.accept(builder); + }); this.workflow.setUse(builder.build()); return self(); } diff --git a/fluent/spec/src/main/java/org/openworkflow/sdk/fluent/spec/dsl/AbstractEventFilterSpec.java b/fluent/spec/src/main/java/org/openworkflow/sdk/fluent/spec/dsl/AbstractEventFilterSpec.java index df23b92d0..2f3524fda 100644 --- a/fluent/spec/src/main/java/org/openworkflow/sdk/fluent/spec/dsl/AbstractEventFilterSpec.java +++ b/fluent/spec/src/main/java/org/openworkflow/sdk/fluent/spec/dsl/AbstractEventFilterSpec.java @@ -50,10 +50,9 @@ public SELF correlate( @Override public void accept(EVENT_FILTER filterBuilder) { - filterBuilder.with( - pb -> { - getPropertySteps().forEach(step -> step.accept(pb)); - }); + filterBuilder.with(pb -> { + getPropertySteps().forEach(step -> step.accept(pb)); + }); filterSteps.forEach(step -> step.accept(filterBuilder)); } diff --git a/fluent/spec/src/main/java/org/openworkflow/sdk/fluent/spec/dsl/CallHttpSpec.java b/fluent/spec/src/main/java/org/openworkflow/sdk/fluent/spec/dsl/CallHttpSpec.java index 40fbd6ea8..960ffa521 100644 --- a/fluent/spec/src/main/java/org/openworkflow/sdk/fluent/spec/dsl/CallHttpSpec.java +++ b/fluent/spec/src/main/java/org/openworkflow/sdk/fluent/spec/dsl/CallHttpSpec.java @@ -47,15 +47,14 @@ public void accept(CallHttpTaskBuilder builder) { @Override public CallHttpSpec andThen(Consumer after) { Objects.requireNonNull(after, "after"); - steps.add( - fluent -> { - if (!(fluent instanceof CallHttpTaskBuilder builder)) { - throw new IllegalArgumentException( - "andThen requires CallHttpTaskBuilder, got: " - + (fluent == null ? "null" : fluent.getClass().getName())); - } - after.accept(builder); - }); + steps.add(fluent -> { + if (!(fluent instanceof CallHttpTaskBuilder builder)) { + throw new IllegalArgumentException( + "andThen requires CallHttpTaskBuilder, got: " + + (fluent == null ? "null" : fluent.getClass().getName())); + } + after.accept(builder); + }); return this; } } diff --git a/fluent/spec/src/main/java/org/openworkflow/sdk/fluent/spec/dsl/DSL.java b/fluent/spec/src/main/java/org/openworkflow/sdk/fluent/spec/dsl/DSL.java index d0795dfb4..12a9fad36 100644 --- a/fluent/spec/src/main/java/org/openworkflow/sdk/fluent/spec/dsl/DSL.java +++ b/fluent/spec/src/main/java/org/openworkflow/sdk/fluent/spec/dsl/DSL.java @@ -432,11 +432,8 @@ public static AuthenticationConfigurer oidc( String clientId, String clientSecret) { return a -> - a.openIDConnect( - o -> - o.authority(authority) - .grant(grant) - .client(c -> c.id(clientId).secret(clientSecret))); + a.openIDConnect(o -> + o.authority(authority).grant(grant).client(c -> c.id(clientId).secret(clientSecret))); } public static AuthenticationConfigurer oidc(String secret) { @@ -472,11 +469,8 @@ public static AuthenticationConfigurer oauth2( String clientId, String clientSecret) { return a -> - a.openIDConnect( - o -> - o.authority(authority) - .grant(grant) - .client(c -> c.id(clientId).secret(clientSecret))); + a.openIDConnect(o -> + o.authority(authority).grant(grant).client(c -> c.id(clientId).secret(clientSecret))); } public static AuthenticationConfigurer oauth2(String secret) { @@ -514,11 +508,10 @@ public static AuthenticationConfigurer oauth2( String clientSecret, Consumer endpoints) { return a -> - a.oauth2( - o -> { - o.authority(authority).grant(grant).client(c -> c.id(clientId).secret(clientSecret)); - o.endpoints(endpoints); - }); + a.oauth2(o -> { + o.authority(authority).grant(grant).client(c -> c.id(clientId).secret(clientSecret)); + o.endpoints(endpoints); + }); } /** diff --git a/fluent/spec/src/main/java/org/openworkflow/sdk/fluent/spec/dsl/RaiseSpec.java b/fluent/spec/src/main/java/org/openworkflow/sdk/fluent/spec/dsl/RaiseSpec.java index 6bf81532a..4d92b402b 100644 --- a/fluent/spec/src/main/java/org/openworkflow/sdk/fluent/spec/dsl/RaiseSpec.java +++ b/fluent/spec/src/main/java/org/openworkflow/sdk/fluent/spec/dsl/RaiseSpec.java @@ -58,9 +58,8 @@ public RaiseSpec then(Consumer step) { @Override public void accept(RaiseTaskBuilder b) { - b.error( - err -> { - for (var s : steps) s.accept(err); - }); + b.error(err -> { + for (var s : steps) s.accept(err); + }); } } diff --git a/fluent/spec/src/test/java/org/openworkflow/sdk/fluent/spec/TaskItemDefaultNamingTest.java b/fluent/spec/src/test/java/org/openworkflow/sdk/fluent/spec/TaskItemDefaultNamingTest.java index 6ba2f08d9..eb67ad01e 100644 --- a/fluent/spec/src/test/java/org/openworkflow/sdk/fluent/spec/TaskItemDefaultNamingTest.java +++ b/fluent/spec/src/test/java/org/openworkflow/sdk/fluent/spec/TaskItemDefaultNamingTest.java @@ -69,16 +69,14 @@ void testTopLevelDoListAutoNaming() { void testNestedTryCatchTaskAutoNaming() { Workflow wf = WorkflowBuilder.workflow("flowAutoNameTryCatch") - .tasks( - d -> - d.tryCatch( - null, - t -> - t.tryHandler( - tb -> - tb.set(null, s -> s.expr("$.start = true")) - .http(null, http().get().endpoint("http://test")) - .set(null, s -> s.expr("$.end = true"))))) + .tasks(d -> + d.tryCatch( + null, + t -> + t.tryHandler(tb -> + tb.set(null, s -> s.expr("$.start = true")) + .http(null, http().get().endpoint("http://test")) + .set(null, s -> s.expr("$.end = true"))))) .build(); List topItems = wf.getDo(); @@ -102,18 +100,16 @@ void testNestedTryCatchTaskAutoNaming() { void testNestedForEachTaskAutoNaming() { Workflow wf = WorkflowBuilder.workflow("flowAutoNameForEach") - .tasks( - d -> - d.forEach( - null, - f -> - f.each("item") - .in("$.list") - // Define tasks to be executed for each item in the forEach loop - .tasks( - tb -> - tb.http(null, http().post().endpoint("http://test")) - .set(null, s -> s.expr("$.processed = true"))))) + .tasks(d -> + d.forEach( + null, + f -> + f.each("item") + .in("$.list") + // Define tasks to be executed for each item in the forEach loop + .tasks(tb -> + tb.http(null, http().post().endpoint("http://test")) + .set(null, s -> s.expr("$.processed = true"))))) .build(); List topItems = wf.getDo(); @@ -150,16 +146,14 @@ void testWaitTaskAutoNamingAndDuration() { void testNestedForkTaskAutoNaming() { Workflow wf = WorkflowBuilder.workflow("flowAutoNameFork") - .tasks( - d -> - d.fork( - null, - f -> - f.branches( - b -> - b.set(null, s -> s.expr("$.a = 1")) - .set(null, s -> s.expr("$.a = 2")) - .http(null, http().get().endpoint("http://b"))))) + .tasks(d -> + d.fork( + null, + f -> + f.branches(b -> + b.set(null, s -> s.expr("$.a = 1")) + .set(null, s -> s.expr("$.a = 2")) + .http(null, http().get().endpoint("http://b"))))) .build(); List topItems = wf.getDo(); @@ -186,25 +180,21 @@ void testDeterministicNamingAcrossInstances() { // Build the first workflow instance Workflow wf1 = WorkflowBuilder.workflow("workflowOne") - .tasks( - d -> - d.set(null, s -> s.expr("$.a = 1")) - .http(null, http().get().endpoint("http://example.com")) - .emit("customEmit", e -> e.event(ev -> ev.type("test"))) - .tryCatch( - null, t -> t.tryHandler(tb -> tb.set(null, s -> s.expr("$.b = 2"))))) + .tasks(d -> + d.set(null, s -> s.expr("$.a = 1")) + .http(null, http().get().endpoint("http://example.com")) + .emit("customEmit", e -> e.event(ev -> ev.type("test"))) + .tryCatch(null, t -> t.tryHandler(tb -> tb.set(null, s -> s.expr("$.b = 2"))))) .build(); // Build the second workflow instance with the exact same task structure Workflow wf2 = WorkflowBuilder.workflow("workflowTwo") - .tasks( - d -> - d.set(null, s -> s.expr("$.a = 1")) - .http(null, http().get().endpoint("http://example.com")) - .emit("customEmit", e -> e.event(ev -> ev.type("test"))) - .tryCatch( - null, t -> t.tryHandler(tb -> tb.set(null, s -> s.expr("$.b = 2"))))) + .tasks(d -> + d.set(null, s -> s.expr("$.a = 1")) + .http(null, http().get().endpoint("http://example.com")) + .emit("customEmit", e -> e.event(ev -> ev.type("test"))) + .tryCatch(null, t -> t.tryHandler(tb -> tb.set(null, s -> s.expr("$.b = 2"))))) .build(); List tasks1 = wf1.getDo(); @@ -235,15 +225,12 @@ void testMultipleTasksAppendsMaintainOffset() { Workflow wf = WorkflowBuilder.workflow("flowMultipleAppends") // First invocation: list is empty, offset is 0 - .tasks( - d -> - d.set(null, s -> s.expr("$.a = 1")) - .http(null, http().get().endpoint("http://a"))) + .tasks(d -> + d.set(null, s -> s.expr("$.a = 1")).http(null, http().get().endpoint("http://a"))) // Second invocation: list has 2 items, offset passed to builder should be 2 - .tasks( - d -> - d.set(null, s -> s.expr("$.b = 2")) - .emit("", e -> e.event(ev -> ev.type("test.event")))) + .tasks(d -> + d.set(null, s -> s.expr("$.b = 2")) + .emit("", e -> e.event(ev -> ev.type("test.event")))) .build(); List items = wf.getDo(); @@ -263,17 +250,16 @@ void testMultipleTasksAppendsMaintainOffset() { void testForkTaskMultipleBranchesAppends() { Workflow wf = WorkflowBuilder.workflow("flowForkMultipleAppends") - .tasks( - d -> - d.fork( - null, - f -> - // 1. First call: list is empty, offset is 0 - f.branches(b -> b.set(null, s -> s.expr("$.a = 1"))) - // 2. Second call: list has 1 item, offset should be 1 - .branches(b -> b.set(null, s -> s.expr("$.b = 2"))) - // 3. Third call: list has 2 items, offset should be 2 - .branches(b -> b.http(null, http().get().endpoint("http://test"))))) + .tasks(d -> + d.fork( + null, + f -> + // 1. First call: list is empty, offset is 0 + f.branches(b -> b.set(null, s -> s.expr("$.a = 1"))) + // 2. Second call: list has 1 item, offset should be 1 + .branches(b -> b.set(null, s -> s.expr("$.b = 2"))) + // 3. Third call: list has 2 items, offset should be 2 + .branches(b -> b.http(null, http().get().endpoint("http://test"))))) .build(); List topItems = wf.getDo(); @@ -298,19 +284,18 @@ void testForkTaskMultipleBranchesAppends() { void testForEachTaskMultipleTasksAppends() { Workflow wf = WorkflowBuilder.workflow("flowForMultipleAppends") - .tasks( - d -> - d.forEach( - null, - f -> - f.each("item") - .in("$.list") - // 1. First call: list is empty, offset is 0 - .tasks(tb -> tb.set(null, s -> s.expr("$.a = 1"))) - // 2. Second call: list has 1 item, offset should be 1 - .tasks(tb -> tb.set(null, s -> s.expr("$.b = 2"))) - // 3. Third call: list has 2 items, offset should be 2 - .tasks(tb -> tb.http(null, http().get().endpoint("http://test"))))) + .tasks(d -> + d.forEach( + null, + f -> + f.each("item") + .in("$.list") + // 1. First call: list is empty, offset is 0 + .tasks(tb -> tb.set(null, s -> s.expr("$.a = 1"))) + // 2. Second call: list has 1 item, offset should be 1 + .tasks(tb -> tb.set(null, s -> s.expr("$.b = 2"))) + // 3. Third call: list has 2 items, offset should be 2 + .tasks(tb -> tb.http(null, http().get().endpoint("http://test"))))) .build(); List topItems = wf.getDo(); @@ -363,24 +348,19 @@ void testSubscriptionIteratorMultipleTasksAppends() { void testTryCatchMultipleTasksAppends() { Workflow wf = WorkflowBuilder.workflow("flowTryCatchMultipleAppends") - .tasks( - d -> - d.tryCatch( - null, - t -> - // Multiple tryHandler calls - t.tryHandler(tb -> tb.set(null, s -> s.expr("$.a = 1"))) - .tryHandler(tb -> tb.set(null, s -> s.expr("$.b = 2"))) - .catchHandler( - c -> - c.errorsWith(eb -> eb.type("CustomError")) - // Multiple doTasks calls inside the catch - .doTasks(cb -> cb.set(null, s -> s.expr("$.c = 3"))) - .doTasks( - cb -> - cb.http( - null, - http().get().endpoint("http://test")))))) + .tasks(d -> + d.tryCatch( + null, + t -> + // Multiple tryHandler calls + t.tryHandler(tb -> tb.set(null, s -> s.expr("$.a = 1"))) + .tryHandler(tb -> tb.set(null, s -> s.expr("$.b = 2"))) + .catchHandler(c -> + c.errorsWith(eb -> eb.type("CustomError")) + // Multiple doTasks calls inside the catch + .doTasks(cb -> cb.set(null, s -> s.expr("$.c = 3"))) + .doTasks(cb -> + cb.http(null, http().get().endpoint("http://test")))))) .build(); List topItems = wf.getDo(); @@ -412,22 +392,17 @@ void testTryCatchMultipleTasksAppends() { void testListenTaskSubscriptionIteratorMultipleTasksAppends() { Workflow wf = WorkflowBuilder.workflow("flowListenMultipleAppends") - .tasks( - d -> - d.listen( - null, // Auto-names the listen task - l -> - l.forEach( - sub -> - // 1. First call: list is empty, offset is 0 - sub.tasks(tb -> tb.set(null, s -> s.expr("$.a = 1"))) - // 2. Second call: list has 1 item, offset should be 1 - .tasks(tb -> tb.set(null, s -> s.expr("$.b = 2"))) - // 3. Third call: list has 2 items, offset should be 2 - .tasks( - tb -> - tb.http( - null, http().get().endpoint("http://test")))))) + .tasks(d -> + d.listen( + null, // Auto-names the listen task + l -> + l.forEach(sub -> + // 1. First call: list is empty, offset is 0 + sub.tasks(tb -> tb.set(null, s -> s.expr("$.a = 1"))) + // 2. Second call: list has 1 item, offset should be 1 + .tasks(tb -> tb.set(null, s -> s.expr("$.b = 2"))) + // 3. Third call: list has 2 items, offset should be 2 + .tasks(tb -> tb.http(null, http().get().endpoint("http://test")))))) .build(); List topItems = wf.getDo(); @@ -455,21 +430,20 @@ null, http().get().endpoint("http://test")))))) void testNamedForkBranchesWrapDoTaskAndPreserveBranchName() { Workflow wf = WorkflowBuilder.workflow("flowNamedForkBranch") - .tasks( - d -> - d.fork( - null, - f -> - f.branch( - "helloBranch", - b -> - b.wait(null, w -> w.wait(Duration.ofMillis(10))) - .set(null, s -> s.expr("$.value = 1"))) - .branch( - "byeBranch", - b -> - b.wait(null, w -> w.wait(Duration.ofMillis(10))) - .set(null, s -> s.expr("$.value = 2"))))) + .tasks(d -> + d.fork( + null, + f -> + f.branch( + "helloBranch", + b -> + b.wait(null, w -> w.wait(Duration.ofMillis(10))) + .set(null, s -> s.expr("$.value = 1"))) + .branch( + "byeBranch", + b -> + b.wait(null, w -> w.wait(Duration.ofMillis(10))) + .set(null, s -> s.expr("$.value = 2"))))) .build(); List topItems = wf.getDo(); diff --git a/fluent/spec/src/test/java/org/openworkflow/sdk/fluent/spec/UseAuthenticationsBuilderTest.java b/fluent/spec/src/test/java/org/openworkflow/sdk/fluent/spec/UseAuthenticationsBuilderTest.java index 174a20bf3..590996be8 100644 --- a/fluent/spec/src/test/java/org/openworkflow/sdk/fluent/spec/UseAuthenticationsBuilderTest.java +++ b/fluent/spec/src/test/java/org/openworkflow/sdk/fluent/spec/UseAuthenticationsBuilderTest.java @@ -85,14 +85,12 @@ void digest_shorthand_creates_digest_policy() { void oidc_shorthand_without_client_creates_oidc_policy() { Workflow wf = WorkflowBuilder.workflow("f") - .use( - u -> - u.authentications( - a -> - a.oidc( - "myOidc", - "https://auth.example.com/", - OAuth2AuthenticationDataGrant.CLIENT_CREDENTIALS))) + .use(u -> + u.authentications(a -> + a.oidc( + "myOidc", + "https://auth.example.com/", + OAuth2AuthenticationDataGrant.CLIENT_CREDENTIALS))) .build(); AuthenticationPolicyUnion union = @@ -115,16 +113,14 @@ void oidc_shorthand_without_client_creates_oidc_policy() { void oidc_shorthand_with_client_creates_oidc_policy() { Workflow wf = WorkflowBuilder.workflow("f") - .use( - u -> - u.authentications( - a -> - a.oidc( - "myOidc", - "https://auth.example.com/", - OAuth2AuthenticationDataGrant.CLIENT_CREDENTIALS, - "client-id", - "client-secret"))) + .use(u -> + u.authentications(a -> + a.oidc( + "myOidc", + "https://auth.example.com/", + OAuth2AuthenticationDataGrant.CLIENT_CREDENTIALS, + "client-id", + "client-secret"))) .build(); AuthenticationPolicyUnion union = @@ -148,16 +144,14 @@ void oidc_shorthand_with_client_creates_oidc_policy() { void oauth2_shorthand_with_client_creates_oidc_policy() { Workflow wf = WorkflowBuilder.workflow("f") - .use( - u -> - u.authentications( - a -> - a.oauth2( - "myAuth", - "https://auth.example.com/", - OAuth2AuthenticationDataGrant.CLIENT_CREDENTIALS, - "cid", - "csecret"))) + .use(u -> + u.authentications(a -> + a.oauth2( + "myAuth", + "https://auth.example.com/", + OAuth2AuthenticationDataGrant.CLIENT_CREDENTIALS, + "cid", + "csecret"))) .build(); AuthenticationPolicyUnion union = @@ -181,17 +175,15 @@ void oauth2_shorthand_with_client_creates_oidc_policy() { void oauth2_shorthand_with_custom_endpoints() { Workflow wf = WorkflowBuilder.workflow("f") - .use( - u -> - u.authentications( - a -> - a.oauth2( - "myAuth", - "https://auth.example.com/", - OAuth2AuthenticationDataGrant.CLIENT_CREDENTIALS, - "cid", - "csecret", - e -> e.token("/custom/token")))) + .use(u -> + u.authentications(a -> + a.oauth2( + "myAuth", + "https://auth.example.com/", + OAuth2AuthenticationDataGrant.CLIENT_CREDENTIALS, + "cid", + "csecret", + e -> e.token("/custom/token")))) .build(); AuthenticationPolicyUnion union = @@ -216,18 +208,16 @@ void oauth2_shorthand_with_custom_endpoints() { void oauth2_full_builder_shorthand() { Workflow wf = WorkflowBuilder.workflow("f") - .use( - u -> - u.authentications( - a -> - a.oauth2( - "myAuth", - o -> - o.endpoints(e -> e.token("/t").revocation("/r")) - .authority("https://auth.example.com/") - .grant(OAuth2AuthenticationDataGrant.CLIENT_CREDENTIALS) - .scopes("read", "write") - .client(c -> c.id("cid").secret("csecret"))))) + .use(u -> + u.authentications(a -> + a.oauth2( + "myAuth", + o -> + o.endpoints(e -> e.token("/t").revocation("/r")) + .authority("https://auth.example.com/") + .grant(OAuth2AuthenticationDataGrant.CLIENT_CREDENTIALS) + .scopes("read", "write") + .client(c -> c.id("cid").secret("csecret"))))) .build(); AuthenticationPolicyUnion union = @@ -251,22 +241,20 @@ void oauth2_full_builder_shorthand() { void multiple_named_authentications_via_chaining() { Workflow wf = WorkflowBuilder.workflow("f") - .use( - u -> - u.authentications( - a -> - a.oauth2( - "joogle", - "https://joogle.example.com/", - OAuth2AuthenticationDataGrant.CLIENT_CREDENTIALS, - "joogle-id", - "joogle-secret") - .oauth2( - "jahoo", - "https://jahoo.example.com/", - OAuth2AuthenticationDataGrant.CLIENT_CREDENTIALS, - "jahoo-id", - "jahoo-secret"))) + .use(u -> + u.authentications(a -> + a.oauth2( + "joogle", + "https://joogle.example.com/", + OAuth2AuthenticationDataGrant.CLIENT_CREDENTIALS, + "joogle-id", + "joogle-secret") + .oauth2( + "jahoo", + "https://jahoo.example.com/", + OAuth2AuthenticationDataGrant.CLIENT_CREDENTIALS, + "jahoo-id", + "jahoo-secret"))) .build(); UseAuthentications auths = wf.getUse().getAuthentications(); @@ -296,18 +284,16 @@ void multiple_named_authentications_via_chaining() { void mixed_auth_types_via_chaining() { Workflow wf = WorkflowBuilder.workflow("f") - .use( - u -> - u.authentications( - a -> - a.basic("b", "user", "pass") - .bearer("t", "token-123") - .oauth2( - "o", - "https://auth.example.com/", - OAuth2AuthenticationDataGrant.CLIENT_CREDENTIALS, - "cid", - "csecret"))) + .use(u -> + u.authentications(a -> + a.basic("b", "user", "pass") + .bearer("t", "token-123") + .oauth2( + "o", + "https://auth.example.com/", + OAuth2AuthenticationDataGrant.CLIENT_CREDENTIALS, + "cid", + "csecret"))) .build(); UseAuthentications auths = wf.getUse().getAuthentications(); diff --git a/fluent/spec/src/test/java/org/openworkflow/sdk/fluent/spec/WorkflowBuilderTest.java b/fluent/spec/src/test/java/org/openworkflow/sdk/fluent/spec/WorkflowBuilderTest.java index 983312b29..d8b899110 100644 --- a/fluent/spec/src/test/java/org/openworkflow/sdk/fluent/spec/WorkflowBuilderTest.java +++ b/fluent/spec/src/test/java/org/openworkflow/sdk/fluent/spec/WorkflowBuilderTest.java @@ -103,18 +103,16 @@ void testWorkflowDocumentExplicit() { void testTaskMetadata() { Workflow wf = WorkflowBuilder.workflow("flowWithTaskMetadata") - .tasks( - d -> - d.set( - "described", - s -> - s.expr("$.value = 'test'") - .metadata( - m -> - m.description("Exit when counter reaches 10") - .put("exitConditionDescription", "counter == 10") - .put("weight", 42))) - .set("plain", s -> s.expr("$.other = 'value'"))) + .tasks(d -> + d.set( + "described", + s -> + s.expr("$.value = 'test'") + .metadata(m -> + m.description("Exit when counter reaches 10") + .put("exitConditionDescription", "counter == 10") + .put("weight", 42))) + .set("plain", s -> s.expr("$.other = 'value'"))) .build(); List items = wf.getDo(); @@ -164,10 +162,9 @@ void testEmptyTasksConsumerThrows() { void testDoTaskSetAndForEach() { Workflow wf = WorkflowBuilder.workflow("flowDo") - .tasks( - d -> - d.set("initCtx", "$.foo = 'bar'") - .forEach("item", f -> f.each("item").at("index").in("$.list"))) + .tasks(d -> + d.set("initCtx", "$.foo = 'bar'") + .forEach("item", f -> f.each("item").at("index").in("$.list"))) .build(); List items = wf.getDo(); @@ -190,9 +187,8 @@ void testTaskNamedSet() { // Test that we can now name a task "set" using the DSL Workflow wf = WorkflowBuilder.workflow("flowWithSetTask") - .tasks( - d -> - d.set("set", "$.value = 'test'").set("set", s -> s.expr("$.another = 'value'"))) + .tasks(d -> + d.set("set", "$.value = 'test'").set("set", s -> s.expr("$.another = 'value'"))) .build(); List items = wf.getDo(); @@ -252,11 +248,8 @@ void testAllTasksWithExplicitNames() { listen( "listen", l -> - l.to( - to -> - to.one( - f -> - f.with(p -> p.type("com.test.event").source("test"))))), + l.to(to -> + to.one(f -> f.with(p -> p.type("com.test.event").source("test"))))), forEach("forEach", f -> f.each("item").in("$.items")), fork("fork", f -> f.compete(false)), switchCase("switch", cases().onDefault(FlowDirectiveEnum.CONTINUE)), @@ -300,21 +293,20 @@ void testAllTasksWithExplicitNames() { void testDoTaskMultipleTypes() { Workflow wf = WorkflowBuilder.workflow("flowMixed") - .tasks( - d -> - d.set("init", s -> s.expr("$.init = true")) - .forEach("items", f -> f.each("item").in("$.list")) - .switchCase("choice", cases().onDefault(FlowDirectiveEnum.CONTINUE)) - .raise( - "alert", - r -> { - // no-op configuration - }) - .fork( - "parallel", - f -> { - // no-op configuration - })) + .tasks(d -> + d.set("init", s -> s.expr("$.init = true")) + .forEach("items", f -> f.each("item").in("$.list")) + .switchCase("choice", cases().onDefault(FlowDirectiveEnum.CONTINUE)) + .raise( + "alert", + r -> { + // no-op configuration + }) + .fork( + "parallel", + f -> { + // no-op configuration + })) .build(); List items = wf.getDo(); @@ -351,21 +343,16 @@ void testDoTaskMultipleTypes() { void testDoTaskListenOne() { Workflow wf = WorkflowBuilder.workflow("flowListen") - .tasks( - d -> - d.listen( - "waitCheck", - l -> - l.to( - to -> - to.one( - f -> - f.with(p -> p.type("com.fake.pet").source("mySource")) - .correlate( - "orderId", - c -> - c.from("$.data.orderId") - .expect("$.input.orderId")))))) + .tasks(d -> + d.listen( + "waitCheck", + l -> + l.to(to -> + to.one(f -> + f.with(p -> p.type("com.fake.pet").source("mySource")) + .correlate( + "orderId", + c -> c.from("$.data.orderId").expect("$.input.orderId")))))) .build(); List items = wf.getDo(); @@ -436,20 +423,16 @@ void testDoTaskEmitEvent() { void testDoTaskTryCatchWithRetry() { Workflow wf = WorkflowBuilder.workflow("flowTry") - .tasks( - d -> - d.tryCatch( - "tryBlock", - t -> - t.tryHandler(tb -> tb.set("init", s -> s.expr("$.start = true"))) - .catchHandler( - c -> - c.when("$.errorType == 'TEMP' ") - .retry( - r -> - r.when("$.retryCount < 3") - .limit( - l -> l.attempt(at -> at.count(3))))))) + .tasks(d -> + d.tryCatch( + "tryBlock", + t -> + t.tryHandler(tb -> tb.set("init", s -> s.expr("$.start = true"))) + .catchHandler(c -> + c.when("$.errorType == 'TEMP' ") + .retry(r -> + r.when("$.retryCount < 3") + .limit(l -> l.attempt(at -> at.count(3))))))) .build(); List items = wf.getDo(); @@ -484,20 +467,17 @@ void testDoTaskTryCatchWithRetry() { void testDoTaskTryCatchErrorsFiltering() { Workflow wf = WorkflowBuilder.workflow("flowCatch") - .tasks( - d -> - d.tryCatch( - "tryBlock", - t -> - t.tryHandler(tb -> tb.set("foo", s -> s.expr("$.foo = 'bar'"))) - .catchHandler( - c -> - c.exceptWhen("$.status == 500") - .errorsWith( - eb -> - eb.type("ServerError") - .status(500) - .instance("http://errors/5xx"))))) + .tasks(d -> + d.tryCatch( + "tryBlock", + t -> + t.tryHandler(tb -> tb.set("foo", s -> s.expr("$.foo = 'bar'"))) + .catchHandler(c -> + c.exceptWhen("$.status == 500") + .errorsWith(eb -> + eb.type("ServerError") + .status(500) + .instance("http://errors/5xx"))))) .build(); TaskItem item = wf.getDo().get(0); @@ -582,14 +562,13 @@ void testWorkflowInputInlineSchemaAndFromObject() { void testDoTaskCallHTTPBasic() { Workflow wf = WorkflowBuilder.workflow("flowCallBasic") - .tasks( - d -> - d.http( - "basicCall", - http() - .post() - .uri(URI.create("http://example.com/api")) - .andThen(b -> b.body(Map.of("foo", "bar"))))) + .tasks(d -> + d.http( + "basicCall", + http() + .post() + .uri(URI.create("http://example.com/api")) + .andThen(b -> b.body(Map.of("foo", "bar"))))) .build(); List items = wf.getDo(); assertEquals(1, items.size(), "Should have one HTTP call task"); @@ -608,11 +587,10 @@ void testDoTaskCallHTTPBasic() { void testDoTaskCallHTTPHeadersConsumerAndMap() { Workflow wf = WorkflowBuilder.workflow("flowCallHeaders") - .tasks( - d -> - d.http( - "hdrCall", - http().get().endpoint("${uriExpr}").headers(Map.of("A", "1", "B", "2")))) + .tasks(d -> + d.http( + "hdrCall", + http().get().endpoint("${uriExpr}").headers(Map.of("A", "1", "B", "2")))) .build(); CallHTTP call = wf.getDo().get(0).getTask().getCallTask().getCallHTTP(); HTTPHeaders hh = call.getWith().getHeaders().getHTTPHeaders(); @@ -621,10 +599,8 @@ void testDoTaskCallHTTPHeadersConsumerAndMap() { Workflow wf2 = WorkflowBuilder.workflow() - .tasks( - d -> - d.http( - http().get().endpoint("${ expr }").headers(Map.of("X", "10", "Y", "20")))) + .tasks(d -> + d.http(http().get().endpoint("${ expr }").headers(Map.of("X", "10", "Y", "20")))) .build(); CallHTTP call2 = wf2.getDo().get(0).getTask().getCallTask().getCallHTTP(); HTTPHeaders hh2 = call2.getWith().getHeaders().getHTTPHeaders(); @@ -636,14 +612,13 @@ void testDoTaskCallHTTPHeadersConsumerAndMap() { void testDoTaskCallHTTPQueryMap() { Workflow wf = WorkflowBuilder.workflow("flowCallQuery") - .tasks( - d -> - d.http( - "qryCall", - http() - .get() - .endpoint("${ exprUri }") - .andThen(q -> q.query(Map.of("k1", "v1", "k2", "v2"))))) + .tasks(d -> + d.http( + "qryCall", + http() + .get() + .endpoint("${ exprUri }") + .andThen(q -> q.query(Map.of("k1", "v1", "k2", "v2"))))) .build(); HTTPQuery hq = wf.getDo().get(0).getTask().getCallTask().getCallHTTP().getWith().getQuery().getHTTPQuery(); @@ -652,13 +627,9 @@ void testDoTaskCallHTTPQueryMap() { Workflow wf2 = WorkflowBuilder.workflow() - .tasks( - d -> - d.http( - c -> - c.method("GET") - .endpoint("http://uri") - .query(Map.of("q1", "x", "q2", "y")))) + .tasks(d -> + d.http(c -> + c.method("GET").endpoint("http://uri").query(Map.of("q1", "x", "q2", "y")))) .build(); HTTPQuery hq2 = wf2.getDo() @@ -688,15 +659,14 @@ void testDoTaskCallHTTPQuerySingleKeyValue() { void testDoTaskCallHTTPRedirectAndOutput() { Workflow wf = WorkflowBuilder.workflow("flowCallOpts") - .tasks( - d -> - d.http( - "optCall", - c -> - c.method("DELETE") - .endpoint("${ expr }") - .redirect(true) - .output(HTTPArguments.HTTPOutput.RESPONSE))) + .tasks(d -> + d.http( + "optCall", + c -> + c.method("DELETE") + .endpoint("${ expr }") + .redirect(true) + .output(HTTPArguments.HTTPOutput.RESPONSE))) .build(); CallHTTP call = wf.getDo().get(0).getTask().getCallTask().getCallHTTP(); assertTrue(call.getWith().isRedirect(), "Redirect should be true"); @@ -710,17 +680,16 @@ void testDoTaskCallHTTPRedirectAndOutput() { void testDoTaskRunWorkflow() { Workflow wf = WorkflowBuilder.workflow("parentFlow") - .tasks( - d -> - d.workflow( - "runChild", - w -> - w.namespace("org.acme") - .name("childFlow") - .version("1.0.0") - .input(Map.of("id", 42, "region", "us-east")) - .await(false) - .returnType(RunTaskConfiguration.ProcessReturnType.NONE))) + .tasks(d -> + d.workflow( + "runChild", + w -> + w.namespace("org.acme") + .name("childFlow") + .version("1.0.0") + .input(Map.of("id", 42, "region", "us-east")) + .await(false) + .returnType(RunTaskConfiguration.ProcessReturnType.NONE))) .build(); var runTask = wf.getDo().get(0).getTask().getRunTask(); diff --git a/fluent/spec/src/test/java/org/openworkflow/sdk/fluent/spec/dsl/DSLTest.java b/fluent/spec/src/test/java/org/openworkflow/sdk/fluent/spec/dsl/DSLTest.java index d32313b3e..e594a16b6 100644 --- a/fluent/spec/src/test/java/org/openworkflow/sdk/fluent/spec/dsl/DSLTest.java +++ b/fluent/spec/src/test/java/org/openworkflow/sdk/fluent/spec/dsl/DSLTest.java @@ -69,13 +69,12 @@ public void when_new_http_call_task() { public void when_listen_all_then_emit() { Workflow wf = WorkflowBuilder.workflow("myFlow", "myNs", "1.2.3") - .tasks( - t -> - t.listen( - to().all( - event().type("org.acme.listen"), - event().type("org.example.listen"))) - .emit(produced("org.example.emit"))) + .tasks(t -> + t.listen( + to().all( + event().type("org.acme.listen"), + event().type("org.example.listen"))) + .emit(produced("org.example.emit"))) .build(); // Sanity @@ -139,12 +138,11 @@ public void when_listen_any_with_until() { Workflow wf = WorkflowBuilder.workflow("f", "ns", "1") - .tasks( - t -> - t.listen( - to().any(event().type("A"), event().type("B")) - .until(untilExpr) - .andThen(c -> c.read(ListenTaskConfiguration.ListenAndReadAs.RAW)))) + .tasks(t -> + t.listen( + to().any(event().type("A"), event().type("B")) + .until(untilExpr) + .andThen(c -> c.read(ListenTaskConfiguration.ListenAndReadAs.RAW)))) .build(); var to = wf.getDo().get(0).getTask().getListenTask().getListen().getTo(); @@ -167,15 +165,13 @@ public void when_listen_any_with_until() { public void when_listen_one() { Workflow wf = WorkflowBuilder.workflow("f", "ns", "1") - .tasks( - t -> - t.listen( - to().one( - event() - .type("only-once") - .correlate( - "workflowInstanceId", - c -> c.from("$.metadata.instanceId"))))) + .tasks(t -> + t.listen( + to().one( + event() + .type("only-once") + .correlate( + "workflowInstanceId", c -> c.from("$.metadata.instanceId"))))) .build(); var to = wf.getDo().get(0).getTask().getListenTask().getListen().getTo(); @@ -197,10 +193,8 @@ public void when_listen_one() { public void when_raise_with_string_type_and_status() { Workflow wf = WorkflowBuilder.workflow("f", "ns", "1") - .tasks( - t -> - t.raise( - error("org.acme.Error", 422).title("Unprocessable").detail("Bad input"))) + .tasks(t -> + t.raise(error("org.acme.Error", 422).title("Unprocessable").detail("Bad input"))) .build(); var err = wf.getDo().get(0).getTask().getRaiseTask().getRaise().getError(); diff --git a/fluent/spec/src/test/java/org/openworkflow/sdk/fluent/spec/dsl/DSLTimeoutTest.java b/fluent/spec/src/test/java/org/openworkflow/sdk/fluent/spec/dsl/DSLTimeoutTest.java index 9439c7af3..9163f65c1 100644 --- a/fluent/spec/src/test/java/org/openworkflow/sdk/fluent/spec/dsl/DSLTimeoutTest.java +++ b/fluent/spec/src/test/java/org/openworkflow/sdk/fluent/spec/dsl/DSLTimeoutTest.java @@ -126,17 +126,15 @@ public void when_all_timeout_shortcuts_are_applied() { @Test public void when_mixing_expression_and_inline_throws_exception() { - assertThatThrownBy( - () -> - WorkflowBuilder.workflow("failFlow", "myNs", "1.0.0") - .timeout(t -> t.duration("PT15M").duration(d -> d.minutes(15)))) + assertThatThrownBy(() -> + WorkflowBuilder.workflow("failFlow", "myNs", "1.0.0") + .timeout(t -> t.duration("PT15M").duration(d -> d.minutes(15)))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Duration expression already set"); - assertThatThrownBy( - () -> - WorkflowBuilder.workflow("failFlow", "myNs", "1.0.0") - .timeout(t -> t.duration(d -> d.minutes(15)).duration("PT15M"))) + assertThatThrownBy(() -> + WorkflowBuilder.workflow("failFlow", "myNs", "1.0.0") + .timeout(t -> t.duration(d -> d.minutes(15)).duration("PT15M"))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Duration already specified"); } diff --git a/fluent/spec/src/test/java/org/openworkflow/sdk/fluent/spec/dsl/TryCatchDslTest.java b/fluent/spec/src/test/java/org/openworkflow/sdk/fluent/spec/dsl/TryCatchDslTest.java index ec1daf75b..aac95f588 100644 --- a/fluent/spec/src/test/java/org/openworkflow/sdk/fluent/spec/dsl/TryCatchDslTest.java +++ b/fluent/spec/src/test/java/org/openworkflow/sdk/fluent/spec/dsl/TryCatchDslTest.java @@ -40,24 +40,23 @@ public class TryCatchDslTest { void when_try_with_tasks_and_catch_when_with_retry_and_tasks() { Workflow wf = WorkflowBuilder.workflow("f", "ns", "1") - .tasks( - t -> - t.tryCatch( - tryCatch() - // try block (one HTTP call) - .tasks(call(http().get().endpoint(EXPR_ENDPOINT))) - // catch block - .catches() - .when("$.error == true") - .errors(Errors.RUNTIME, 500) - .tasks(emit("org.acme.failed")) - .retry() - .when("$.retries < 3") - .limit("PT5S") - .jitter("PT0.1S", "PT0.5S") - .done() // back to TryCatchSpec - .done() // back to TrySpec - )) + .tasks(t -> + t.tryCatch( + tryCatch() + // try block (one HTTP call) + .tasks(call(http().get().endpoint(EXPR_ENDPOINT))) + // catch block + .catches() + .when("$.error == true") + .errors(Errors.RUNTIME, 500) + .tasks(emit("org.acme.failed")) + .retry() + .when("$.retries < 3") + .limit("PT5S") + .jitter("PT0.1S", "PT0.5S") + .done() // back to TryCatchSpec + .done() // back to TrySpec + )) .build(); // --- locate Try task --- @@ -113,21 +112,20 @@ void when_try_with_multiple_tasks_and_catch_except_when_with_uri_error_filter() Workflow wf = WorkflowBuilder.workflow("g", "ns", "1") - .tasks( - t -> - t.tryCatch( - tryCatch() - // try with two tasks - .tasks( - call(http().get().endpoint(EXPR_ENDPOINT)), - set("$.status = \"IN_FLIGHT\"")) - // catch with exceptWhen + explicit URI error filter + status - .catches() - .exceptWhen("$.code == 502") - .errors(errType, 502) - .tasks(emit("org.acme.recover")) - .done() // back to TrySpec - )) + .tasks(t -> + t.tryCatch( + tryCatch() + // try with two tasks + .tasks( + call(http().get().endpoint(EXPR_ENDPOINT)), + set("$.status = \"IN_FLIGHT\"")) + // catch with exceptWhen + explicit URI error filter + status + .catches() + .exceptWhen("$.code == 502") + .errors(errType, 502) + .tasks(emit("org.acme.recover")) + .done() // back to TrySpec + )) .build(); var tryTask = wf.getDo().get(0).getTask().getTryTask(); @@ -167,19 +165,18 @@ void when_try_with_multiple_tasks_and_catch_except_when_with_uri_error_filter() void when_try_with_catch_and_simple_retry_limit_only() { Workflow wf = WorkflowBuilder.workflow("r", "ns", "1") - .tasks( - t -> - t.tryCatch( - tryCatch() - .tasks(call(http().get().endpoint(EXPR_ENDPOINT))) - .catches() - .when("$.fail == true") - .errors(Errors.COMMUNICATION, 503) - .retry() - .limit("PT2S") - .done() - .tasks(emit("org.acme.retrying")) - .done())) + .tasks(t -> + t.tryCatch( + tryCatch() + .tasks(call(http().get().endpoint(EXPR_ENDPOINT))) + .catches() + .when("$.fail == true") + .errors(Errors.COMMUNICATION, 503) + .retry() + .limit("PT2S") + .done() + .tasks(emit("org.acme.retrying")) + .done())) .build(); var tryTask = wf.getDo().get(0).getTask().getTryTask(); @@ -316,11 +313,10 @@ void when_try_catch_match_details() { error(URI.create("https://example.com/errors/transient"), 503) .detail("Enforcement Failure - invalid email"))) .catches() - .errors( - e -> - e.type("https://example.com/errors/transient") - .status(503) - .details("Enforcement Failure - invalid email")) + .errors(e -> + e.type("https://example.com/errors/transient") + .status(503) + .details("Enforcement Failure - invalid email")) .tasks(set("handleError", s -> s.put("recovered", true))) .done())) .build(); @@ -435,15 +431,14 @@ void when_try_catch_reusable_retry() { WorkflowBuilder.workflow("try-catch-retry-reusable", "test", "0.1.0") .use( use() - .retries( - r -> - r.retry( - "default", - policy -> - policy - .delay("PT0.01S") - .backoff(b -> b.constant("c", "10")) - .limit(l -> l.attempt(a -> a.count(5)))))) + .retries(r -> + r.retry( + "default", + policy -> + policy + .delay("PT0.01S") + .backoff(b -> b.constant("c", "10")) + .limit(l -> l.attempt(a -> a.count(5)))))) .tasks( tryCatch( "tryGetPet", @@ -698,25 +693,23 @@ void when_try_catch_backoff_constant_then_oneof_value_is_set() { @Test void when_backoff_builder_mixes_variants_then_throws() { - assertThatThrownBy( - () -> - WorkflowBuilder.workflow("mixed-backoff", "test", "0.1.0") - .tasks( - tryCatch( - "tryTask", - tryCatch() - .tasks(call(http().get().endpoint("http://localhost:9797"))) - .catches() - .errors(Errors.COMMUNICATION, 404) - .retry() - .backoff( - b -> { - b.constant("c", "10"); - b.exponential("e", "1.5"); - }) - .done() - .done())) - .build()) + assertThatThrownBy(() -> + WorkflowBuilder.workflow("mixed-backoff", "test", "0.1.0") + .tasks( + tryCatch( + "tryTask", + tryCatch() + .tasks(call(http().get().endpoint("http://localhost:9797"))) + .catches() + .errors(Errors.COMMUNICATION, 404) + .retry() + .backoff(b -> { + b.constant("c", "10"); + b.exponential("e", "1.5"); + }) + .done() + .done())) + .build()) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Only one backoff variant"); } diff --git a/generators/types/src/main/java/org/openworkflow/sdk/generator/AllAnyOneOfSchemaRule.java b/generators/types/src/main/java/org/openworkflow/sdk/generator/AllAnyOneOfSchemaRule.java index 0f880b368..e9d39e8b8 100644 --- a/generators/types/src/main/java/org/openworkflow/sdk/generator/AllAnyOneOfSchemaRule.java +++ b/generators/types/src/main/java/org/openworkflow/sdk/generator/AllAnyOneOfSchemaRule.java @@ -311,14 +311,13 @@ private JDefinedClass wrapAll( private JDefinedClass populateRef( JDefinedClass definedClass, Optional refType, Schema parentSchema) { - refType.ifPresent( - type -> { - if (type instanceof JClass classType) { - definedClass._extends(classType); - } else { - wrapIt(parentSchema, definedClass, Optional.empty(), type, null); - } - }); + refType.ifPresent(type -> { + if (type instanceof JClass classType) { + definedClass._extends(classType); + } else { + wrapIt(parentSchema, definedClass, Optional.empty(), type, null); + } + }); if (definedClass.constructors().hasNext() && definedClass.getConstructor(new JType[0]) == null) { @@ -354,13 +353,12 @@ private JVar setupMethod( Optional valueField, JFieldVar instanceField) { JVar methodParam = method.param(instanceField.type(), instanceField.name()); - valueField.ifPresent( - v -> { - method.body().assign(JExpr._this().ref(v), methodParam); - method - .annotate(definedClass.owner().ref(OneOfSetter.class)) - .param("value", instanceField.type()); - }); + valueField.ifPresent(v -> { + method.body().assign(JExpr._this().ref(v), methodParam); + method + .annotate(definedClass.owner().ref(OneOfSetter.class)) + .param("value", instanceField.type()); + }); return methodParam; } diff --git a/impl/a2a/src/main/java/org/openworkflow/sdk/impl/executors/a2a/A2AExecutor.java b/impl/a2a/src/main/java/org/openworkflow/sdk/impl/executors/a2a/A2AExecutor.java index ba92ab502..83e449c5a 100644 --- a/impl/a2a/src/main/java/org/openworkflow/sdk/impl/executors/a2a/A2AExecutor.java +++ b/impl/a2a/src/main/java/org/openworkflow/sdk/impl/executors/a2a/A2AExecutor.java @@ -68,24 +68,21 @@ public CompletableFuture apply( } }, workflowContext.definition().application().executorService()) - .thenCompose( - agentCard -> { - logger.debug("Agent card is {}", agentCard); - try { - return dispatcher.apply( - agentCard, - Client.builder(agentCard) - .clientConfig(new ClientConfig.Builder().build()) - .withTransport(JSONRPCTransport.class, new JSONRPCTransportConfig()) - .build(), - mapResolver - .map(m -> m.apply(workflowContext, taskContext, input)) - .orElse(Map.of()), - workflowContext, - taskContext); - } catch (A2AClientException ex) { - throw A2AUtils.workflowException(taskContext.position(), ex); - } - }); + .thenCompose(agentCard -> { + logger.debug("Agent card is {}", agentCard); + try { + return dispatcher.apply( + agentCard, + Client.builder(agentCard) + .clientConfig(new ClientConfig.Builder().build()) + .withTransport(JSONRPCTransport.class, new JSONRPCTransportConfig()) + .build(), + mapResolver.map(m -> m.apply(workflowContext, taskContext, input)).orElse(Map.of()), + workflowContext, + taskContext); + } catch (A2AClientException ex) { + throw A2AUtils.workflowException(taskContext.position(), ex); + } + }); } } diff --git a/impl/a2a/src/main/java/org/openworkflow/sdk/impl/executors/a2a/A2AExecutorBuilder.java b/impl/a2a/src/main/java/org/openworkflow/sdk/impl/executors/a2a/A2AExecutorBuilder.java index d01923882..5462adcb7 100644 --- a/impl/a2a/src/main/java/org/openworkflow/sdk/impl/executors/a2a/A2AExecutorBuilder.java +++ b/impl/a2a/src/main/java/org/openworkflow/sdk/impl/executors/a2a/A2AExecutorBuilder.java @@ -54,14 +54,12 @@ public CallableTaskFactory init( A2ARequestDispatcher dispatcher = switch (args.getMethod()) { case MESSAGE_SEND -> - new MessageDispatcher( - (workflowContext, taskContext, completableFuture) -> - new MessageSendConsumer(workflowContext.definition(), completableFuture)); + new MessageDispatcher((workflowContext, taskContext, completableFuture) -> + new MessageSendConsumer(workflowContext.definition(), completableFuture)); case MESSAGE_STREAM -> - new MessageDispatcher( - (workflowContext, taskContext, completableFuture) -> - new MessageStreamConsumer( - workflowContext.definition(), completableFuture, taskContext.position())); + new MessageDispatcher((workflowContext, taskContext, completableFuture) -> + new MessageStreamConsumer( + workflowContext.definition(), completableFuture, taskContext.position())); case TASKS_LIST -> new ListTaskDispatcher(); case TASKS_GET -> new GetTaskDispatcher(); case TASKS_CANCEL -> new CancelTaskDispatcher(); diff --git a/impl/a2a/src/main/java/org/openworkflow/sdk/impl/executors/a2a/A2AUtils.java b/impl/a2a/src/main/java/org/openworkflow/sdk/impl/executors/a2a/A2AUtils.java index 96fdcfa32..9ea537aef 100644 --- a/impl/a2a/src/main/java/org/openworkflow/sdk/impl/executors/a2a/A2AUtils.java +++ b/impl/a2a/src/main/java/org/openworkflow/sdk/impl/executors/a2a/A2AUtils.java @@ -84,17 +84,16 @@ static T isInstanceOrThrow(Object obj, Class instanceClass, Supplier T isInstanceOrDefault(Object obj, Class instanceClass, Supplier defaultValue) { return isInstance(obj, instanceClass) - .orElseGet( - () -> { - if (obj != null) { - logger.warn( - "Object {} is expected to be of class {} but it is of class {}. Using provided default", - obj, - instanceClass.getName(), - obj.getClass().getName()); - } - return defaultValue.get(); - }); + .orElseGet(() -> { + if (obj != null) { + logger.warn( + "Object {} is expected to be of class {} but it is of class {}. Using provided default", + obj, + instanceClass.getName(), + obj.getClass().getName()); + } + return defaultValue.get(); + }); } private static Optional isInstance(Object obj, Class instanceClass) { diff --git a/impl/container/src/main/java/org/openworkflow/sdk/impl/container/executors/ContainerEnvironmentPropertySetter.java b/impl/container/src/main/java/org/openworkflow/sdk/impl/container/executors/ContainerEnvironmentPropertySetter.java index eb360e084..e3d459dd8 100644 --- a/impl/container/src/main/java/org/openworkflow/sdk/impl/container/executors/ContainerEnvironmentPropertySetter.java +++ b/impl/container/src/main/java/org/openworkflow/sdk/impl/container/executors/ContainerEnvironmentPropertySetter.java @@ -51,9 +51,8 @@ public void accept( WorkflowModel model) { envResolver .map(env -> env.apply(workflowContext, taskContext, model)) - .ifPresent( - envs -> - command.withEnv( - envs.entrySet().stream().map(e -> e.getKey() + "=" + e.getValue()).toList())); + .ifPresent(envs -> + command.withEnv( + envs.entrySet().stream().map(e -> e.getKey() + "=" + e.getValue()).toList())); } } diff --git a/impl/container/src/main/java/org/openworkflow/sdk/impl/container/executors/VolumesPropertySetter.java b/impl/container/src/main/java/org/openworkflow/sdk/impl/container/executors/VolumesPropertySetter.java index dedae00c4..934d54681 100644 --- a/impl/container/src/main/java/org/openworkflow/sdk/impl/container/executors/VolumesPropertySetter.java +++ b/impl/container/src/main/java/org/openworkflow/sdk/impl/container/executors/VolumesPropertySetter.java @@ -64,11 +64,10 @@ public void accept( .getHostConfig() .withBinds( binds.stream() - .map( - r -> - new Bind( - r.host().apply(workflowContext, taskContext, model), - new Volume(r.container.apply(workflowContext, taskContext, model)))) + .map(r -> + new Bind( + r.host().apply(workflowContext, taskContext, model), + new Volume(r.container.apply(workflowContext, taskContext, model)))) .toList()); } } diff --git a/impl/container/src/test/java/org/openworkflow/sdk/impl/test/ContainerTest.java b/impl/container/src/test/java/org/openworkflow/sdk/impl/test/ContainerTest.java index a086eef35..898e81579 100644 --- a/impl/container/src/test/java/org/openworkflow/sdk/impl/test/ContainerTest.java +++ b/impl/container/src/test/java/org/openworkflow/sdk/impl/test/ContainerTest.java @@ -166,14 +166,8 @@ public void onNext(Frame frame) { public void testContainerTimeout() throws IOException { String containerName = "hello-world-timeout"; Workflow workflow = readWorkflowFromClasspath("workflows-samples/container-timeout.yaml"); - assertThatThrownBy( - () -> - app.workflowDefinition(workflow) - .instance(Map.of()) - .start() - .join() - .asMap() - .orElseThrow()); + assertThatThrownBy(() -> + app.workflowDefinition(workflow).instance(Map.of()).start().join().asMap().orElseThrow()); assertTrue(isContainerGone(containerName)); } diff --git a/impl/core/src/main/java/org/openworkflow/sdk/impl/CollectionConversionUtils.java b/impl/core/src/main/java/org/openworkflow/sdk/impl/CollectionConversionUtils.java index 643b7ee63..7478951e3 100644 --- a/impl/core/src/main/java/org/openworkflow/sdk/impl/CollectionConversionUtils.java +++ b/impl/core/src/main/java/org/openworkflow/sdk/impl/CollectionConversionUtils.java @@ -52,10 +52,9 @@ else if (clazz.isArray()) { primitiveArray, i++, convert(item, componentType, converter) - .orElseThrow( - () -> - new IllegalArgumentException( - "Cannot convert " + item + " into class " + componentType))); + .orElseThrow(() -> + new IllegalArgumentException( + "Cannot convert " + item + " into class " + componentType))); } return Optional.of(clazz.cast(primitiveArray)); } else { diff --git a/impl/core/src/main/java/org/openworkflow/sdk/impl/CompositeExpressionFactory.java b/impl/core/src/main/java/org/openworkflow/sdk/impl/CompositeExpressionFactory.java index 4321f2487..aa7594eec 100644 --- a/impl/core/src/main/java/org/openworkflow/sdk/impl/CompositeExpressionFactory.java +++ b/impl/core/src/main/java/org/openworkflow/sdk/impl/CompositeExpressionFactory.java @@ -40,9 +40,8 @@ private T processFactories( .sorted(Comparator.comparingInt(f -> f.priority(desc))) .findFirst() .map(consumer::apply) - .orElseThrow( - () -> - new IllegalArgumentException("No expression factory found for expression " + desc)); + .orElseThrow(() -> + new IllegalArgumentException("No expression factory found for expression " + desc)); } @Override diff --git a/impl/core/src/main/java/org/openworkflow/sdk/impl/LifecycleEventsUtils.java b/impl/core/src/main/java/org/openworkflow/sdk/impl/LifecycleEventsUtils.java index c3a130b17..1df444b82 100644 --- a/impl/core/src/main/java/org/openworkflow/sdk/impl/LifecycleEventsUtils.java +++ b/impl/core/src/main/java/org/openworkflow/sdk/impl/LifecycleEventsUtils.java @@ -44,20 +44,17 @@ public static CompletableFuture publishEvent( for (Collection listeners : workflowContext.definition().application().listenersByPriority()) { result = - result.thenCompose( - __ -> - CompletableFuture.allOf( - listeners.stream() - .map( - v -> - function - .apply(v) - .exceptionally( - ex -> { - logger.error("Error while executing listener", ex); - return null; - })) - .toArray(CompletableFuture[]::new))); + result.thenCompose(__ -> + CompletableFuture.allOf( + listeners.stream() + .map(v -> + function + .apply(v) + .exceptionally(ex -> { + logger.error("Error while executing listener", ex); + return null; + })) + .toArray(CompletableFuture[]::new))); } return result; } diff --git a/impl/core/src/main/java/org/openworkflow/sdk/impl/WorkflowApplication.java b/impl/core/src/main/java/org/openworkflow/sdk/impl/WorkflowApplication.java index cebbcd89d..c7d1fc716 100644 --- a/impl/core/src/main/java/org/openworkflow/sdk/impl/WorkflowApplication.java +++ b/impl/core/src/main/java/org/openworkflow/sdk/impl/WorkflowApplication.java @@ -494,10 +494,9 @@ public WorkflowApplication build() { if (modelFactory == null) { modelFactory = loadFirst(WorkflowModelFactory.class) - .orElseThrow( - () -> - new IllegalStateException( - "WorkflowModelFactory instance has to be set in WorkflowApplication or present in the classpath")); + .orElseThrow(() -> + new IllegalStateException( + "WorkflowModelFactory instance has to be set in WorkflowApplication or present in the classpath")); } if (contextFactory == null) { contextFactory = modelFactory; @@ -516,14 +515,13 @@ public WorkflowApplication build() { if (eventConsumer == null) { eventConsumer = loadFirst(EventConsumer.class) - .orElseGet( - () -> { - InMemoryEvents inMemory = new InMemoryEvents(executorFactory); - if (eventPublishers.isEmpty()) { - eventPublishers.add(inMemory); - } - return inMemory; - }); + .orElseGet(() -> { + InMemoryEvents inMemory = new InMemoryEvents(executorFactory); + if (eventPublishers.isEmpty()) { + eventPublishers.add(inMemory); + } + return inMemory; + }); } if (idFactory == null) { idFactory = new MonotonicUlidWorkflowInstanceIdFactory(); @@ -533,23 +531,22 @@ public WorkflowApplication build() { if (cronResolverFactory == null) { cronResolverFactory = loadFirst(CronResolverFactory.class) - .orElseGet( - () -> - new CronResolverFactory() { - private CronResolver emptyResolver = - new CronResolver() { - @Override - public Optional nextExecution() { - throw new UnsupportedOperationException( - "Missing CronResolverFactory, please add openworkflow-impl-cron dependency to your classpath"); - } - }; - - @Override - public CronResolver parseCron(String cron) { - return emptyResolver; - } - }); + .orElseGet(() -> + new CronResolverFactory() { + private CronResolver emptyResolver = + new CronResolver() { + @Override + public Optional nextExecution() { + throw new UnsupportedOperationException( + "Missing CronResolverFactory, please add openworkflow-impl-cron dependency to your classpath"); + } + }; + + @Override + public CronResolver parseCron(String cron) { + return emptyResolver; + } + }); } schedulerExecutorService = Executors.newSingleThreadScheduledExecutor(); scheduler = new DefaultWorkflowScheduler(schedulerExecutorService, cronResolverFactory); diff --git a/impl/core/src/main/java/org/openworkflow/sdk/impl/WorkflowMutableInstance.java b/impl/core/src/main/java/org/openworkflow/sdk/impl/WorkflowMutableInstance.java index 55abf0d4c..1a3ba0a49 100644 --- a/impl/core/src/main/java/org/openworkflow/sdk/impl/WorkflowMutableInstance.java +++ b/impl/core/src/main/java/org/openworkflow/sdk/impl/WorkflowMutableInstance.java @@ -77,16 +77,14 @@ protected WorkflowMutableInstance(WorkflowDefinition definition, String id, Work @Override public CompletableFuture start() { - return startExecution( - () -> { - startedAt = Instant.now(); - return status(WorkflowStatus.RUNNING) - .thenCompose( - __ -> - publishEvent( - workflowContext, - l -> l.onWorkflowStarted(new WorkflowStartedEvent(workflowContext)))); - }); + return startExecution(() -> { + startedAt = Instant.now(); + return status(WorkflowStatus.RUNNING) + .thenCompose(__ -> + publishEvent( + workflowContext, + l -> l.onWorkflowStarted(new WorkflowStartedEvent(workflowContext)))); + }); } protected final CompletableFuture startExecution( @@ -122,43 +120,39 @@ public boolean cancel(boolean mayInterruptIfRunning) { if (isInitializer) { runnable .get() - .thenCompose( - v -> - TaskExecutorHelper.processTaskList( - workflowContext.definition().startTask(), - workflowContext, - Optional.empty(), - workflowContext - .definition() - .inputFilter() - .map(f -> f.apply(workflowContext, null, input)) - .orElse(input)) - .whenComplete(this::setCompleteDate) - .thenApply(this::filterAndValidate) - .thenCompose(this::publishCompletionEvents) - .exceptionallyCompose(this::handleException)) + .thenCompose(v -> + TaskExecutorHelper.processTaskList( + workflowContext.definition().startTask(), + workflowContext, + Optional.empty(), + workflowContext + .definition() + .inputFilter() + .map(f -> f.apply(workflowContext, null, input)) + .orElse(input)) + .whenComplete(this::setCompleteDate) + .thenApply(this::filterAndValidate) + .thenCompose(this::publishCompletionEvents) + .exceptionallyCompose(this::handleException)) .handle(this::cleanUpWaitingListeners) .thenCompose(Function.identity()) - .whenComplete( - (result, ex) -> { - if (ex != null) { - future.completeExceptionally( - ex instanceof CompletionException ? ex.getCause() : ex); - } else { - future.complete(result); - } - }); + .whenComplete((result, ex) -> { + if (ex != null) { + future.completeExceptionally(ex instanceof CompletionException ? ex.getCause() : ex); + } else { + future.complete(result); + } + }); } return future; } private CompletableFuture publishCompletionEvents(WorkflowModel model) { return status(WorkflowStatus.COMPLETED) - .thenCompose( - __ -> - publishEvent( - workflowContext, - l -> l.onWorkflowCompleted(new WorkflowCompletedEvent(workflowContext, model)))) + .thenCompose(__ -> + publishEvent( + workflowContext, + l -> l.onWorkflowCompleted(new WorkflowCompletedEvent(workflowContext, model)))) .thenApply(__ -> model); } @@ -197,11 +191,10 @@ private CompletableFuture handleException(Throwable exception) { return cause instanceof CancellationException ? CompletableFuture.failedFuture(cause) : status(WorkflowStatus.FAULTED) - .thenCompose( - __ -> - publishEvent( - workflowContext, - l -> l.onWorkflowFailed(new WorkflowFailedEvent(workflowContext, cause)))) + .thenCompose(__ -> + publishEvent( + workflowContext, + l -> l.onWorkflowFailed(new WorkflowFailedEvent(workflowContext, cause)))) .thenCompose(__ -> CompletableFuture.failedFuture(exception)); } @@ -260,10 +253,9 @@ public T outputAs(Class clazz) { return output != null ? output .as(clazz) - .orElseThrow( - () -> - new IllegalArgumentException( - "Output " + output + " cannot be converted to class " + clazz)) + .orElseThrow(() -> + new IllegalArgumentException( + "Output " + output + " cannot be converted to class " + clazz)) : null; } @@ -316,13 +308,11 @@ public boolean suspend() { if (result) { outOfOrder( publishStatusChange(prevState, WorkflowStatus.SUSPENDED) - .thenCompose( - changed -> - publishEvent( - changed, - workflowContext, - l -> - l.onWorkflowSuspended(new WorkflowSuspendedEvent(workflowContext))))); + .thenCompose(changed -> + publishEvent( + changed, + workflowContext, + l -> l.onWorkflowSuspended(new WorkflowSuspendedEvent(workflowContext))))); } return result; } @@ -332,12 +322,11 @@ public CompletableFuture suspendFuture() { WorkflowStatus prevState = internalSuspend(); return outOfOrder( publishStatusChange(prevState, WorkflowStatus.SUSPENDED) - .thenCompose( - changed -> - publishEvent( - changed, - workflowContext, - l -> l.onWorkflowSuspended(new WorkflowSuspendedEvent(workflowContext))))); + .thenCompose(changed -> + publishEvent( + changed, + workflowContext, + l -> l.onWorkflowSuspended(new WorkflowSuspendedEvent(workflowContext))))); } private WorkflowStatus internalSuspend() { @@ -365,12 +354,11 @@ public boolean resume() { if (result) { outOfOrder( publishStatusChange(prevStatus, WorkflowStatus.RUNNING) - .thenCompose( - changed -> - publishEvent( - changed, - workflowContext, - l -> l.onWorkflowResumed(new WorkflowResumedEvent(workflowContext))))); + .thenCompose(changed -> + publishEvent( + changed, + workflowContext, + l -> l.onWorkflowResumed(new WorkflowResumedEvent(workflowContext))))); } return result; } @@ -380,12 +368,11 @@ public CompletableFuture resumeFuture() { WorkflowStatus prevStatus = internalResume(); return outOfOrder( publishStatusChange(prevStatus, WorkflowStatus.RUNNING) - .thenCompose( - change -> - publishEvent( - change, - workflowContext, - l -> l.onWorkflowResumed(new WorkflowResumedEvent(workflowContext))))); + .thenCompose(change -> + publishEvent( + change, + workflowContext, + l -> l.onWorkflowResumed(new WorkflowResumedEvent(workflowContext))))); } private WorkflowStatus internalResume() { @@ -393,10 +380,9 @@ private WorkflowStatus internalResume() { try { statusLock.lock(); if (TaskExecutorHelper.isActive(status.get()) && suspended != null) { - suspended.forEach( - (k, v) -> { - k.complete(v); - }); + suspended.forEach((k, v) -> { + k.complete(v); + }); suspended = null; result = status.getAndSet(WorkflowStatus.RUNNING); } else { @@ -471,14 +457,11 @@ private CompletableFuture internalCancel() { CompletableFuture result = outOfOrder( publishStatusChange(prevState, WorkflowStatus.CANCELLED) - .thenCompose( - changed -> - publishEvent( - changed, - workflowContext, - l -> - l.onWorkflowCancelled( - new WorkflowCancelledEvent(workflowContext))))); + .thenCompose(changed -> + publishEvent( + changed, + workflowContext, + l -> l.onWorkflowCancelled(new WorkflowCancelledEvent(workflowContext))))); if (prevState != WorkflowStatus.CANCELLED && toCancel != null) { toCancel.forEach(t -> t.cancel(true)); @@ -501,15 +484,14 @@ public void addCancelable(CompletableFuture cancelable) { } else { cancelables.add(cancelable); statusLock.unlock(); - cancelable.thenAccept( - __ -> { - try { - statusLock.lock(); - cancelables.remove(cancelable); - } finally { - statusLock.unlock(); - } - }); + cancelable.thenAccept(__ -> { + try { + statusLock.lock(); + cancelables.remove(cancelable); + } finally { + statusLock.unlock(); + } + }); } } diff --git a/impl/core/src/main/java/org/openworkflow/sdk/impl/auth/AccessTokenProvider.java b/impl/core/src/main/java/org/openworkflow/sdk/impl/auth/AccessTokenProvider.java index dac605d9d..2d0969070 100644 --- a/impl/core/src/main/java/org/openworkflow/sdk/impl/auth/AccessTokenProvider.java +++ b/impl/core/src/main/java/org/openworkflow/sdk/impl/auth/AccessTokenProvider.java @@ -53,19 +53,16 @@ public CompletableFuture validateAndGet(WorkflowContext workflow, TaskConte List issuers = authRequestInfo.issuers(); if (!issuers.isEmpty()) { future = - future.whenComplete( - (jwt, ex) -> { - if (jwt != null) { - jwt.issuer() - .ifPresent( - issuer -> { - if (!issuers.contains(issuer)) { - throw new IllegalStateException( - "Token issuer is not valid: " + issuer); - } - }); - } - }); + future.whenComplete((jwt, ex) -> { + if (jwt != null) { + jwt.issuer() + .ifPresent(issuer -> { + if (!issuers.contains(issuer)) { + throw new IllegalStateException("Token issuer is not valid: " + issuer); + } + }); + } + }); } return future; } diff --git a/impl/core/src/main/java/org/openworkflow/sdk/impl/auth/DefaultAuthProviderFactory.java b/impl/core/src/main/java/org/openworkflow/sdk/impl/auth/DefaultAuthProviderFactory.java index 363527a09..3c5ac055a 100644 --- a/impl/core/src/main/java/org/openworkflow/sdk/impl/auth/DefaultAuthProviderFactory.java +++ b/impl/core/src/main/java/org/openworkflow/sdk/impl/auth/DefaultAuthProviderFactory.java @@ -65,11 +65,10 @@ private Optional buildFromPolicy( digestAuthProvider(app, workflow, authenticationPolicy.getDigestAuthenticationPolicy())); } return OAuthUtils.from(authenticationPolicy) - .map( - policyData -> - policyData.scheme() == OAuthScheme.OPENID_CONNECT - ? openIdAuthProvider(app, workflow, policyData) - : oAuth2AuthProvider(app, workflow, policyData)); + .map(policyData -> + policyData.scheme() == OAuthScheme.OPENID_CONNECT + ? openIdAuthProvider(app, workflow, policyData) + : oAuth2AuthProvider(app, workflow, policyData)); } protected AuthProvider oAuth2AuthProvider( diff --git a/impl/core/src/main/java/org/openworkflow/sdk/impl/auth/DigestAuthProvider.java b/impl/core/src/main/java/org/openworkflow/sdk/impl/auth/DigestAuthProvider.java index 5d5aefbf4..1effd3401 100644 --- a/impl/core/src/main/java/org/openworkflow/sdk/impl/auth/DigestAuthProvider.java +++ b/impl/core/src/main/java/org/openworkflow/sdk/impl/auth/DigestAuthProvider.java @@ -104,12 +104,12 @@ public static DigestServerInfo from(String header) { private static enum Algorithm { MD5, MD5SESSS - }; + } private static enum QOP { AUTH, AUTH_INT, - }; + } private static final String HEX = "%08x"; private final WorkflowValueResolver userFilter; @@ -147,14 +147,13 @@ public CompletableFuture content( return app.httpRequestFactory() .request(app, WorkflowHttpRequestInfo.builder(method).build(uri)) .invoke(workflow, task) - .thenApply( - r -> { - try { - return processResponse(r, uri, method, workflow, task); - } finally { - r.close(); - } - }); + .thenApply(r -> { + try { + return processResponse(r, uri, method, workflow, task); + } finally { + r.close(); + } + }); } private String processResponse( @@ -188,15 +187,14 @@ private String processResponse( nonceCount, serverInfo .qop - .map( - qop -> - calculateHash( - ha1, - serverInfo.nonce, - nonceCount, - clientNonce, - qop.toString().toLowerCase(), - ha2)) + .map(qop -> + calculateHash( + ha1, + serverInfo.nonce, + nonceCount, + clientNonce, + qop.toString().toLowerCase(), + ha2)) .orElseGet(() -> calculateHash(ha1, serverInfo.nonce, ha2))); } else { throw new IllegalStateException( diff --git a/impl/core/src/main/java/org/openworkflow/sdk/impl/executors/AbstractTaskExecutor.java b/impl/core/src/main/java/org/openworkflow/sdk/impl/executors/AbstractTaskExecutor.java index 26978e529..4957f0266 100644 --- a/impl/core/src/main/java/org/openworkflow/sdk/impl/executors/AbstractTaskExecutor.java +++ b/impl/core/src/main/java/org/openworkflow/sdk/impl/executors/AbstractTaskExecutor.java @@ -215,61 +215,52 @@ public CompletableFuture apply( completable = completable .thenCompose(workflowContext.instance()::suspendedCheck) - .thenCompose( - t -> { - CompletableFuture events = - t.isRetrying() - ? publishEvent( - workflowContext, - l -> - l.onTaskRetried( - new TaskRetriedEvent(workflowContext, taskContext))) - : publishEvent( - workflowContext, - l -> - l.onTaskStarted( - new TaskStartedEvent(workflowContext, taskContext))); - return events.thenApply(v -> t); - }) - .thenApply( - t -> { - inputSchemaValidator.ifPresent( - s -> validationError(s.validate(t.rawInput()), t)); - inputProcessor.ifPresent( - p -> taskContext.input(p.apply(workflowContext, t, t.rawInput()))); - return t; - }) + .thenCompose(t -> { + CompletableFuture events = + t.isRetrying() + ? publishEvent( + workflowContext, + l -> + l.onTaskRetried(new TaskRetriedEvent(workflowContext, taskContext))) + : publishEvent( + workflowContext, + l -> + l.onTaskStarted( + new TaskStartedEvent(workflowContext, taskContext))); + return events.thenApply(v -> t); + }) + .thenApply(t -> { + inputSchemaValidator.ifPresent(s -> validationError(s.validate(t.rawInput()), t)); + inputProcessor.ifPresent( + p -> taskContext.input(p.apply(workflowContext, t, t.rawInput()))); + return t; + }) .thenCompose(t -> execute(workflowContext, t)) .thenCompose(workflowContext.instance()::cancelCheck) - .thenApply( - t -> { - outputProcessor.ifPresent( - p -> t.output(p.apply(workflowContext, t, t.rawOutput()))); - outputSchemaValidator.ifPresent( - s -> validationError(s.validate(t.output()), t)); - contextProcessor.ifPresent( - p -> - workflowContext.context( - p.apply(workflowContext, t, workflowContext.context()))); - contextSchemaValidator.ifPresent( - s -> validationError(s.validate(workflowContext.context()), t)); - t.completedAt(Instant.now()); - return t; - }) - .thenCompose( - t -> - publishEvent( - workflowContext, - l -> - l.onTaskCompleted( - new TaskCompletedEvent(workflowContext, taskContext))) - .thenApply(__ -> t)) - .exceptionallyCompose( - e -> - handleException( + .thenApply(t -> { + outputProcessor.ifPresent( + p -> t.output(p.apply(workflowContext, t, t.rawOutput()))); + outputSchemaValidator.ifPresent(s -> validationError(s.validate(t.output()), t)); + contextProcessor.ifPresent(p -> + workflowContext.context( + p.apply(workflowContext, t, workflowContext.context()))); + contextSchemaValidator.ifPresent( + s -> validationError(s.validate(workflowContext.context()), t)); + t.completedAt(Instant.now()); + return t; + }) + .thenCompose(t -> + publishEvent( workflowContext, - taskContext, - e instanceof CompletionException ? e.getCause() : e)); + l -> + l.onTaskCompleted( + new TaskCompletedEvent(workflowContext, taskContext))) + .thenApply(__ -> t)) + .exceptionallyCompose(e -> + handleException( + workflowContext, + taskContext, + e instanceof CompletionException ? e.getCause() : e)); if (timeout.isPresent()) { completable = completable @@ -279,14 +270,13 @@ public CompletableFuture apply( .orElseThrow() .toMillis(), TimeUnit.MILLISECONDS) - .exceptionallyCompose( - e -> - CompletableFuture.failedFuture( - new WorkflowException( - WorkflowError.timeout() - .instance(taskContext.position().jsonPointer()) - .build(), - e))); + .exceptionallyCompose(e -> + CompletableFuture.failedFuture( + new WorkflowException( + WorkflowError.timeout() + .instance(taskContext.position().jsonPointer()) + .build(), + e))); } return executeNext(completable, workflowContext); } else { diff --git a/impl/core/src/main/java/org/openworkflow/sdk/impl/executors/CallFunctionExecutorBuilder.java b/impl/core/src/main/java/org/openworkflow/sdk/impl/executors/CallFunctionExecutorBuilder.java index bc5d35f14..9cfd49fbd 100644 --- a/impl/core/src/main/java/org/openworkflow/sdk/impl/executors/CallFunctionExecutorBuilder.java +++ b/impl/core/src/main/java/org/openworkflow/sdk/impl/executors/CallFunctionExecutorBuilder.java @@ -110,10 +110,9 @@ private Task from(WorkflowDefinition definition, String name, byte[] content) { .application() .functionReader() .map(v -> v.apply(name, content)) - .orElseThrow( - () -> - new IllegalStateException( - "No converter from external resource to function found. Make sure a dependency that includes an implementation of FunctionReader is included")); + .orElseThrow(() -> + new IllegalStateException( + "No converter from external resource to function found. Make sure a dependency that includes an implementation of FunctionReader is included")); } @Override diff --git a/impl/core/src/main/java/org/openworkflow/sdk/impl/executors/DefaultTaskExecutorFactory.java b/impl/core/src/main/java/org/openworkflow/sdk/impl/executors/DefaultTaskExecutorFactory.java index 664c5b4d6..c7ab39e03 100644 --- a/impl/core/src/main/java/org/openworkflow/sdk/impl/executors/DefaultTaskExecutorFactory.java +++ b/impl/core/src/main/java/org/openworkflow/sdk/impl/executors/DefaultTaskExecutorFactory.java @@ -92,9 +92,8 @@ private CallableTaskBuilder findCallTask( callTasks.stream() .filter(s -> s.accept(clazz)) .findFirst() - .orElseThrow( - () -> - new UnsupportedOperationException( - clazz.getName() + " not accepted by any of these builders " + callTasks)); + .orElseThrow(() -> + new UnsupportedOperationException( + clazz.getName() + " not accepted by any of these builders " + callTasks)); } } diff --git a/impl/core/src/main/java/org/openworkflow/sdk/impl/executors/EmitExecutor.java b/impl/core/src/main/java/org/openworkflow/sdk/impl/executors/EmitExecutor.java index 455d97119..0b3316c49 100644 --- a/impl/core/src/main/java/org/openworkflow/sdk/impl/executors/EmitExecutor.java +++ b/impl/core/src/main/java/org/openworkflow/sdk/impl/executors/EmitExecutor.java @@ -99,13 +99,12 @@ private CloudEvent buildCloudEvent(WorkflowContext workflow, TaskContext taskCon .sourceFilter() .map(filter -> filter.apply(workflow, taskContext, taskContext.input())) .map(URI::create) - .orElseGet( - () -> - workflow - .definition() - .application() - .defaultEventSource() - .apply(workflow, taskContext, taskContext.input()))); + .orElseGet(() -> + workflow + .definition() + .application() + .defaultEventSource() + .apply(workflow, taskContext, taskContext.input()))); ceBuilder.withType( props .typeFilter() diff --git a/impl/core/src/main/java/org/openworkflow/sdk/impl/executors/ForkExecutor.java b/impl/core/src/main/java/org/openworkflow/sdk/impl/executors/ForkExecutor.java index b51ad4b1b..0e3661cd1 100644 --- a/impl/core/src/main/java/org/openworkflow/sdk/impl/executors/ForkExecutor.java +++ b/impl/core/src/main/java/org/openworkflow/sdk/impl/executors/ForkExecutor.java @@ -80,21 +80,19 @@ protected CompletableFuture internalExecute( } return CompletableFuture.allOf( futures.values().toArray(new CompletableFuture[futures.size()])) - .thenApply( - i -> - combine( - workflow, - futures.entrySet().stream() - .collect(Collectors.toMap(Entry::getKey, e -> e.getValue().join())))); + .thenApply(i -> + combine( + workflow, + futures.entrySet().stream() + .collect(Collectors.toMap(Entry::getKey, e -> e.getValue().join())))); } private WorkflowModel combine(WorkflowContext context, Map futures) { Stream> sortedStream = futures.entrySet().stream() - .sorted( - (arg1, arg2) -> - arg1.getValue().completedAt().compareTo(arg2.getValue().completedAt())); + .sorted((arg1, arg2) -> + arg1.getValue().completedAt().compareTo(arg2.getValue().completedAt())); return compete ? sortedStream.map(e -> e.getValue().output()).findFirst().orElseThrow() : context diff --git a/impl/core/src/main/java/org/openworkflow/sdk/impl/executors/ListenExecutor.java b/impl/core/src/main/java/org/openworkflow/sdk/impl/executors/ListenExecutor.java index f9f0a0ccd..fd0b25196 100644 --- a/impl/core/src/main/java/org/openworkflow/sdk/impl/executors/ListenExecutor.java +++ b/impl/core/src/main/java/org/openworkflow/sdk/impl/executors/ListenExecutor.java @@ -128,15 +128,14 @@ protected EventRegistrationInfo buildInfo( untilRegBuilders, (ce, f) -> f.complete(null), eventConsumer, workflow, task); untilInfo .completableFuture() - .whenComplete( - (__, e) -> { - untilInfo.registrations().forEach(eventConsumer::unregister); - if (e == null) { - info.completableFuture().complete(null); - } else { - info.completableFuture().completeExceptionally(e); - } - }); + .whenComplete((__, e) -> { + untilInfo.registrations().forEach(eventConsumer::unregister); + if (e == null) { + info.completableFuture().complete(null); + } else { + info.completableFuture().completeExceptionally(e); + } + }); } return info; } @@ -191,10 +190,9 @@ protected CompletableFuture internalExecute( workflow.instance().addCancelable(info.completableFuture()); return info.completableFuture() .whenComplete((__, e) -> info.registrations().forEach(eventConsumer::unregister)) - .thenCompose( - __ -> - CompletableFuture.allOf( - waitingListeners.toArray(new CompletableFuture[waitingListeners.size()]))) + .thenCompose(__ -> + CompletableFuture.allOf( + waitingListeners.toArray(new CompletableFuture[waitingListeners.size()]))) .handle((__, ___) -> output); } @@ -225,10 +223,8 @@ private void processCe( taskContext.variables().put(at, arrayNode.size()); } TaskExecutorHelper.processTaskList(t, workflow, Optional.of(taskContext), node) - .thenAccept( - n -> - internalProcessCe( - n, arrayNode, workflow, taskContext, future, waitingListeners)); + .thenAccept(n -> + internalProcessCe(n, arrayNode, workflow, taskContext, future, waitingListeners)); }, () -> internalProcessCe(node, arrayNode, workflow, taskContext, future, waitingListeners)); } diff --git a/impl/core/src/main/java/org/openworkflow/sdk/impl/executors/RunScriptExecutorBuilder.java b/impl/core/src/main/java/org/openworkflow/sdk/impl/executors/RunScriptExecutorBuilder.java index 669729693..99f049549 100644 --- a/impl/core/src/main/java/org/openworkflow/sdk/impl/executors/RunScriptExecutorBuilder.java +++ b/impl/core/src/main/java/org/openworkflow/sdk/impl/executors/RunScriptExecutorBuilder.java @@ -77,10 +77,9 @@ public CallableTask build(RunScript taskConfiguration, WorkflowDefinition defini application.serviceLoadedClasses(ScriptRunner.class).stream() .filter(s -> s.identifier().equals(language)) .findFirst() - .orElseThrow( - () -> - new IllegalStateException( - "No script runner implementation found for language " + language))); + .orElseThrow(() -> + new IllegalStateException( + "No script runner implementation found for language " + language))); } @Override diff --git a/impl/core/src/main/java/org/openworkflow/sdk/impl/executors/RunShellExecutor.java b/impl/core/src/main/java/org/openworkflow/sdk/impl/executors/RunShellExecutor.java index ee6ed1d74..eecdd850d 100644 --- a/impl/core/src/main/java/org/openworkflow/sdk/impl/executors/RunShellExecutor.java +++ b/impl/core/src/main/java/org/openworkflow/sdk/impl/executors/RunShellExecutor.java @@ -76,28 +76,25 @@ public CompletableFuture apply( shellArguments.forEach(f -> commandAndArgs.add(f.apply(workflowContext, taskContext, model))); ProcessBuilder builder = new ProcessBuilder(commandAndArgs); - shellDirectory.ifPresent( - directory -> - builder.directory(new File(directory.apply(workflowContext, taskContext, model)))); + shellDirectory.ifPresent(directory -> + builder.directory(new File(directory.apply(workflowContext, taskContext, model)))); shellEnv.ifPresent( map -> ScriptUtils.addEnviromment(builder, map.apply(workflowContext, taskContext, model))); return returnType - .map( - type -> - CompletableFuture.supplyAsync( - () -> - ScriptUtils.buildResultFromProcess( - workflowContext.definition(), uncheckedStart(builder), type, model), - workflowContext.definition().application().executorService())) - .orElseGet( - () -> { - workflowContext - .definition() - .application() - .executorService() - .submit(() -> uncheckedStart(builder)); - return CompletableFuture.completedFuture(model); - }); + .map(type -> + CompletableFuture.supplyAsync( + () -> + ScriptUtils.buildResultFromProcess( + workflowContext.definition(), uncheckedStart(builder), type, model), + workflowContext.definition().application().executorService())) + .orElseGet(() -> { + workflowContext + .definition() + .application() + .executorService() + .submit(() -> uncheckedStart(builder)); + return CompletableFuture.completedFuture(model); + }); } } diff --git a/impl/core/src/main/java/org/openworkflow/sdk/impl/executors/RunTaskExecutor.java b/impl/core/src/main/java/org/openworkflow/sdk/impl/executors/RunTaskExecutor.java index bf831a2eb..2a7181847 100644 --- a/impl/core/src/main/java/org/openworkflow/sdk/impl/executors/RunTaskExecutor.java +++ b/impl/core/src/main/java/org/openworkflow/sdk/impl/executors/RunTaskExecutor.java @@ -41,10 +41,9 @@ protected RunTaskExecutorBuilder( .filter(r -> r.accept(config.getClass())) .findFirst() .map(r -> r.build(config, definition)) - .orElseThrow( - () -> - new UnsupportedOperationException( - "No runnable found for operation " + config.getClass())); + .orElseThrow(() -> + new UnsupportedOperationException( + "No runnable found for operation " + config.getClass())); } @Override diff --git a/impl/core/src/main/java/org/openworkflow/sdk/impl/executors/TaskExecutorHelper.java b/impl/core/src/main/java/org/openworkflow/sdk/impl/executors/TaskExecutorHelper.java index e17b08948..aa1b5bfe4 100644 --- a/impl/core/src/main/java/org/openworkflow/sdk/impl/executors/TaskExecutorHelper.java +++ b/impl/core/src/main/java/org/openworkflow/sdk/impl/executors/TaskExecutorHelper.java @@ -40,11 +40,10 @@ public static CompletableFuture processTaskList( WorkflowModel input) { return taskExecutor .apply(context, parentTask, input) - .thenApply( - t -> { - parentTask.ifPresent(p -> p.rawOutput(t.output())); - return t.output(); - }); + .thenApply(t -> { + parentTask.ifPresent(p -> p.rawOutput(t.output())); + return t.output(); + }); } public static boolean isActive(WorkflowContext context) { diff --git a/impl/core/src/main/java/org/openworkflow/sdk/impl/executors/TryExecutor.java b/impl/core/src/main/java/org/openworkflow/sdk/impl/executors/TryExecutor.java index f0012ae81..7abc97b1e 100644 --- a/impl/core/src/main/java/org/openworkflow/sdk/impl/executors/TryExecutor.java +++ b/impl/core/src/main/java/org/openworkflow/sdk/impl/executors/TryExecutor.java @@ -257,29 +257,27 @@ private CompletableFuture handleException( } if (catchTaskExecutor.isPresent()) { completable = - completable.thenCompose( - model -> - TaskExecutorHelper.processTaskList( - catchTaskExecutor.get(), workflow, Optional.of(taskContext), model)); + completable.thenCompose(model -> + TaskExecutorHelper.processTaskList( + catchTaskExecutor.get(), workflow, Optional.of(taskContext), model)); } if (retryIntervalExecutor.isPresent()) { completable = - completable.thenCompose( - model -> { - Optional> retryCompletable = - retryIntervalExecutor.orElseThrow().retry(workflow, taskContext, model); - if (retryCompletable.isPresent()) { - return retryCompletable - .orElseThrow() - .thenCompose(innerModel -> doIt(workflow, taskContext, innerModel)); - } else if (catchTransition.isPresent()) { - taskContext.transition(catchTransition.orElseThrow()); - return CompletableFuture.completedFuture(model); - } else { - return CompletableFuture.failedFuture(exception); - } - }); + completable.thenCompose(model -> { + Optional> retryCompletable = + retryIntervalExecutor.orElseThrow().retry(workflow, taskContext, model); + if (retryCompletable.isPresent()) { + return retryCompletable + .orElseThrow() + .thenCompose(innerModel -> doIt(workflow, taskContext, innerModel)); + } else if (catchTransition.isPresent()) { + taskContext.transition(catchTransition.orElseThrow()); + return CompletableFuture.completedFuture(model); + } else { + return CompletableFuture.failedFuture(exception); + } + }); } else { catchTransition.ifPresent(t -> taskContext.transition(t)); } diff --git a/impl/core/src/main/java/org/openworkflow/sdk/impl/executors/openapi/OpenAPIExecutor.java b/impl/core/src/main/java/org/openworkflow/sdk/impl/executors/openapi/OpenAPIExecutor.java index 5f10044da..ace70db0e 100644 --- a/impl/core/src/main/java/org/openworkflow/sdk/impl/executors/openapi/OpenAPIExecutor.java +++ b/impl/core/src/main/java/org/openworkflow/sdk/impl/executors/openapi/OpenAPIExecutor.java @@ -77,12 +77,9 @@ public CompletableFuture apply( while (iter.hasNext()) { final String uri = iter.next(); future = - future.exceptionallyCompose( - i -> - WorkflowHttpRequestHelper.executeRequest( - httpInfoBuilder.build(URI.create(uri)), - workflowContext, - taskContext)); + future.exceptionallyCompose(i -> + WorkflowHttpRequestHelper.executeRequest( + httpInfoBuilder.build(URI.create(uri)), workflowContext, taskContext)); } return future; }, diff --git a/impl/core/src/main/java/org/openworkflow/sdk/impl/executors/openapi/OpenAPIExecutorBuilder.java b/impl/core/src/main/java/org/openworkflow/sdk/impl/executors/openapi/OpenAPIExecutorBuilder.java index 6e4ea725c..7ff10ebc9 100644 --- a/impl/core/src/main/java/org/openworkflow/sdk/impl/executors/openapi/OpenAPIExecutorBuilder.java +++ b/impl/core/src/main/java/org/openworkflow/sdk/impl/executors/openapi/OpenAPIExecutorBuilder.java @@ -54,9 +54,8 @@ public CallableTaskFactory init( private UnifiedOpenAPIReader reader(WorkflowApplication app) { return app.additionalObject(UnifiedOpenAPIReader.UNIFIED_OPEN_API_READER) - .orElseThrow( - () -> - new IllegalStateException( - "Missing UnifiedOpenAPIReader, please make sure dependency openworkflow-impl-openapi is included")); + .orElseThrow(() -> + new IllegalStateException( + "Missing UnifiedOpenAPIReader, please make sure dependency openworkflow-impl-openapi is included")); } } diff --git a/impl/core/src/main/java/org/openworkflow/sdk/impl/executors/openapi/OpenAPIProcessor.java b/impl/core/src/main/java/org/openworkflow/sdk/impl/executors/openapi/OpenAPIProcessor.java index 006d83519..9267576c7 100644 --- a/impl/core/src/main/java/org/openworkflow/sdk/impl/executors/openapi/OpenAPIProcessor.java +++ b/impl/core/src/main/java/org/openworkflow/sdk/impl/executors/openapi/OpenAPIProcessor.java @@ -29,8 +29,7 @@ class OpenAPIProcessor { OperationDefinition parse(UnifiedOpenAPI unifiedOpenAPI) { Optional operationDefinition = unifiedOpenAPI.findOperationById(this.operationId); - return operationDefinition.orElseThrow( - () -> - new IllegalArgumentException("Operation with ID '" + this.operationId + "' not found")); + return operationDefinition.orElseThrow(() -> + new IllegalArgumentException("Operation with ID '" + this.operationId + "' not found")); } } diff --git a/impl/core/src/main/java/org/openworkflow/sdk/impl/executors/openapi/OperationDefinition.java b/impl/core/src/main/java/org/openworkflow/sdk/impl/executors/openapi/OperationDefinition.java index 33c50dd7a..bfaed8f03 100644 --- a/impl/core/src/main/java/org/openworkflow/sdk/impl/executors/openapi/OperationDefinition.java +++ b/impl/core/src/main/java/org/openworkflow/sdk/impl/executors/openapi/OperationDefinition.java @@ -74,24 +74,23 @@ List getParameters() { && operation.hasParameters()) { operation.parameters().stream() .filter(p -> "body".equals(p.in())) - .forEach( - p -> { - UnifiedOpenAPI.Schema schema = p.schema(); - if (schema != null && schema.hasRef()) { - String ref = schema.ref(); - schema = openAPI.resolveSchema(ref); - } - - if (schema != null && schema.hasProperties()) { - Map properties = schema.properties(); - for (String fieldName : properties.keySet()) { - UnifiedOpenAPI.Schema fieldSchema = properties.get(fieldName); - boolean isRequired = schema.requiredFields().contains(fieldName); - paramDefinitions.add( - new ParameterDefinition(fieldName, "body", isRequired, fieldSchema)); - } - } - }); + .forEach(p -> { + UnifiedOpenAPI.Schema schema = p.schema(); + if (schema != null && schema.hasRef()) { + String ref = schema.ref(); + schema = openAPI.resolveSchema(ref); + } + + if (schema != null && schema.hasProperties()) { + Map properties = schema.properties(); + for (String fieldName : properties.keySet()) { + UnifiedOpenAPI.Schema fieldSchema = properties.get(fieldName); + boolean isRequired = schema.requiredFields().contains(fieldName); + paramDefinitions.add( + new ParameterDefinition(fieldName, "body", isRequired, fieldSchema)); + } + } + }); } if (operation.hasRequestBody()) { diff --git a/impl/core/src/main/java/org/openworkflow/sdk/impl/http/DefaultHttpRequest.java b/impl/core/src/main/java/org/openworkflow/sdk/impl/http/DefaultHttpRequest.java index a84cf0d5a..3ed6769f9 100644 --- a/impl/core/src/main/java/org/openworkflow/sdk/impl/http/DefaultHttpRequest.java +++ b/impl/core/src/main/java/org/openworkflow/sdk/impl/http/DefaultHttpRequest.java @@ -68,10 +68,8 @@ public CompletableFuture invoke( httpInfo, builder::header, workflowContext, taskContext) .thenCompose( __ -> client.sendAsync(builder.build(), HttpResponse.BodyHandlers.ofByteArray())) - .exceptionallyCompose( - ex -> - CompletableFuture.failedFuture( - WorkflowHttpRequestHelper.fromError(ex, taskContext))) + .exceptionallyCompose(ex -> + CompletableFuture.failedFuture(WorkflowHttpRequestHelper.fromError(ex, taskContext))) .thenApply(response -> new DefaultHttpResponse(app, taskContext, response)); } @@ -92,20 +90,18 @@ private BodyPublisher buildBody() { case WorkflowHttpContentType.APPLICATION_JSON -> HttpRequest.BodyPublishers.ofByteArray( body.asJson() - .orElseThrow( - () -> - new IllegalStateException( - "Underlying model needs to support json in order to use application-json content type"))); + .orElseThrow(() -> + new IllegalStateException( + "Underlying model needs to support json in order to use application-json content type"))); case WorkflowHttpContentType.APPLICATION_X_WWW_FORM_URLENCODED -> HttpRequest.BodyPublishers.ofString( encodeMap( httpInfo .body() .asMap() - .orElseThrow( - () -> - new IllegalStateException( - "Underlying model needs to support asMap in order to use form urlencoded content type")), + .orElseThrow(() -> + new IllegalStateException( + "Underlying model needs to support asMap in order to use form urlencoded content type")), DefaultHttpRequest::encodeForm)); }; } diff --git a/impl/core/src/main/java/org/openworkflow/sdk/impl/http/WorkflowHttpRequestHelper.java b/impl/core/src/main/java/org/openworkflow/sdk/impl/http/WorkflowHttpRequestHelper.java index 7160faf68..afdf36dee 100644 --- a/impl/core/src/main/java/org/openworkflow/sdk/impl/http/WorkflowHttpRequestHelper.java +++ b/impl/core/src/main/java/org/openworkflow/sdk/impl/http/WorkflowHttpRequestHelper.java @@ -39,20 +39,18 @@ public static CompletableFuture executeRequest( WorkflowHttpRequestInfo requestInfo, WorkflowContext workflow, TaskContext taskContext) { return asWorkflowHtppResponse( requestInfo, workflow.definition().application(), workflow, taskContext) - .thenApply( - response -> { - try { - validateStatus(taskContext, requestInfo, response); - return response - .asWorkflowModel() - .orElseThrow( - () -> - new IllegalStateException( - "Unable to extract WorkflowModel from response " + response)); - } finally { - response.close(); - } - }); + .thenApply(response -> { + try { + validateStatus(taskContext, requestInfo, response); + return response + .asWorkflowModel() + .orElseThrow(() -> + new IllegalStateException( + "Unable to extract WorkflowModel from response " + response)); + } finally { + response.close(); + } + }); } public static CompletableFuture executeRequest( @@ -61,15 +59,14 @@ public static CompletableFuture executeRequest( WorkflowContext workflow, TaskContext taskContext) { return asWorkflowHtppResponse(requestInfo, app, workflow, taskContext) - .thenApply( - response -> { - try { - validateStatus(taskContext, requestInfo, response); - return response.asByteArray(); - } finally { - response.close(); - } - }); + .thenApply(response -> { + try { + validateStatus(taskContext, requestInfo, response); + return response.asByteArray(); + } finally { + response.close(); + } + }); } public static CompletableFuture asWorkflowHtppResponse( @@ -128,14 +125,13 @@ private static CompletableFuture addAuthHeader( TaskContext task) { String scheme = auth.scheme(); return auth.content(workflow, task, info.uri(), info.method()) - .thenAccept( - parameter -> { - if (task != null) { - task.authorization(scheme, parameter); - } - headerFiller.accept( - AuthUtils.AUTH_HEADER_NAME, AuthUtils.authHeaderValue(scheme, parameter)); - }); + .thenAccept(parameter -> { + if (task != null) { + task.authorization(scheme, parameter); + } + headerFiller.accept( + AuthUtils.AUTH_HEADER_NAME, AuthUtils.authHeaderValue(scheme, parameter)); + }); } private static boolean isSuccessful(int status) { diff --git a/impl/core/src/main/java/org/openworkflow/sdk/impl/marshaller/AbstractOutputBuffer.java b/impl/core/src/main/java/org/openworkflow/sdk/impl/marshaller/AbstractOutputBuffer.java index 7b0063b93..39a8cf3ec 100644 --- a/impl/core/src/main/java/org/openworkflow/sdk/impl/marshaller/AbstractOutputBuffer.java +++ b/impl/core/src/main/java/org/openworkflow/sdk/impl/marshaller/AbstractOutputBuffer.java @@ -47,11 +47,10 @@ public > WorkflowOutputBuffer writeEnum(T value) { @Override public WorkflowOutputBuffer writeMap(Map map) { writeInt(map.size()); - map.forEach( - (k, v) -> { - writeString(k); - writeObject(v); - }); + map.forEach((k, v) -> { + writeString(k); + writeObject(v); + }); return this; } diff --git a/impl/core/src/main/java/org/openworkflow/sdk/impl/resources/DefaultResourceLoader.java b/impl/core/src/main/java/org/openworkflow/sdk/impl/resources/DefaultResourceLoader.java index c06d0f252..7d3a04dfa 100644 --- a/impl/core/src/main/java/org/openworkflow/sdk/impl/resources/DefaultResourceLoader.java +++ b/impl/core/src/main/java/org/openworkflow/sdk/impl/resources/DefaultResourceLoader.java @@ -86,11 +86,10 @@ protected CompletableFuture loadURI( ? reload(resourceHandler, function, workflowContext, taskContext) : resourceHandler .shouldReload(cached.lastReload(), workflowContext, taskContext) - .thenCompose( - changed -> - changed - ? reload(resourceHandler, function, workflowContext, taskContext) - : CompletableFuture.completedFuture((T) cached.content())); + .thenCompose(changed -> + changed + ? reload(resourceHandler, function, workflowContext, taskContext) + : CompletableFuture.completedFuture((T) cached.content())); } private CompletableFuture reload( @@ -101,16 +100,15 @@ private CompletableFuture reload( Instant lastReload = Instant.now(); return resourceHandler .load(workflowContext, taskContext) - .thenApply( - bytes -> { - T content = function.apply(resourceHandler.name(), bytes); - resourceCache.compute( - resourceHandler, - (k, v) -> - v == null || v.lastReload().isBefore(lastReload) - ? new CachedResource(lastReload, content) - : v); - return content; - }); + .thenApply(bytes -> { + T content = function.apply(resourceHandler.name(), bytes); + resourceCache.compute( + resourceHandler, + (k, v) -> + v == null || v.lastReload().isBefore(lastReload) + ? new CachedResource(lastReload, content) + : v); + return content; + }); } } diff --git a/impl/core/src/main/java/org/openworkflow/sdk/impl/resources/HttpResource.java b/impl/core/src/main/java/org/openworkflow/sdk/impl/resources/HttpResource.java index aa80229ab..d6e28edee 100644 --- a/impl/core/src/main/java/org/openworkflow/sdk/impl/resources/HttpResource.java +++ b/impl/core/src/main/java/org/openworkflow/sdk/impl/resources/HttpResource.java @@ -71,13 +71,12 @@ public CompletableFuture shouldReload( application, workflowContext, taskContext) - .thenApply( - response -> { - try (response) { - return response.status() != HttpURLConnection.HTTP_NOT_MODIFIED - && checkLastModified(response.lastModified(), millis); - } - }); + .thenApply(response -> { + try (response) { + return response.status() != HttpURLConnection.HTTP_NOT_MODIFIED + && checkLastModified(response.lastModified(), millis); + } + }); } private boolean checkLastModified(OptionalLong lastModified, long millis) { diff --git a/impl/core/src/main/java/org/openworkflow/sdk/impl/scheduler/DefaultWorkflowScheduler.java b/impl/core/src/main/java/org/openworkflow/sdk/impl/scheduler/DefaultWorkflowScheduler.java index 791919323..8ce1859c3 100644 --- a/impl/core/src/main/java/org/openworkflow/sdk/impl/scheduler/DefaultWorkflowScheduler.java +++ b/impl/core/src/main/java/org/openworkflow/sdk/impl/scheduler/DefaultWorkflowScheduler.java @@ -54,13 +54,12 @@ public CronResolverCancellable(WorkflowDefinition definition, CronResolver cronR private void scheduleNext() { cronResolver .nextExecution() - .ifPresent( - d -> - nextCron.set( - service.schedule( - new CronResolverIntanceRunner(definition), - d.toMillis(), - TimeUnit.MILLISECONDS))); + .ifPresent(d -> + nextCron.set( + service.schedule( + new CronResolverIntanceRunner(definition), + d.toMillis(), + TimeUnit.MILLISECONDS))); } @Override diff --git a/impl/core/src/main/java/org/openworkflow/sdk/impl/scheduler/ScheduledEventConsumer.java b/impl/core/src/main/java/org/openworkflow/sdk/impl/scheduler/ScheduledEventConsumer.java index c8d2775db..7f50f5145 100644 --- a/impl/core/src/main/java/org/openworkflow/sdk/impl/scheduler/ScheduledEventConsumer.java +++ b/impl/core/src/main/java/org/openworkflow/sdk/impl/scheduler/ScheduledEventConsumer.java @@ -59,11 +59,10 @@ public ScheduledEventConsumer( Collection registrationBuilders = builderInfo.registrations().registrations(); allStrategyCorrelationInfo.init(registrationBuilders, this::start); - registrationBuilders.forEach( - reg -> - registrations.add( - eventConsumer.register( - reg, ce -> allStrategyCorrelationInfo.correlate(reg, (CloudEvent) ce)))); + registrationBuilders.forEach(reg -> + registrations.add( + eventConsumer.register( + reg, ce -> allStrategyCorrelationInfo.correlate(reg, (CloudEvent) ce)))); } else { builderInfo .registrations() diff --git a/impl/core/src/main/java/org/openworkflow/sdk/impl/scheduler/ScheduledInstanceRunnable.java b/impl/core/src/main/java/org/openworkflow/sdk/impl/scheduler/ScheduledInstanceRunnable.java index 1b3ca419f..ae0aed7f9 100644 --- a/impl/core/src/main/java/org/openworkflow/sdk/impl/scheduler/ScheduledInstanceRunnable.java +++ b/impl/core/src/main/java/org/openworkflow/sdk/impl/scheduler/ScheduledInstanceRunnable.java @@ -52,19 +52,17 @@ private static void runScheduledInstance( definition .application() .executorService() - .execute( - () -> - instance - .start() - .whenComplete( - (model, ex) -> { - if (ex != null) { - logger.error( - "Scheduled workflow instance {} of definition {} has failed", - instance.id(), - definition.id(), - ex); - } - })); + .execute(() -> + instance + .start() + .whenComplete((model, ex) -> { + if (ex != null) { + logger.error( + "Scheduled workflow instance {} of definition {} has failed", + instance.id(), + definition.id(), + ex); + } + })); } } diff --git a/impl/core/src/main/java/org/openworkflow/sdk/impl/schema/AbstractSchemaValidator.java b/impl/core/src/main/java/org/openworkflow/sdk/impl/schema/AbstractSchemaValidator.java index 0b6f70c4a..e7f7b5509 100644 --- a/impl/core/src/main/java/org/openworkflow/sdk/impl/schema/AbstractSchemaValidator.java +++ b/impl/core/src/main/java/org/openworkflow/sdk/impl/schema/AbstractSchemaValidator.java @@ -33,16 +33,14 @@ public Optional validate(WorkflowModel model) { return validate( model .as(validationClass) - .orElseThrow( - () -> - new IllegalStateException( - "Model cannot be converted to proper schema validation class " - + validationClass))) - .map( - s -> - WorkflowError.error(Errors.VALIDATION.toString(), Errors.VALIDATION.status()) - .title("Schema validation errors") - .details(s)); + .orElseThrow(() -> + new IllegalStateException( + "Model cannot be converted to proper schema validation class " + + validationClass))) + .map(s -> + WorkflowError.error(Errors.VALIDATION.toString(), Errors.VALIDATION.status()) + .title("Schema validation errors") + .details(s)); } protected abstract Optional validate(T object); diff --git a/impl/http/src/main/java/org/openworkflow/sdk/impl/jakarta/http/JakartaRequestExecutor.java b/impl/http/src/main/java/org/openworkflow/sdk/impl/jakarta/http/JakartaRequestExecutor.java index 7de745728..08ee26796 100644 --- a/impl/http/src/main/java/org/openworkflow/sdk/impl/jakarta/http/JakartaRequestExecutor.java +++ b/impl/http/src/main/java/org/openworkflow/sdk/impl/jakarta/http/JakartaRequestExecutor.java @@ -84,23 +84,21 @@ public CompletableFuture invoke( } return WorkflowHttpRequestHelper.processAuth( requestInfo, request::header, workflowContext, taskContext) - .thenCompose( - __ -> - doRequest( - request, - HttpConverterResolver.converter(application, workflowContext, taskContext), - taskContext)) - .exceptionallyCompose( - ex -> - ex instanceof WebApplicationException webAppEx - ? CompletableFuture.failedFuture( - new WorkflowException( - WorkflowError.communication( - webAppEx.getResponse().getStatus(), taskContext, webAppEx) - .build(), - webAppEx)) - : CompletableFuture.failedFuture( - WorkflowHttpRequestHelper.fromError(ex, taskContext))); + .thenCompose(__ -> + doRequest( + request, + HttpConverterResolver.converter(application, workflowContext, taskContext), + taskContext)) + .exceptionallyCompose(ex -> + ex instanceof WebApplicationException webAppEx + ? CompletableFuture.failedFuture( + new WorkflowException( + WorkflowError.communication( + webAppEx.getResponse().getStatus(), taskContext, webAppEx) + .build(), + webAppEx)) + : CompletableFuture.failedFuture( + WorkflowHttpRequestHelper.fromError(ex, taskContext))); } private Entity buildBody(HttpModelConverter converter) { @@ -115,10 +113,9 @@ private Entity
buildForm() { requestInfo .body() .asMap() - .orElseThrow( - () -> - new IllegalStateException( - "Workflow model should support asMap in order form_url_enconded to work")) + .orElseThrow(() -> + new IllegalStateException( + "Workflow model should support asMap in order form_url_enconded to work")) .forEach((k, v) -> form.param(k, v == null ? "" : v.toString())); return Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED); } diff --git a/impl/jq/src/main/java/org/openworkflow/sdk/impl/expressions/jq/JQExpression.java b/impl/jq/src/main/java/org/openworkflow/sdk/impl/expressions/jq/JQExpression.java index e45c49790..42a5982af 100644 --- a/impl/jq/src/main/java/org/openworkflow/sdk/impl/expressions/jq/JQExpression.java +++ b/impl/jq/src/main/java/org/openworkflow/sdk/impl/expressions/jq/JQExpression.java @@ -41,12 +41,10 @@ public class JQExpression implements ObjectExpression { private final Supplier scope; - private final String expr; private final net.thisptr.jackson.jq.Expression internalExpr; public JQExpression(Supplier scope, String expr, Version version) throws JsonQueryException { - this.expr = expr; this.scope = scope; this.internalExpr = ExpressionParser.compile(expr, version); } @@ -106,15 +104,14 @@ private Scope createScope(WorkflowContext workflow, TaskContext task) { if (workflow != null) { childScope.setValue( "secret", - new FunctionJsonNode( - k -> { - Map secret = - workflow.definition().application().secretManager().secret(k); - if (secret.isEmpty()) { - throw new WorkflowException(WorkflowError.authorization().build()); - } - return secret; - })); + new FunctionJsonNode(k -> { + Map secret = + workflow.definition().application().secretManager().secret(k); + if (secret.isEmpty()) { + throw new WorkflowException(WorkflowError.authorization().build()); + } + return secret; + })); childScope.setValue("context", modelToJson(workflow.context())); childScope.setValue( "runtime", diff --git a/impl/model/src/main/java/org/openworkflow/sdk/impl/model/jackson/JacksonModelFactory.java b/impl/model/src/main/java/org/openworkflow/sdk/impl/model/jackson/JacksonModelFactory.java index c654da045..5d37c9ad9 100644 --- a/impl/model/src/main/java/org/openworkflow/sdk/impl/model/jackson/JacksonModelFactory.java +++ b/impl/model/src/main/java/org/openworkflow/sdk/impl/model/jackson/JacksonModelFactory.java @@ -41,17 +41,14 @@ public class JacksonModelFactory implements WorkflowModelFactory { public WorkflowModel combine(Map workflowVariables) { return new JacksonModelCollection( workflowVariables.entrySet().stream() - .map( - e -> - JsonUtils.object() - .set( - e.getKey(), - e.getValue() - .as(JsonNode.class) - .orElseThrow( - () -> - new IllegalArgumentException( - "Model cannot be converted ")))) + .map(e -> + JsonUtils.object() + .set( + e.getKey(), + e.getValue() + .as(JsonNode.class) + .orElseThrow( + () -> new IllegalArgumentException("Model cannot be converted ")))) .collect(JsonUtils.arrayNodeCollector())); } diff --git a/impl/persistence/api/src/main/java/org/openworkflow/sdk/impl/persistence/AbstractAllStrategyCorrelationInfo.java b/impl/persistence/api/src/main/java/org/openworkflow/sdk/impl/persistence/AbstractAllStrategyCorrelationInfo.java index ca8c6d03f..77c3c4bd2 100644 --- a/impl/persistence/api/src/main/java/org/openworkflow/sdk/impl/persistence/AbstractAllStrategyCorrelationInfo.java +++ b/impl/persistence/api/src/main/java/org/openworkflow/sdk/impl/persistence/AbstractAllStrategyCorrelationInfo.java @@ -66,12 +66,11 @@ public void correlate(EventRegistrationBuilder reg, CloudEvent event) { public void init( Collection regs, Consumer> starter) { - regs.forEach( - reg -> { - String id = generateIdFromReg(reg); - id2RegMapping.put(id, reg); - reg2IdMapping.put(reg, id); - }); + regs.forEach(reg -> { + String id = generateIdFromReg(reg); + id2RegMapping.put(id, reg); + reg2IdMapping.put(reg, id); + }); this.starter = starter; queueCorrelation(operations -> startupCheck(operations), starter); } @@ -84,14 +83,11 @@ private void queueCorrelation( this.completableFuture = completableFuture .thenCompose(v -> executor.execute(() -> doTransaction(function), definition)) - .exceptionally( - ex -> { - logger.error( - "Exception processing correlation task for definition {}", - definition.id(), - ex); - return List.of(); - }); + .exceptionally(ex -> { + logger.error( + "Exception processing correlation task for definition {}", definition.id(), ex); + return List.of(); + }); completableFuture.thenAccept(events -> events.forEach(starter)); } } diff --git a/impl/persistence/api/src/main/java/org/openworkflow/sdk/impl/persistence/WorkflowPersistenceInstance.java b/impl/persistence/api/src/main/java/org/openworkflow/sdk/impl/persistence/WorkflowPersistenceInstance.java index 96a244b29..3c35cb642 100644 --- a/impl/persistence/api/src/main/java/org/openworkflow/sdk/impl/persistence/WorkflowPersistenceInstance.java +++ b/impl/persistence/api/src/main/java/org/openworkflow/sdk/impl/persistence/WorkflowPersistenceInstance.java @@ -43,28 +43,26 @@ private WorkflowPersistenceInstance(WorkflowDefinition definition, PersistenceWo super(definition, info.id(), info.input()); this.info = info; info.tasks() - .forEach( - (k, v) -> { - if (v instanceof CompletedTaskInfo task) { - iterationsMap.put(k, task.iteration()); - } - }); + .forEach((k, v) -> { + if (v instanceof CompletedTaskInfo task) { + iterationsMap.put(k, task.iteration()); + } + }); this.startedAt = info.startedAt(); additionalObjects.putAll(info.metadata()); } @Override public CompletableFuture start() { - return startExecution( - () -> { - if (info.status() == WorkflowStatus.SUSPENDED) { - setSuspended(); - setStatus(WorkflowStatus.SUSPENDED); - } else { - setStatus(WorkflowStatus.RUNNING); - } - return CompletableFuture.completedFuture(null); - }); + return startExecution(() -> { + if (info.status() == WorkflowStatus.SUSPENDED) { + setSuspended(); + setStatus(WorkflowStatus.SUSPENDED); + } else { + setStatus(WorkflowStatus.RUNNING); + } + return CompletableFuture.completedFuture(null); + }); } @Override @@ -107,13 +105,12 @@ public void restoreContext(WorkflowContext workflow, TaskContext context) { retainKeys = new HashSet<>(userMetaKeys); taskInfo .additionalObjects() - .forEach( - (k, v) -> { - if (!retainKeys.contains(k)) { - additionalObjects.put(k, v); - retainKeys.add(k); - } - }); + .forEach((k, v) -> { + if (!retainKeys.contains(k)) { + additionalObjects.put(k, v); + retainKeys.add(k); + } + }); additionalObjects.keySet().retainAll(retainKeys); } } diff --git a/impl/persistence/api/src/main/java/org/openworkflow/sdk/impl/persistence/hashing/HashMappingCoordinator.java b/impl/persistence/api/src/main/java/org/openworkflow/sdk/impl/persistence/hashing/HashMappingCoordinator.java index da2de21ee..d78fed29b 100644 --- a/impl/persistence/api/src/main/java/org/openworkflow/sdk/impl/persistence/hashing/HashMappingCoordinator.java +++ b/impl/persistence/api/src/main/java/org/openworkflow/sdk/impl/persistence/hashing/HashMappingCoordinator.java @@ -144,12 +144,11 @@ public void persist() { if (instanceMap != null) { synchronized (instanceMap) { item.getValue() - .forEach( - v -> { - if (v.bytes.isTransient()) { - list.add(from(v)); - } - }); + .forEach(v -> { + if (v.bytes.isTransient()) { + list.add(from(v)); + } + }); } } if (!list.isEmpty()) { diff --git a/impl/persistence/api/src/main/java/org/openworkflow/sdk/impl/persistence/metadata/PersistenceMetaUtils.java b/impl/persistence/api/src/main/java/org/openworkflow/sdk/impl/persistence/metadata/PersistenceMetaUtils.java index 09025e84a..af61281c9 100644 --- a/impl/persistence/api/src/main/java/org/openworkflow/sdk/impl/persistence/metadata/PersistenceMetaUtils.java +++ b/impl/persistence/api/src/main/java/org/openworkflow/sdk/impl/persistence/metadata/PersistenceMetaUtils.java @@ -28,10 +28,9 @@ private PersistenceMetaUtils() {} public static Stream> durableMetadataAsStream( WorkflowInstanceData instance) { return instance.metadata().entrySet().stream() - .filter( - e -> - e.getValue() != null - && !e.getValue().getClass().isAnnotationPresent(MetaTransient.class)); + .filter(e -> + e.getValue() != null + && !e.getValue().getClass().isAnnotationPresent(MetaTransient.class)); } public static Map durableMetadata(WorkflowInstanceData instance) { diff --git a/impl/persistence/api/src/test/java/org/openworkflow/sdk/impl/persistence/hashing/HashMappingCoordinatorTest.java b/impl/persistence/api/src/test/java/org/openworkflow/sdk/impl/persistence/hashing/HashMappingCoordinatorTest.java index 9cd0c9d42..3bfd1a302 100644 --- a/impl/persistence/api/src/test/java/org/openworkflow/sdk/impl/persistence/hashing/HashMappingCoordinatorTest.java +++ b/impl/persistence/api/src/test/java/org/openworkflow/sdk/impl/persistence/hashing/HashMappingCoordinatorTest.java @@ -113,17 +113,15 @@ void setUp() { lastWrittenData.clear(); lastWrittenData.putAll(data); // Simulate persistence - data.forEach( - (instanceId, mappings) -> { - Map> instanceMap = - persistedData.computeIfAbsent(instanceId, k -> new HashMap<>()); - mappings.forEach( - mapping -> { - instanceMap - .computeIfAbsent(mapping.item().key(), k -> new HashMap<>()) - .put(mapping.index(), mapping.bytes()); - }); - }); + data.forEach((instanceId, mappings) -> { + Map> instanceMap = + persistedData.computeIfAbsent(instanceId, k -> new HashMap<>()); + mappings.forEach(mapping -> { + instanceMap + .computeIfAbsent(mapping.item().key(), k -> new HashMap<>()) + .put(mapping.index(), mapping.bytes()); + }); + }); }); } diff --git a/impl/persistence/bigmap/src/main/java/org/openworkflow/sdk/impl/persistence/bigmap/BigMapInstanceTransaction.java b/impl/persistence/bigmap/src/main/java/org/openworkflow/sdk/impl/persistence/bigmap/BigMapInstanceTransaction.java index 944584316..3537a68c6 100644 --- a/impl/persistence/bigmap/src/main/java/org/openworkflow/sdk/impl/persistence/bigmap/BigMapInstanceTransaction.java +++ b/impl/persistence/bigmap/src/main/java/org/openworkflow/sdk/impl/persistence/bigmap/BigMapInstanceTransaction.java @@ -70,10 +70,9 @@ public Stream scanAll( Map status = status(definition); return instances.entrySet().stream() .filter(e -> testAppl(applicationData, e.getKey(), applicationId)) - .map( - e -> - readPersistenceInfo( - e.getKey(), e.getValue(), tasks(e.getKey()), status.get(e.getKey()))); + .map(e -> + readPersistenceInfo( + e.getKey(), e.getValue(), tasks(e.getKey()), status.get(e.getKey()))); } private boolean testAppl(Map applicationData, String key, String applicationId) { @@ -114,16 +113,15 @@ public void clearStatus(WorkflowContextData workflowContext) { public void retrieveEvents(Map> events) { events .entrySet() - .forEach( - e -> { - String regId = e.getKey(); - Collection ces = e.getValue(); - Map processedCes = processedCloudEvents(regId); - cloudEvents(regId).values().stream() - .map(this::unmarshallCloudEvent) - .filter(ce -> !processedCes.containsKey(ce.getId())) - .forEach(ces::add); - }); + .forEach(e -> { + String regId = e.getKey(); + Collection ces = e.getValue(); + Map processedCes = processedCloudEvents(regId); + cloudEvents(regId).values().stream() + .map(this::unmarshallCloudEvent) + .filter(ce -> !processedCes.containsKey(ce.getId())) + .forEach(ces::add); + }); } @Override @@ -133,11 +131,10 @@ public void storeEvent(String regId, CloudEvent event) { @Override public void markAsProcessed(Map> regCeIds) { - regCeIds.forEach( - (k, v) -> { - Map processed = processedCloudEvents(k); - v.forEach(id -> processed.put(id, processedValue())); - }); + regCeIds.forEach((k, v) -> { + Map processed = processedCloudEvents(k); + v.forEach(id -> processed.put(id, processedValue())); + }); } @Override diff --git a/impl/persistence/bigmap/src/main/java/org/openworkflow/sdk/impl/persistence/bigmap/BytesMapInstanceTransaction.java b/impl/persistence/bigmap/src/main/java/org/openworkflow/sdk/impl/persistence/bigmap/BytesMapInstanceTransaction.java index 7ea1e9b13..020f5f17d 100644 --- a/impl/persistence/bigmap/src/main/java/org/openworkflow/sdk/impl/persistence/bigmap/BytesMapInstanceTransaction.java +++ b/impl/persistence/bigmap/src/main/java/org/openworkflow/sdk/impl/persistence/bigmap/BytesMapInstanceTransaction.java @@ -133,11 +133,10 @@ protected byte[] marshallTaskCompleted(WorkflowContextData contextData, TaskCont private void writeMetadata(WorkflowInstanceData instanceData, WorkflowOutputBuffer writer) { Map additionalObjects = PersistenceMetaUtils.durableMetadata(instanceData); writer.writeInt(additionalObjects.size()); - additionalObjects.forEach( - (k, v) -> { - writer.writeString(k); - writeLargeObject(instanceData, writer, v); - }); + additionalObjects.forEach((k, v) -> { + writer.writeString(k); + writeLargeObject(instanceData, writer, v); + }); } private void writeLargeObject( @@ -290,18 +289,17 @@ private void writeLargeObject( private Object readLargeObject(String instanceId, WorkflowInputBuffer buffer) { return hashFactory .fromBuffer(buffer.readByte(), buffer) - .map( - item -> { - try (WorkflowInputBuffer input = - bufferFactory.input( - new ByteArrayInputStream( - hashCoordinator - .readBytes( - instanceId, item, hashFactory.indexFromBytes(buffer.readBytes())) - .orElseThrow()))) { - return input.readObject(); - } - }) + .map(item -> { + try (WorkflowInputBuffer input = + bufferFactory.input( + new ByteArrayInputStream( + hashCoordinator + .readBytes( + instanceId, item, hashFactory.indexFromBytes(buffer.readBytes())) + .orElseThrow()))) { + return input.readObject(); + } + }) .orElseGet(() -> buffer.readObject()); } diff --git a/impl/persistence/tests/src/main/java/org/openworkflow/sdk/impl/persistence/test/AbstractCorrelationPersistenceTest.java b/impl/persistence/tests/src/main/java/org/openworkflow/sdk/impl/persistence/test/AbstractCorrelationPersistenceTest.java index 44dc5cbc4..dc97d78ac 100644 --- a/impl/persistence/tests/src/main/java/org/openworkflow/sdk/impl/persistence/test/AbstractCorrelationPersistenceTest.java +++ b/impl/persistence/tests/src/main/java/org/openworkflow/sdk/impl/persistence/test/AbstractCorrelationPersistenceTest.java @@ -73,10 +73,8 @@ void testAllStrategy() { await() .pollDelay(Duration.ofMillis(50)) .atMost(Duration.ofSeconds(maxSeconds2Wait())) - .until( - () -> - instances.stream().filter(i -> i.status() == WorkflowStatus.COMPLETED).count() - == 1); + .until(() -> + instances.stream().filter(i -> i.status() == WorkflowStatus.COMPLETED).count() == 1); assertThat((Collection) assertThat(instances).singleElement().actual().output().asJavaObject()) .containsExactlyInAnyOrder("Javierito", "Fulanito"); } diff --git a/impl/persistence/tests/src/main/java/org/openworkflow/sdk/impl/persistence/test/AbstractHandlerPersistenceTest.java b/impl/persistence/tests/src/main/java/org/openworkflow/sdk/impl/persistence/test/AbstractHandlerPersistenceTest.java index 62dca3e04..e413bfebc 100644 --- a/impl/persistence/tests/src/main/java/org/openworkflow/sdk/impl/persistence/test/AbstractHandlerPersistenceTest.java +++ b/impl/persistence/tests/src/main/java/org/openworkflow/sdk/impl/persistence/test/AbstractHandlerPersistenceTest.java @@ -68,7 +68,7 @@ private record TransientMeta(String useless) {} protected HashFactory hashFactory; private Instant beforeStart; - @BeforeAll() + @BeforeAll static void init() throws IOException { app = WorkflowApplication.builder().build(); definition = app.workflowDefinition(readWorkflowFromClasspath("simple-expression.yaml")); diff --git a/impl/pom.xml b/impl/pom.xml index 38d90cc51..59ef34958 100644 --- a/impl/pom.xml +++ b/impl/pom.xml @@ -16,8 +16,8 @@ 4.0.3 9.2.1 3.7.1 - 25.4.4.1.1 - 1.4.0.Final + 25.5.5.0.3 + 1.5.0.Final 2.15.0 diff --git a/impl/test/src/test/java/org/openworkflow/sdk/impl/test/BasicAuthHttpTest.java b/impl/test/src/test/java/org/openworkflow/sdk/impl/test/BasicAuthHttpTest.java index eb009f440..1d7aeeaae 100644 --- a/impl/test/src/test/java/org/openworkflow/sdk/impl/test/BasicAuthHttpTest.java +++ b/impl/test/src/test/java/org/openworkflow/sdk/impl/test/BasicAuthHttpTest.java @@ -42,11 +42,10 @@ public class BasicAuthHttpTest { static void init() { app = WorkflowApplication.builder() - .withSecretManager( - k -> - k.equals("mySecret") - ? Map.of("username", "Javierito", "password", "Vicentito") - : Map.of()) + .withSecretManager(k -> + k.equals("mySecret") + ? Map.of("username", "Javierito", "password", "Vicentito") + : Map.of()) .build(); } diff --git a/impl/test/src/test/java/org/openworkflow/sdk/impl/test/ConcurrentStartTest.java b/impl/test/src/test/java/org/openworkflow/sdk/impl/test/ConcurrentStartTest.java index 54d9915e5..41623cafc 100644 --- a/impl/test/src/test/java/org/openworkflow/sdk/impl/test/ConcurrentStartTest.java +++ b/impl/test/src/test/java/org/openworkflow/sdk/impl/test/ConcurrentStartTest.java @@ -82,14 +82,13 @@ private List> raceStart(WorkflowInstance instan try { CompletableFuture[] racers = IntStream.range(0, RACERS) - .mapToObj( - i -> - CompletableFuture.runAsync( - () -> { - await(barrier); - results.add(instance.start()); - }, - pool)) + .mapToObj(i -> + CompletableFuture.runAsync( + () -> { + await(barrier); + results.add(instance.start()); + }, + pool)) .toArray(CompletableFuture[]::new); CompletableFuture.allOf(racers).join(); } finally { diff --git a/impl/test/src/test/java/org/openworkflow/sdk/impl/test/CoreTaskTypesTest.java b/impl/test/src/test/java/org/openworkflow/sdk/impl/test/CoreTaskTypesTest.java index f393c43ff..c26e0cc4a 100644 --- a/impl/test/src/test/java/org/openworkflow/sdk/impl/test/CoreTaskTypesTest.java +++ b/impl/test/src/test/java/org/openworkflow/sdk/impl/test/CoreTaskTypesTest.java @@ -136,11 +136,10 @@ private static Workflow forCollectWorkflow() { .in(".input") .at("index") .input(i -> i.from("{input: .input, output: []}")) - .tasks( - t -> - t.set( - "sumIndex", - s -> s.put("output", "${.output+[$number+$index+1]}")))))) + .tasks(t -> + t.set( + "sumIndex", + s -> s.put("output", "${.output+[$number+$index+1]}")))))) .build(); } @@ -182,14 +181,13 @@ private static Workflow forSumWorkflow() { f -> f.each("number") .in(".input") - .tasks( - t -> - t.set( - "accumulate", - (SetTaskBuilder s) -> - s.put("counter", "${.counter+$number}") - .exportAs( - "if .incr==null then {incr:[$number+1]} else .incr+=[$number+1] end"))) + .tasks(t -> + t.set( + "accumulate", + (SetTaskBuilder s) -> + s.put("counter", "${.counter+$number}") + .exportAs( + "if .incr==null then {incr:[$number+1]} else .incr+=[$number+1] end"))) .output(o -> o.as(".counter"))))) .build(); } @@ -466,17 +464,16 @@ private static Workflow raiseReusableWorkflow() { return WorkflowBuilder.workflow("raise-reusable-dsl", "test", "0.1.0") .use( use() - .errors( - e -> - e.error( - "notImplemented", - err -> - err.type( - "https://open-workflow-specification.org/1.0.0/errors/not-implemented") - .status(500) - .title("Not Implemented") - .detail( - "${ \"The workflow '\\( $workflow.definition.document.name ):\\( $workflow.definition.document.version )' is a work in progress and cannot be run yet\" }")))) + .errors(e -> + e.error( + "notImplemented", + err -> + err.type( + "https://open-workflow-specification.org/1.0.0/errors/not-implemented") + .status(500) + .title("Not Implemented") + .detail( + "${ \"The workflow '\\( $workflow.definition.document.name ):\\( $workflow.definition.document.version )' is a work in progress and cannot be run yet\" }")))) .tasks(doTasks(raise("notImplemented", r -> r.error("notImplemented")))) .build(); } diff --git a/impl/test/src/test/java/org/openworkflow/sdk/impl/test/CorrelationTest.java b/impl/test/src/test/java/org/openworkflow/sdk/impl/test/CorrelationTest.java index 97121c07c..01c3bcac7 100644 --- a/impl/test/src/test/java/org/openworkflow/sdk/impl/test/CorrelationTest.java +++ b/impl/test/src/test/java/org/openworkflow/sdk/impl/test/CorrelationTest.java @@ -74,12 +74,11 @@ void testCorrelateMatch(String sourceName, Workflow workflow) throws Exception { .untilAsserted(() -> assertThat(instance.status()).isEqualTo(WorkflowStatus.WAITING)); appl.eventPublishers() - .forEach( - p -> - p.publish( - buildCloudEvent( - "com.example.hospital.patient.admitted", - Map.of("patientId", "P123", "name", "John")))); + .forEach(p -> + p.publish( + buildCloudEvent( + "com.example.hospital.patient.admitted", + Map.of("patientId", "P123", "name", "John")))); WorkflowModel result = future.get(2, TimeUnit.SECONDS); Object outputValue = JsonUtils.toJavaValue(JsonUtils.modelToJson(result)); @@ -113,18 +112,14 @@ private static Workflow listenCorrelateWorkflow() { listen( "waitForPatient", l -> - l.to( - listenTo -> - listenTo.one( - filter -> - filter - .with( - props -> - props.type( - "com.example.hospital.patient.admitted")) - .correlate( - "patientId", - cp -> cp.from(".data.patientId").expect(".id"))))))) + l.to(listenTo -> + listenTo.one(filter -> + filter + .with(props -> + props.type("com.example.hospital.patient.admitted")) + .correlate( + "patientId", + cp -> cp.from(".data.patientId").expect(".id"))))))) .build(); } @@ -139,21 +134,19 @@ private void assertCorrelateNoMatch(Workflow workflow) throws Exception { .untilAsserted(() -> assertThat(instance.status()).isEqualTo(WorkflowStatus.WAITING)); appl.eventPublishers() - .forEach( - p -> - p.publish( - buildCloudEvent( - "com.example.hospital.patient.admitted", - Map.of("patientId", "P456", "name", "Jane")))); + .forEach(p -> + p.publish( + buildCloudEvent( + "com.example.hospital.patient.admitted", + Map.of("patientId", "P456", "name", "Jane")))); await() .during(Duration.ofMillis(200)) .atMost(Duration.ofSeconds(3)) - .untilAsserted( - () -> { - assertThat(instance.status()).isEqualTo(WorkflowStatus.WAITING); - assertThat(future.isDone()).isFalse(); - }); + .untilAsserted(() -> { + assertThat(instance.status()).isEqualTo(WorkflowStatus.WAITING); + assertThat(future.isDone()).isFalse(); + }); instance.cancel(); } @@ -173,17 +166,12 @@ private static Workflow listenCorrelateNoExpectWorkflow() { listen( "waitForPatient", l -> - l.to( - listenTo -> - listenTo.one( - filter -> - filter - .with( - props -> - props.type( - "com.example.hospital.patient.admitted")) - .correlate( - "patientId", cp -> cp.from(".data.patientId"))))))) + l.to(listenTo -> + listenTo.one(filter -> + filter + .with(props -> + props.type("com.example.hospital.patient.admitted")) + .correlate("patientId", cp -> cp.from(".data.patientId"))))))) .build(); } @@ -207,12 +195,11 @@ void testCorrelateNoExpectMatch(String sourceName, Workflow workflow) throws Exc .untilAsserted(() -> assertThat(instance.status()).isEqualTo(WorkflowStatus.WAITING)); appl.eventPublishers() - .forEach( - p -> - p.publish( - buildCloudEvent( - "com.example.hospital.patient.admitted", - Map.of("patientId", "P123", "name", "John")))); + .forEach(p -> + p.publish( + buildCloudEvent( + "com.example.hospital.patient.admitted", + Map.of("patientId", "P123", "name", "John")))); WorkflowModel result = future.get(2, TimeUnit.SECONDS); Object outputValue = JsonUtils.toJavaValue(JsonUtils.modelToJson(result)); @@ -239,11 +226,9 @@ void testCorrelateNoExpectMismatchThenMatch(String sourceName, Workflow workflow .untilAsserted(() -> assertThat(instance.status()).isEqualTo(WorkflowStatus.WAITING)); appl.eventPublishers() - .forEach( - p -> - p.publish( - buildCloudEvent( - "com.example.hospital.patient.admitted", Map.of("name", "Jane")))); + .forEach(p -> + p.publish( + buildCloudEvent("com.example.hospital.patient.admitted", Map.of("name", "Jane")))); await() .during(Duration.ofMillis(200)) @@ -251,28 +236,24 @@ void testCorrelateNoExpectMismatchThenMatch(String sourceName, Workflow workflow .untilAsserted(() -> assertThat(instance.status()).isEqualTo(WorkflowStatus.WAITING)); appl.eventPublishers() - .forEach( - p -> - p.publish( - buildCloudEvent( - "com.example.hospital.patient.admitted", Map.of("name", "Alice")))); + .forEach(p -> + p.publish( + buildCloudEvent("com.example.hospital.patient.admitted", Map.of("name", "Alice")))); await() .during(Duration.ofMillis(200)) .atMost(Duration.ofSeconds(3)) - .untilAsserted( - () -> { - assertThat(instance.status()).isEqualTo(WorkflowStatus.WAITING); - assertThat(future.isDone()).isFalse(); - }); + .untilAsserted(() -> { + assertThat(instance.status()).isEqualTo(WorkflowStatus.WAITING); + assertThat(future.isDone()).isFalse(); + }); appl.eventPublishers() - .forEach( - p -> - p.publish( - buildCloudEvent( - "com.example.hospital.patient.admitted", - Map.of("patientId", "P123", "name", "Bob")))); + .forEach(p -> + p.publish( + buildCloudEvent( + "com.example.hospital.patient.admitted", + Map.of("patientId", "P123", "name", "Bob")))); WorkflowModel result = future.get(2, TimeUnit.SECONDS); Object outputValue = JsonUtils.toJavaValue(JsonUtils.modelToJson(result)); diff --git a/impl/test/src/test/java/org/openworkflow/sdk/impl/test/CustomAuthProviderFactoryOverrideTest.java b/impl/test/src/test/java/org/openworkflow/sdk/impl/test/CustomAuthProviderFactoryOverrideTest.java index 9f6bad210..c4ae85c36 100644 --- a/impl/test/src/test/java/org/openworkflow/sdk/impl/test/CustomAuthProviderFactoryOverrideTest.java +++ b/impl/test/src/test/java/org/openworkflow/sdk/impl/test/CustomAuthProviderFactoryOverrideTest.java @@ -45,10 +45,10 @@ public class CustomAuthProviderFactoryOverrideTest { private static final String RESPONSE = """ - { - "message": "Hello World" - } - """; + { + "message": "Hello World" + } + """; private MockWebServer authServer; private MockWebServer apiServer; diff --git a/impl/test/src/test/java/org/openworkflow/sdk/impl/test/CustomFunctionTest.java b/impl/test/src/test/java/org/openworkflow/sdk/impl/test/CustomFunctionTest.java index a675180cf..f8475b8fd 100644 --- a/impl/test/src/test/java/org/openworkflow/sdk/impl/test/CustomFunctionTest.java +++ b/impl/test/src/test/java/org/openworkflow/sdk/impl/test/CustomFunctionTest.java @@ -46,20 +46,18 @@ static void cleanup() { @Test void testCustomFunction() { - assertThatThrownBy( - () -> - app.workflowDefinition( - readWorkflowFromClasspath( - "workflows-samples/call-custom-function-inline.yaml")) - .instance(Map.of()) - .start() - .join()) + assertThatThrownBy(() -> + app.workflowDefinition( + readWorkflowFromClasspath("workflows-samples/call-custom-function-inline.yaml")) + .instance(Map.of()) + .start() + .join()) .hasCauseInstanceOf(WorkflowException.class) .extracting(w -> ((WorkflowException) w.getCause()).getWorkflowError().status()) .isEqualTo(404); } - @DisabledIfPythonUnavailable() + @DisabledIfPythonUnavailable @ParameterizedTest @ValueSource( strings = { diff --git a/impl/test/src/test/java/org/openworkflow/sdk/impl/test/DigestAuthHttpTest.java b/impl/test/src/test/java/org/openworkflow/sdk/impl/test/DigestAuthHttpTest.java index 47cc48efd..877564759 100644 --- a/impl/test/src/test/java/org/openworkflow/sdk/impl/test/DigestAuthHttpTest.java +++ b/impl/test/src/test/java/org/openworkflow/sdk/impl/test/DigestAuthHttpTest.java @@ -45,11 +45,10 @@ public class DigestAuthHttpTest { static void init() { app = WorkflowApplication.builder() - .withSecretManager( - k -> - k.equals("mySecret") - ? Map.of("username", "Mufasa", "password", "Circle Of Life") - : Map.of()) + .withSecretManager(k -> + k.equals("mySecret") + ? Map.of("username", "Mufasa", "password", "Circle Of Life") + : Map.of()) .build(); } diff --git a/impl/test/src/test/java/org/openworkflow/sdk/impl/test/EmitExecutorTest.java b/impl/test/src/test/java/org/openworkflow/sdk/impl/test/EmitExecutorTest.java index 3ae7c5798..2f813a20e 100644 --- a/impl/test/src/test/java/org/openworkflow/sdk/impl/test/EmitExecutorTest.java +++ b/impl/test/src/test/java/org/openworkflow/sdk/impl/test/EmitExecutorTest.java @@ -121,16 +121,14 @@ void whenAppHasDefaultEventSource_itOverridesCalculatedDefault() throws IOExcept void whenExplicitSourceInEventDefinition_itTakesPrecedenceOverAllDefaults() throws IOException { Workflow wf = WorkflowBuilder.workflow("emit-explicit-source", "my.ns", "1.2.3") - .tasks( - t -> - t.emit( - "emitEvent", - etb -> - etb.event( - epb -> { - epb.type("org.example.event"); - epb.source("explicit/source"); - }))) + .tasks(t -> + t.emit( + "emitEvent", + etb -> + etb.event(epb -> { + epb.type("org.example.event"); + epb.source("explicit/source"); + }))) .build(); List events = @@ -150,9 +148,8 @@ void whenDefaultEventSourceIsResolver_uriIsResolvedFromWorkflowContext() throws wf, "org.example.event", b -> - b.withDefaultEventSource( - (workflow, task, model) -> - URI.create("apps/" + workflow.definition().id().name()))); + b.withDefaultEventSource((workflow, task, model) -> + URI.create("apps/" + workflow.definition().id().name()))); assertThat(events).hasSize(1); CloudEvent ev = events.get(0); diff --git a/impl/test/src/test/java/org/openworkflow/sdk/impl/test/HTTPWorkflowDefinitionTest.java b/impl/test/src/test/java/org/openworkflow/sdk/impl/test/HTTPWorkflowDefinitionTest.java index 77c794a09..df92a96ed 100644 --- a/impl/test/src/test/java/org/openworkflow/sdk/impl/test/HTTPWorkflowDefinitionTest.java +++ b/impl/test/src/test/java/org/openworkflow/sdk/impl/test/HTTPWorkflowDefinitionTest.java @@ -65,10 +65,8 @@ public CallableTask build(CallableTask delegate) { long init = System.currentTimeMillis(); CompletableFuture result = delegate.apply(w, t, n); if (logger.isDebugEnabled()) { - result.thenAccept( - x -> - logger.debug( - "Http calls takes {} milliseconds", System.currentTimeMillis() - init)); + result.thenAccept(x -> + logger.debug("Http calls takes {} milliseconds", System.currentTimeMillis() - init)); } return result; }; @@ -130,20 +128,16 @@ void callHttpGet_should_return_pet_data(WorkflowApplication app) throws Exceptio .instance(Map.of("petId", 10)) .start() .join(); - SoftAssertions.assertSoftly( - softly -> { - softly - .assertThat(result.asMap().orElseThrow()) - .containsKey("petId") - .containsKey("photoUrls"); - try { - RecordedRequest recordedRequest = mockServer.takeRequest(); - softly.assertThat(recordedRequest.getUrl()).asString().contains("/pets/10"); - softly.assertThat(recordedRequest.getMethod()).isEqualTo("GET"); - } catch (InterruptedException e) { - softly.fail(e); - } - }); + SoftAssertions.assertSoftly(softly -> { + softly.assertThat(result.asMap().orElseThrow()).containsKey("petId").containsKey("photoUrls"); + try { + RecordedRequest recordedRequest = mockServer.takeRequest(); + softly.assertThat(recordedRequest.getUrl()).asString().contains("/pets/10"); + softly.assertThat(recordedRequest.getMethod()).isEqualTo("GET"); + } catch (InterruptedException e) { + softly.fail(e); + } + }); } @ParameterizedTest(autoCloseArguments = false) @@ -155,8 +149,8 @@ void callHttpGet_with_not_found_petId_should_keep_input_petId(WorkflowApplicatio 404, Headers.of("Content-Type", "application/json"), """ - {"message": "Pet not found"} - """)); + {"message": "Pet not found"} + """)); WorkflowModel result = app.workflowDefinition(readWorkflowFromClasspath("workflows-samples/call-http-get.yaml")) .instance(Map.of("petId", "-1")) @@ -164,12 +158,11 @@ void callHttpGet_with_not_found_petId_should_keep_input_petId(WorkflowApplicatio .join(); RecordedRequest recordedRequest = mockServer.takeRequest(); - SoftAssertions.assertSoftly( - softly -> { - softly.assertThat(result.asMap().orElseThrow()).containsKey("petId"); - softly.assertThat(recordedRequest.getUrl()).asString().contains("/pets/-1"); - softly.assertThat(recordedRequest.getMethod()).isEqualTo("GET"); - }); + SoftAssertions.assertSoftly(softly -> { + softly.assertThat(result.asMap().orElseThrow()).containsKey("petId"); + softly.assertThat(recordedRequest.getUrl()).asString().contains("/pets/-1"); + softly.assertThat(recordedRequest.getMethod()).isEqualTo("GET"); + }); } @ParameterizedTest(autoCloseArguments = false) @@ -197,15 +190,11 @@ void callHttpEndpointInterpolation_should_work(WorkflowApplication app) throws E .join(); RecordedRequest recordedRequest = mockServer.takeRequest(); - SoftAssertions.assertSoftly( - softly -> { - softly - .assertThat(result.asMap().orElseThrow()) - .containsKey("petId") - .containsKey("photoUrls"); - softly.assertThat(recordedRequest.getUrl()).asString().contains("/pets/1994"); - softly.assertThat(recordedRequest.getMethod()).isEqualTo("GET"); - }); + SoftAssertions.assertSoftly(softly -> { + softly.assertThat(result.asMap().orElseThrow()).containsKey("petId").containsKey("photoUrls"); + softly.assertThat(recordedRequest.getUrl()).asString().contains("/pets/1994"); + softly.assertThat(recordedRequest.getMethod()).isEqualTo("GET"); + }); } @ParameterizedTest(autoCloseArguments = false) @@ -234,15 +223,14 @@ void callHttpQueryParameters_should_find_star_trek_movie(WorkflowApplication app .join(); RecordedRequest recordedRequest = mockServer.takeRequest(); - SoftAssertions.assertSoftly( - softly -> { - Map response = result.asMap().orElseThrow(); - softly.assertThat(response).containsKey("movie"); - var movie = (Map) response.get("movie"); - softly.assertThat(movie).containsEntry("title", "Star Trek"); - softly.assertThat(recordedRequest.getUrl()).asString().contains("uid=MOMA0000092393"); - softly.assertThat(recordedRequest.getMethod()).isEqualTo("GET"); - }); + SoftAssertions.assertSoftly(softly -> { + Map response = result.asMap().orElseThrow(); + softly.assertThat(response).containsKey("movie"); + var movie = (Map) response.get("movie"); + softly.assertThat(movie).containsEntry("title", "Star Trek"); + softly.assertThat(recordedRequest.getUrl()).asString().contains("uid=MOMA0000092393"); + softly.assertThat(recordedRequest.getMethod()).isEqualTo("GET"); + }); } @ParameterizedTest(autoCloseArguments = false) @@ -276,12 +264,11 @@ void callHttpFindByStatus_should_return_non_empty_collection(WorkflowApplication .join(); RecordedRequest recordedRequest = mockServer.takeRequest(); - SoftAssertions.assertSoftly( - softly -> { - softly.assertThat(result.asCollection()).isNotEmpty(); - softly.assertThat(recordedRequest.getUrl()).asString().contains("status=sold"); - softly.assertThat(recordedRequest.getMethod()).isEqualTo("GET"); - }); + SoftAssertions.assertSoftly(softly -> { + softly.assertThat(result.asCollection()).isNotEmpty(); + softly.assertThat(recordedRequest.getUrl()).asString().contains("status=sold"); + softly.assertThat(recordedRequest.getMethod()).isEqualTo("GET"); + }); } @ParameterizedTest(autoCloseArguments = false) @@ -293,14 +280,14 @@ void callHttpQueryParameters_external_schema_should_find_star_trek(WorkflowAppli 200, Headers.of("Content-Type", "application/json"), """ - { - "movie": { - "uid": "MOMA0000092393", - "title": "Star Trek", - "director": "J.J. Abrams" - } - } - """)); + { + "movie": { + "uid": "MOMA0000092393", + "title": "Star Trek", + "director": "J.J. Abrams" + } + } + """)); WorkflowModel result = app.workflowDefinition( @@ -310,15 +297,14 @@ void callHttpQueryParameters_external_schema_should_find_star_trek(WorkflowAppli .join(); RecordedRequest recordedRequest = mockServer.takeRequest(); - SoftAssertions.assertSoftly( - softly -> { - Map response = result.asMap().orElseThrow(); - softly.assertThat(response).containsKey("movie"); - var movie = (Map) response.get("movie"); - softly.assertThat(movie).containsEntry("title", "Star Trek"); - softly.assertThat(recordedRequest.getUrl()).asString().contains("uid=MOMA0000092393"); - softly.assertThat(recordedRequest.getMethod()).isEqualTo("GET"); - }); + SoftAssertions.assertSoftly(softly -> { + Map response = result.asMap().orElseThrow(); + softly.assertThat(response).containsKey("movie"); + var movie = (Map) response.get("movie"); + softly.assertThat(movie).containsEntry("title", "Star Trek"); + softly.assertThat(recordedRequest.getUrl()).asString().contains("uid=MOMA0000092393"); + softly.assertThat(recordedRequest.getMethod()).isEqualTo("GET"); + }); } @ParameterizedTest(autoCloseArguments = false) @@ -329,10 +315,10 @@ void callHttpPost_should_return_created_firstName(WorkflowApplication app) throw 200, Headers.of("Content-Type", "application/json"), """ - { - "firstName": "Javierito" - } - """)); + { + "firstName": "Javierito" + } + """)); WorkflowModel result = app.workflowDefinition(readWorkflowFromClasspath("workflows-samples/call-http-post.yaml")) .instance(Map.of("name", "Javierito", "surname", "Unknown")) @@ -340,16 +326,15 @@ void callHttpPost_should_return_created_firstName(WorkflowApplication app) throw .join(); RecordedRequest recordedRequest = mockServer.takeRequest(); - SoftAssertions.assertSoftly( - softly -> { - softly.assertThat(result.asText().orElseThrow()).isEqualTo("Javierito"); - softly.assertThat(recordedRequest.getMethod()).isEqualTo("POST"); - softly.assertThat(recordedRequest.getBody()).isNotNull(); - softly - .assertThat(recordedRequest.getBody().string(StandardCharsets.UTF_8)) - .contains("\"firstName\":\"Javierito\"") - .contains("\"lastName\":\"Unknown\""); - }); + SoftAssertions.assertSoftly(softly -> { + softly.assertThat(result.asText().orElseThrow()).isEqualTo("Javierito"); + softly.assertThat(recordedRequest.getMethod()).isEqualTo("POST"); + softly.assertThat(recordedRequest.getBody()).isNotNull(); + softly + .assertThat(recordedRequest.getBody().string(StandardCharsets.UTF_8)) + .contains("\"firstName\":\"Javierito\"") + .contains("\"lastName\":\"Unknown\""); + }); } @ParameterizedTest(autoCloseArguments = false) @@ -357,21 +342,19 @@ void callHttpPost_should_return_created_firstName(WorkflowApplication app) throw void callHttpPost_without_body_should_not_throw(WorkflowApplication app) throws Exception { mockServer.enqueue(new MockResponse(204, Headers.of(), "")); - assertDoesNotThrow( - () -> - app.workflowDefinition( - readWorkflowFromClasspath("workflows-samples/call-http-post-no-body.yaml")) - .instance(Map.of()) - .start() - .join()); + assertDoesNotThrow(() -> + app.workflowDefinition( + readWorkflowFromClasspath("workflows-samples/call-http-post-no-body.yaml")) + .instance(Map.of()) + .start() + .join()); RecordedRequest recordedRequest = mockServer.takeRequest(); - SoftAssertions.assertSoftly( - softly -> { - softly.assertThat(recordedRequest.getMethod()).isEqualTo("POST"); - softly.assertThat(recordedRequest.getUrl()).asString().contains("/api/v1/authors"); - softly.assertThat(recordedRequest.getBodySize()).isEqualTo(0); - }); + SoftAssertions.assertSoftly(softly -> { + softly.assertThat(recordedRequest.getMethod()).isEqualTo("POST"); + softly.assertThat(recordedRequest.getUrl()).asString().contains("/api/v1/authors"); + softly.assertThat(recordedRequest.getBodySize()).isEqualTo(0); + }); } @ParameterizedTest(autoCloseArguments = false) @@ -386,12 +369,11 @@ void testCallHttpDelete(WorkflowApplication app) throws IOException, Interrupted .join(); RecordedRequest recordedRequest = mockServer.takeRequest(); - SoftAssertions.assertSoftly( - softly -> { - softly.assertThat(model).isNotNull(); - softly.assertThat(recordedRequest.getMethod()).isEqualTo("DELETE"); - softly.assertThat(recordedRequest.getUrl()).asString().contains("/api/v1/authors/1"); - }); + SoftAssertions.assertSoftly(softly -> { + softly.assertThat(model).isNotNull(); + softly.assertThat(recordedRequest.getMethod()).isEqualTo("DELETE"); + softly.assertThat(recordedRequest.getUrl()).asString().contains("/api/v1/authors/1"); + }); } @ParameterizedTest(autoCloseArguments = false) @@ -415,15 +397,14 @@ void callHttpPut_should_contain_firstName_with_john(WorkflowApplication app) thr .join(); RecordedRequest recordedRequest = mockServer.takeRequest(); - SoftAssertions.assertSoftly( - softly -> { - softly.assertThat(result.asText().orElseThrow()).contains("John"); - softly.assertThat(recordedRequest.getMethod()).contains("PUT"); - softly - .assertThat(recordedRequest.getBody().string(StandardCharsets.UTF_8)) - .contains("\"firstName\":\"John\""); - softly.assertThat(recordedRequest.getUrl()).asString().contains("api/v1/authors/1"); - }); + SoftAssertions.assertSoftly(softly -> { + softly.assertThat(result.asText().orElseThrow()).contains("John"); + softly.assertThat(recordedRequest.getMethod()).contains("PUT"); + softly + .assertThat(recordedRequest.getBody().string(StandardCharsets.UTF_8)) + .contains("\"firstName\":\"John\""); + softly.assertThat(recordedRequest.getUrl()).asString().contains("api/v1/authors/1"); + }); } @ParameterizedTest(autoCloseArguments = false) @@ -459,20 +440,18 @@ void testHeadCall(WorkflowApplication app) throws InterruptedException { "CustomValue")), "")); - assertDoesNotThrow( - () -> { - app.workflowDefinition(readWorkflowFromClasspath("workflows-samples/call-http-head.yaml")) - .instance(Map.of()) - .start() - .join(); - }); + assertDoesNotThrow(() -> { + app.workflowDefinition(readWorkflowFromClasspath("workflows-samples/call-http-head.yaml")) + .instance(Map.of()) + .start() + .join(); + }); RecordedRequest recordedRequest = mockServer.takeRequest(); - SoftAssertions.assertSoftly( - softly -> { - softly.assertThat(recordedRequest.getMethod()).isEqualTo("HEAD"); - softly.assertThat(recordedRequest.getUrl().toString()).contains("/users/1"); - }); + SoftAssertions.assertSoftly(softly -> { + softly.assertThat(recordedRequest.getMethod()).isEqualTo("HEAD"); + softly.assertThat(recordedRequest.getUrl().toString()).contains("/users/1"); + }); } @ParameterizedTest(autoCloseArguments = false) @@ -485,11 +464,10 @@ void testOptionsCall(WorkflowApplication app) throws IOException, InterruptedExc .join(); RecordedRequest recordedRequest = mockServer.takeRequest(); - SoftAssertions.assertSoftly( - softly -> { - softly.assertThat(recordedRequest.getMethod()).isEqualTo("OPTIONS"); - softly.assertThat(recordedRequest.getUrl().toString()).contains("/users/1"); - }); + SoftAssertions.assertSoftly(softly -> { + softly.assertThat(recordedRequest.getMethod()).isEqualTo("OPTIONS"); + softly.assertThat(recordedRequest.getUrl().toString()).contains("/users/1"); + }); } @ParameterizedTest(autoCloseArguments = false) @@ -505,11 +483,10 @@ void testPatchCall(WorkflowApplication app) throws IOException, InterruptedExcep .join(); RecordedRequest recordedRequest = mockServer.takeRequest(); - SoftAssertions.assertSoftly( - softly -> { - softly.assertThat(recordedRequest.getMethod()).isEqualTo("PATCH"); - softly.assertThat(recordedRequest.getUrl().toString()).contains("/users/1"); - }); + SoftAssertions.assertSoftly(softly -> { + softly.assertThat(recordedRequest.getMethod()).isEqualTo("PATCH"); + softly.assertThat(recordedRequest.getUrl().toString()).contains("/users/1"); + }); } @ParameterizedTest(autoCloseArguments = false) diff --git a/impl/test/src/test/java/org/openworkflow/sdk/impl/test/LifeCycleEventsTest.java b/impl/test/src/test/java/org/openworkflow/sdk/impl/test/LifeCycleEventsTest.java index c47a37d7d..9a1af323a 100644 --- a/impl/test/src/test/java/org/openworkflow/sdk/impl/test/LifeCycleEventsTest.java +++ b/impl/test/src/test/java/org/openworkflow/sdk/impl/test/LifeCycleEventsTest.java @@ -78,7 +78,6 @@ static void init() { for (String type : AbstractLifeCyclePublisher.getLifeCycleTypes()) { eventBroker.register(type, ce -> publishedEvents.add(ce)); } - ; appl = WorkflowApplication.builder() .withLifeCycleCloudEventFactory(new InputOutputLifeCycleCloudEventFactory()) @@ -141,11 +140,10 @@ void testApplicationIdExtension() throws IOException { assertThat(appl.id()).isNotBlank(); assertThat(publishedEvents) .isNotEmpty() - .allSatisfy( - ce -> - assertThat(ce.getExtension(APPLICATION_ID_EXTENSION)) - .as("%s extension of %s", APPLICATION_ID_EXTENSION, ce.getType()) - .isEqualTo(appl.id())); + .allSatisfy(ce -> + assertThat(ce.getExtension(APPLICATION_ID_EXTENSION)) + .as("%s extension of %s", APPLICATION_ID_EXTENSION, ce.getType()) + .isEqualTo(appl.id())); } @ParameterizedTest(name = "{0}") diff --git a/impl/test/src/test/java/org/openworkflow/sdk/impl/test/MvStorePersistenceTest.java b/impl/test/src/test/java/org/openworkflow/sdk/impl/test/MvStorePersistenceTest.java index fd7d5f1a1..c6869fd20 100644 --- a/impl/test/src/test/java/org/openworkflow/sdk/impl/test/MvStorePersistenceTest.java +++ b/impl/test/src/test/java/org/openworkflow/sdk/impl/test/MvStorePersistenceTest.java @@ -130,11 +130,10 @@ private void runIt(String dbName, WorkflowStatus expectedStatus) throws IOExcept assertThat(definition.activeInstances()).containsExactlyElementsOf(instances); assertThat(instances) .singleElement() - .satisfies( - instance -> { - assertThat(instance.status()).isEqualTo(expectedStatus); - assertThat(taskCounter.taskCounter(instance.id()).completed()).isEqualTo(0); - }); + .satisfies(instance -> { + assertThat(instance.status()).isEqualTo(expectedStatus); + assertThat(taskCounter.taskCounter(instance.id()).completed()).isEqualTo(0); + }); } } } diff --git a/impl/test/src/test/java/org/openworkflow/sdk/impl/test/OAuthHTTPWorkflowDefinitionTest.java b/impl/test/src/test/java/org/openworkflow/sdk/impl/test/OAuthHTTPWorkflowDefinitionTest.java index ab4199aa5..5bc66c835 100644 --- a/impl/test/src/test/java/org/openworkflow/sdk/impl/test/OAuthHTTPWorkflowDefinitionTest.java +++ b/impl/test/src/test/java/org/openworkflow/sdk/impl/test/OAuthHTTPWorkflowDefinitionTest.java @@ -47,20 +47,20 @@ public class OAuthHTTPWorkflowDefinitionTest { private static final String RESPONSE = """ - { - "message": "Hello World" - } - """; + { + "message": "Hello World" + } + """; String TOKEN_RESPONSE_TEMPLATE = """ - { - "access_token": "%s", - "token_type": "Bearer", - "expires_in": 3600, - "scope": "read write" - } - """; + { + "access_token": "%s", + "token_type": "Bearer", + "expires_in": 3600, + "scope": "read write" + } + """; private static WorkflowApplication defaultApp; private static WorkflowApplication jakartaApp; diff --git a/impl/test/src/test/java/org/openworkflow/sdk/impl/test/OpenAPITest.java b/impl/test/src/test/java/org/openworkflow/sdk/impl/test/OpenAPITest.java index 98b3a5cfb..08ac2273c 100644 --- a/impl/test/src/test/java/org/openworkflow/sdk/impl/test/OpenAPITest.java +++ b/impl/test/src/test/java/org/openworkflow/sdk/impl/test/OpenAPITest.java @@ -60,49 +60,49 @@ public class OpenAPITest { private static String PROJECT_JSON_SUCCESS = """ - { - "success": true, - "data": { - "id": 55504, - "name": "CRM", - "code": "crm-20251111", - "ownerId": 12345, - "members": [ - 12345, - 67890 - ], - "created_at": "2025-09-20T00:58:50.170784Z" - } - } - """; + { + "success": true, + "data": { + "id": 55504, + "name": "CRM", + "code": "crm-20251111", + "ownerId": 12345, + "members": [ + 12345, + 67890 + ], + "created_at": "2025-09-20T00:58:50.170784Z" + } + } + """; private static String PROJECT_JSON_FALSE = """ - { - "success": false, - "error": { - "code": "PROJECT_CONFLICT", - "message": "A project with the code crm-2025 already exists.", - "details": null - } - } - """; + { + "success": false, + "error": { + "code": "PROJECT_CONFLICT", + "message": "A project with the code crm-2025 already exists.", + "details": null + } + } + """; private static String PROJECT_GET_JSON_POSITIVE = """ - { - "success": true, - "data": { - "id": 40099, - "name": "Severus Calix", - "email": "severus.calix@hive-terra.example.com" - }, - "meta": { - "request_id": "req_terra123def456", - "timestamp": "999.M41-01-20T12:00:00Z" - } - } - """; + { + "success": true, + "data": { + "id": 40099, + "name": "Severus Calix", + "email": "severus.calix@hive-terra.example.com" + }, + "meta": { + "request_id": "req_terra123def456", + "timestamp": "999.M41-01-20T12:00:00Z" + } + } + """; @BeforeAll static void init() throws IOException { diff --git a/impl/test/src/test/java/org/openworkflow/sdk/impl/test/OpenIDCHTTPWorkflowDefinitionTest.java b/impl/test/src/test/java/org/openworkflow/sdk/impl/test/OpenIDCHTTPWorkflowDefinitionTest.java index f8803a34b..f540fb3ba 100644 --- a/impl/test/src/test/java/org/openworkflow/sdk/impl/test/OpenIDCHTTPWorkflowDefinitionTest.java +++ b/impl/test/src/test/java/org/openworkflow/sdk/impl/test/OpenIDCHTTPWorkflowDefinitionTest.java @@ -48,20 +48,20 @@ public class OpenIDCHTTPWorkflowDefinitionTest { private static final String RESPONSE = """ - { - "message": "Hello World" - } - """; + { + "message": "Hello World" + } + """; String TOKEN_RESPONSE_TEMPLATE = """ - { - "access_token": "%s", - "token_type": "Bearer", - "expires_in": 3600, - "scope": "read write" - } - """; + { + "access_token": "%s", + "token_type": "Bearer", + "expires_in": 3600, + "scope": "read write" + } + """; @BeforeAll static void init() { diff --git a/impl/test/src/test/java/org/openworkflow/sdk/impl/test/RetryTimeoutTest.java b/impl/test/src/test/java/org/openworkflow/sdk/impl/test/RetryTimeoutTest.java index 66c05097e..2795873fd 100644 --- a/impl/test/src/test/java/org/openworkflow/sdk/impl/test/RetryTimeoutTest.java +++ b/impl/test/src/test/java/org/openworkflow/sdk/impl/test/RetryTimeoutTest.java @@ -155,13 +155,12 @@ void testRetryDo() throws IOException { .start(); Awaitility.await() .atMost(Duration.ofSeconds(1)) - .until( - () -> - future - .join() - .asMap() - .orElseThrow() - .equals(Map.of("setAfterFailingTask", "No problem"))); + .until(() -> + future + .join() + .asMap() + .orElseThrow() + .equals(Map.of("setAfterFailingTask", "No problem"))); assertThat(retryListener.taskCompleted.get("do/0/attemptTask/try")).isEqualTo((short) 0); assertThat(retryListener.taskCompleted) @@ -176,14 +175,12 @@ void testRetryEnd() throws IOException { apiServer.enqueue(new MockResponse().setResponseCode(404)); apiServer.enqueue(new MockResponse().setResponseCode(404)); apiServer.enqueue(new MockResponse().setResponseCode(404)); - assertThatThrownBy( - () -> - app.workflowDefinition( - readWorkflowFromClasspath( - "workflows-samples/try-catch-retry-reusable.yaml")) - .instance(Map.of()) - .start() - .join()) + assertThatThrownBy(() -> + app.workflowDefinition( + readWorkflowFromClasspath("workflows-samples/try-catch-retry-reusable.yaml")) + .instance(Map.of()) + .start() + .join()) .hasCauseInstanceOf(WorkflowException.class); } @@ -195,14 +192,13 @@ void testAttemptDuration() throws IOException { .setResponseCode(200) .setHeader("Content-Type", "application/json") .setBody("{}")); - assertThatThrownBy( - () -> - app.workflowDefinition( - readWorkflowFromClasspath( - "workflows-samples/try-catch-retry-attempt-duration.yaml")) - .instance(Map.of()) - .start() - .join()) + assertThatThrownBy(() -> + app.workflowDefinition( + readWorkflowFromClasspath( + "workflows-samples/try-catch-retry-attempt-duration.yaml")) + .instance(Map.of()) + .start() + .join()) .hasCauseInstanceOf(WorkflowException.class); } @@ -289,14 +285,13 @@ void testAttemptDurationOverall() throws IOException { .setResponseCode(200) .setHeader("Content-Type", "application/json") .setBody(result)); - assertThatThrownBy( - () -> - app.workflowDefinition( - readWorkflowFromClasspath( - "workflows-samples/try-catch-retry-attempt-duration-overall.yaml")) - .instance(Map.of()) - .start() - .join()) + assertThatThrownBy(() -> + app.workflowDefinition( + readWorkflowFromClasspath( + "workflows-samples/try-catch-retry-attempt-duration-overall.yaml")) + .instance(Map.of()) + .start() + .join()) .hasCauseInstanceOf(WorkflowException.class); } @@ -341,12 +336,11 @@ void testDoesMatch(String path) throws IOException { "workflows-samples/try-catch-not-match-details.yaml" }) void testDoesNotMatch(String path) { - assertThatThrownBy( - () -> - app.workflowDefinition(readWorkflowFromClasspath(path)) - .instance(Map.of()) - .start() - .join()) + assertThatThrownBy(() -> + app.workflowDefinition(readWorkflowFromClasspath(path)) + .instance(Map.of()) + .start() + .join()) .hasCauseInstanceOf(WorkflowException.class); } diff --git a/impl/test/src/test/java/org/openworkflow/sdk/impl/test/RunScriptJavaScriptTest.java b/impl/test/src/test/java/org/openworkflow/sdk/impl/test/RunScriptJavaScriptTest.java index de0a833ef..2e9b843f7 100644 --- a/impl/test/src/test/java/org/openworkflow/sdk/impl/test/RunScriptJavaScriptTest.java +++ b/impl/test/src/test/java/org/openworkflow/sdk/impl/test/RunScriptJavaScriptTest.java @@ -54,11 +54,10 @@ void testConsoleLog() throws IOException { try (WorkflowApplication appl = WorkflowApplication.builder().build()) { WorkflowModel model = appl.workflowDefinition(workflow).instance(Map.of()).start().join(); - SoftAssertions.assertSoftly( - softly -> { - softly.assertThat(model.asText()).isPresent(); - softly.assertThat(model.asText().get()).isEqualTo("hello from script"); - }); + SoftAssertions.assertSoftly(softly -> { + softly.assertThat(model.asText()).isPresent(); + softly.assertThat(model.asText().get()).isEqualTo("hello from script"); + }); } } @@ -70,11 +69,10 @@ void testConsoleLogWithArgs() throws IOException { try (WorkflowApplication appl = WorkflowApplication.builder().build()) { WorkflowModel model = appl.workflowDefinition(workflow).instance(Map.of()).start().join(); - SoftAssertions.assertSoftly( - softly -> { - softly.assertThat(model.asText()).isPresent(); - softly.assertThat(model.asText().get()).isEqualTo("Hello, world!"); - }); + SoftAssertions.assertSoftly(softly -> { + softly.assertThat(model.asText()).isPresent(); + softly.assertThat(model.asText().get()).isEqualTo("Hello, world!"); + }); } } @@ -86,13 +84,12 @@ void testConsoleLogWithEnvs() throws IOException { try (WorkflowApplication appl = WorkflowApplication.builder().build()) { WorkflowModel model = appl.workflowDefinition(workflow).instance(Map.of()).start().join(); - SoftAssertions.assertSoftly( - softly -> { - softly.assertThat(model.asText()).isPresent(); - softly - .assertThat(model.asText().get()) - .isEqualTo("Running JavaScript code using Open Workflow!"); - }); + SoftAssertions.assertSoftly(softly -> { + softly.assertThat(model.asText()).isPresent(); + softly + .assertThat(model.asText().get()) + .isEqualTo("Running JavaScript code using Open Workflow!"); + }); } } @@ -106,19 +103,18 @@ void testConsoleLogWithExternalSource() throws IOException { new MockResponse() .setBody( """ - console.log("hello from script"); - """) + console.log("hello from script"); + """) .setHeader("Content-Type", "application/javascript") .setResponseCode(200)); try (WorkflowApplication appl = WorkflowApplication.builder().build()) { WorkflowModel model = appl.workflowDefinition(workflow).instance(Map.of()).start().join(); - SoftAssertions.assertSoftly( - softly -> { - softly.assertThat(model.asText()).isPresent(); - softly.assertThat(model.asText().get()).isEqualTo("hello from script"); - }); + SoftAssertions.assertSoftly(softly -> { + softly.assertThat(model.asText()).isPresent(); + softly.assertThat(model.asText().get()).isEqualTo("hello from script"); + }); } } diff --git a/impl/test/src/test/java/org/openworkflow/sdk/impl/test/RunShellExecutorTest.java b/impl/test/src/test/java/org/openworkflow/sdk/impl/test/RunShellExecutorTest.java index 7248fb7ba..5b0f9061d 100644 --- a/impl/test/src/test/java/org/openworkflow/sdk/impl/test/RunShellExecutorTest.java +++ b/impl/test/src/test/java/org/openworkflow/sdk/impl/test/RunShellExecutorTest.java @@ -52,25 +52,23 @@ void testEcho() throws IOException { Workflow workflow = WorkflowReader.readWorkflowFromClasspath("workflows-samples/run-shell/echo.yaml"); WorkflowModel model = appl.workflowDefinition(workflow).instance(Map.of()).start().join(); - SoftAssertions.assertSoftly( - softly -> { - ProcessResult result = model.as(ProcessResult.class).orElseThrow(); - softly.assertThat(result.code()).isEqualTo(0); - softly.assertThat(result.stderr()).isEmpty(); - softly.assertThat(result.stdout()).contains("Hello, anonymous"); - }); + SoftAssertions.assertSoftly(softly -> { + ProcessResult result = model.as(ProcessResult.class).orElseThrow(); + softly.assertThat(result.code()).isEqualTo(0); + softly.assertThat(result.stderr()).isEmpty(); + softly.assertThat(result.stdout()).contains("Hello, anonymous"); + }); } @Test void testEchoInvalid() throws IOException { Workflow workflow = WorkflowReader.readWorkflowFromClasspath("workflows-samples/run-shell/echo-invalid.yaml"); - assertThatThrownBy( - () -> - appl.workflowDefinition(workflow) - .instance(new Input(new User("John Doe"))) - .start() - .join()) + assertThatThrownBy(() -> + appl.workflowDefinition(workflow) + .instance(new Input(new User("John Doe"))) + .start() + .join()) .hasCauseInstanceOf(SecurityException.class); } @@ -80,13 +78,12 @@ void testEchoWithJqExpression() throws IOException { WorkflowReader.readWorkflowFromClasspath("workflows-samples/run-shell/echo-jq.yaml"); WorkflowModel model = appl.workflowDefinition(workflow).instance(new Input(new User("John Doe"))).start().join(); - SoftAssertions.assertSoftly( - softly -> { - ProcessResult result = model.as(ProcessResult.class).orElseThrow(); - softly.assertThat(result.code()).isEqualTo(0); - softly.assertThat(result.stderr()).isEmpty(); - softly.assertThat(result.stdout()).contains("Hello, John Doe"); - }); + SoftAssertions.assertSoftly(softly -> { + ProcessResult result = model.as(ProcessResult.class).orElseThrow(); + softly.assertThat(result.code()).isEqualTo(0); + softly.assertThat(result.stderr()).isEmpty(); + softly.assertThat(result.stdout()).contains("Hello, John Doe"); + }); } @Test @@ -95,13 +92,12 @@ void testDirectory() throws IOException { WorkflowReader.readWorkflowFromClasspath("workflows-samples/run-shell/pwd-directory.yaml"); WorkflowModel model = appl.workflowDefinition(workflow).instance(Map.of()).start().join(); - SoftAssertions.assertSoftly( - softly -> { - ProcessResult result = model.as(ProcessResult.class).orElseThrow(); - softly.assertThat(result.code()).isEqualTo(0); - softly.assertThat(result.stdout().trim()).isEqualTo("/tmp"); - softly.assertThat(result.stderr()).isEmpty(); - }); + SoftAssertions.assertSoftly(softly -> { + ProcessResult result = model.as(ProcessResult.class).orElseThrow(); + softly.assertThat(result.code()).isEqualTo(0); + softly.assertThat(result.stdout().trim()).isEqualTo("/tmp"); + softly.assertThat(result.stderr()).isEmpty(); + }); } @Test @@ -109,15 +105,13 @@ void testMissingShellCommand() throws IOException { Workflow workflow = WorkflowReader.readWorkflowFromClasspath( "workflows-samples/run-shell/missing-shell-command.yaml"); - SoftAssertions.assertSoftly( - softly -> { - softly - .assertThatThrownBy( - () -> { - appl.workflowDefinition(workflow).instance(Map.of()).start().join(); - }) - .hasMessageContaining("Missing shell command in RunShell task configuration"); - }); + SoftAssertions.assertSoftly(softly -> { + softly + .assertThatThrownBy(() -> { + appl.workflowDefinition(workflow).instance(Map.of()).start().join(); + }) + .hasMessageContaining("Missing shell command in RunShell task configuration"); + }); } @Test @@ -127,10 +121,9 @@ void testNonAwaitBehavior() throws IOException { "workflows-samples/run-shell/echo-not-awaiting.yaml"); Map inputMap = Map.of("full_name", "Matheus Cruz"); WorkflowModel outputModel = appl.workflowDefinition(workflow).instance(inputMap).start().join(); - SoftAssertions.assertSoftly( - softly -> { - softly.assertThat(outputModel.asMap().get()).isEqualTo(inputMap); - }); + SoftAssertions.assertSoftly(softly -> { + softly.assertThat(outputModel.asMap().get()).isEqualTo(inputMap); + }); } @Test @@ -141,12 +134,11 @@ void testStderr() throws IOException { WorkflowModel outputModel = appl.workflowDefinition(workflow).instance(inputMap).start().join(); - SoftAssertions.assertSoftly( - softly -> { - softly.assertThat(outputModel.asText()).isPresent(); - softly.assertThat(outputModel.asText().get()).isNotEmpty(); - softly.assertThat(outputModel.asText().get()).contains("ls:"); - }); + SoftAssertions.assertSoftly(softly -> { + softly.assertThat(outputModel.asText()).isPresent(); + softly.assertThat(outputModel.asText().get()).isNotEmpty(); + softly.assertThat(outputModel.asText().get()).contains("ls:"); + }); } @Test @@ -157,11 +149,10 @@ void testExitCode() throws IOException { WorkflowModel outputModel = appl.workflowDefinition(workflow).instance(inputMap).start().join(); - SoftAssertions.assertSoftly( - softly -> { - softly.assertThat(outputModel.asNumber()).isPresent(); - softly.assertThat(outputModel.asNumber().get()).isNotEqualTo(0); - }); + SoftAssertions.assertSoftly(softly -> { + softly.assertThat(outputModel.asNumber()).isPresent(); + softly.assertThat(outputModel.asNumber().get()).isNotEqualTo(0); + }); } @Test @@ -172,10 +163,9 @@ void testNone() throws IOException { WorkflowModel outputModel = appl.workflowDefinition(workflow).instance(inputMap).start().join(); - SoftAssertions.assertSoftly( - softly -> { - softly.assertThat(outputModel.asJavaObject()).isEqualTo(Map.of()); - }); + SoftAssertions.assertSoftly(softly -> { + softly.assertThat(outputModel.asJavaObject()).isEqualTo(Map.of()); + }); } @Test @@ -188,13 +178,12 @@ void testEchoWithArgsOnlyKey() throws IOException { .instance(Map.of("firstName", "John", "lastName", "Doe")) .start() .join(); - SoftAssertions.assertSoftly( - softly -> { - ProcessResult result = model.as(ProcessResult.class).orElseThrow(); - softly.assertThat(result.code()).isEqualTo(0); - softly.assertThat(result.stderr()).isEmpty(); - softly.assertThat(result.stdout()).contains("Hello John Doe"); - }); + SoftAssertions.assertSoftly(softly -> { + ProcessResult result = model.as(ProcessResult.class).orElseThrow(); + softly.assertThat(result.code()).isEqualTo(0); + softly.assertThat(result.stderr()).isEmpty(); + softly.assertThat(result.stdout()).contains("Hello John Doe"); + }); } @Test @@ -204,13 +193,12 @@ void testEchoWithArgsKeyValue() throws IOException { "workflows-samples/run-shell/echo-with-args-key-value.yaml"); WorkflowModel model = appl.workflowDefinition(workflow).instance(Map.of()).start().join(); - SoftAssertions.assertSoftly( - softly -> { - ProcessResult result = model.as(ProcessResult.class).orElseThrow(); - softly.assertThat(result.code()).isEqualTo(0); - softly.assertThat(result.stderr()).isEmpty(); - softly.assertThat(result.stdout()).contains("--user=john --password=doe"); - }); + SoftAssertions.assertSoftly(softly -> { + ProcessResult result = model.as(ProcessResult.class).orElseThrow(); + softly.assertThat(result.code()).isEqualTo(0); + softly.assertThat(result.stderr()).isEmpty(); + softly.assertThat(result.stdout()).contains("--user=john --password=doe"); + }); } @Test @@ -227,13 +215,12 @@ void testEchoWithArgsKeyValueJq() throws IOException { .start() .join(); - SoftAssertions.assertSoftly( - softly -> { - ProcessResult result = model.as(ProcessResult.class).orElseThrow(); - softly.assertThat(result.code()).isEqualTo(0); - softly.assertThat(result.stderr()).isEmpty(); - softly.assertThat(result.stdout()).contains("--user=john --password=doe"); - }); + SoftAssertions.assertSoftly(softly -> { + ProcessResult result = model.as(ProcessResult.class).orElseThrow(); + softly.assertThat(result.code()).isEqualTo(0); + softly.assertThat(result.stderr()).isEmpty(); + softly.assertThat(result.stdout()).contains("--user=john --password=doe"); + }); } record Input(User user) {} diff --git a/impl/test/src/test/java/org/openworkflow/sdk/impl/test/ScheduleEventConsumerTest.java b/impl/test/src/test/java/org/openworkflow/sdk/impl/test/ScheduleEventConsumerTest.java index 0e4614f79..46275e28c 100644 --- a/impl/test/src/test/java/org/openworkflow/sdk/impl/test/ScheduleEventConsumerTest.java +++ b/impl/test/src/test/java/org/openworkflow/sdk/impl/test/ScheduleEventConsumerTest.java @@ -63,10 +63,8 @@ void testAllEvent() throws IOException, InterruptedException, ExecutionException await() .pollDelay(Duration.ofMillis(20)) .atMost(Duration.ofMillis(980)) - .until( - () -> - instances.stream().filter(i -> i.status() == WorkflowStatus.COMPLETED).count() - == 1); + .until(() -> + instances.stream().filter(i -> i.status() == WorkflowStatus.COMPLETED).count() == 1); assertThat((Collection) assertThat(instances).singleElement().actual().output().asJavaObject()) .containsExactlyInAnyOrder("Javierito", "Fulanito"); } @@ -81,10 +79,8 @@ void testOneEvent() throws IOException, InterruptedException, ExecutionException await() .pollDelay(Duration.ofMillis(20)) .atMost(Duration.ofMillis(980)) - .until( - () -> - instances.stream().filter(i -> i.status() == WorkflowStatus.COMPLETED).count() - == 2); + .until(() -> + instances.stream().filter(i -> i.status() == WorkflowStatus.COMPLETED).count() == 2); List outputs = instances.stream().map(i -> i.output().asJavaObject()).toList(); assertThat(outputs) .containsExactlyInAnyOrder( @@ -105,14 +101,13 @@ void testTogether() throws IOException, InterruptedException, ExecutionException await() .pollDelay(Duration.ofMillis(40)) .atMost(Duration.ofMillis(980)) - .until( - () -> - oneDefInstances.stream().filter(i -> i.status() == WorkflowStatus.COMPLETED).count() - == 2 - && allDefInstances.stream() - .filter(i -> i.status() == WorkflowStatus.COMPLETED) - .count() - == 1); + .until(() -> + oneDefInstances.stream().filter(i -> i.status() == WorkflowStatus.COMPLETED).count() + == 2 + && allDefInstances.stream() + .filter(i -> i.status() == WorkflowStatus.COMPLETED) + .count() + == 1); List outputs = oneDefInstances.stream().map(i -> i.output().asJavaObject()).toList(); assertThat(outputs) diff --git a/impl/test/src/test/java/org/openworkflow/sdk/impl/test/SecretExpressionTest.java b/impl/test/src/test/java/org/openworkflow/sdk/impl/test/SecretExpressionTest.java index 8c51d2f4f..7d1e6ea97 100644 --- a/impl/test/src/test/java/org/openworkflow/sdk/impl/test/SecretExpressionTest.java +++ b/impl/test/src/test/java/org/openworkflow/sdk/impl/test/SecretExpressionTest.java @@ -63,14 +63,13 @@ void testDefault() { @Test void testMissing() { try (WorkflowApplication appl = WorkflowApplication.builder().build()) { - assertThatThrownBy( - () -> - appl.workflowDefinition(workflow) - .instance(Map.of()) - .start() - .join() - .asMap() - .orElseThrow()) + assertThatThrownBy(() -> + appl.workflowDefinition(workflow) + .instance(Map.of()) + .start() + .join() + .asMap() + .orElseThrow()) .hasCauseInstanceOf(WorkflowException.class); } } @@ -79,13 +78,8 @@ void testMissing() { void testCustom() { try (WorkflowApplication appl = WorkflowApplication.builder() - .withSecretManager( - k -> - Map.of( - "name", - "ClarkKent", - "enemy", - Map.of("name", "Lex Luthor", "isHuman", true))) + .withSecretManager(k -> + Map.of("name", "ClarkKent", "enemy", Map.of("name", "Lex Luthor", "isHuman", true))) .build()) { Map map = appl.workflowDefinition(workflow).instance(Map.of()).start().join().asMap().orElseThrow(); diff --git a/impl/test/src/test/java/org/openworkflow/sdk/impl/test/WaitExecutorTest.java b/impl/test/src/test/java/org/openworkflow/sdk/impl/test/WaitExecutorTest.java index ae734e641..8ae8f8c92 100644 --- a/impl/test/src/test/java/org/openworkflow/sdk/impl/test/WaitExecutorTest.java +++ b/impl/test/src/test/java/org/openworkflow/sdk/impl/test/WaitExecutorTest.java @@ -108,10 +108,9 @@ void testWaitWithDurationInlineComposite() { void testWaitWithDurationLiteralISO8601Seconds() { Workflow workflow = WorkflowBuilder.workflow("wait-literal-seconds", "test", "0.1.0") - .tasks( - list -> - list.wait( - w -> w.build().setWait(new TimeoutAfter().withDurationExpression("PT1S")))) + .tasks(list -> + list.wait( + w -> w.build().setWait(new TimeoutAfter().withDurationExpression("PT1S")))) .build(); long startTime = System.currentTimeMillis(); @@ -127,11 +126,9 @@ void testWaitWithDurationLiteralISO8601Milliseconds() { // PT0.1S = 100 milliseconds Workflow workflow = WorkflowBuilder.workflow("wait-literal-millis", "test", "0.1.0") - .tasks( - list -> - list.wait( - w -> - w.build().setWait(new TimeoutAfter().withDurationExpression("PT0.1S")))) + .tasks(list -> + list.wait( + w -> w.build().setWait(new TimeoutAfter().withDurationExpression("PT0.1S")))) .build(); long startTime = System.currentTimeMillis(); @@ -173,12 +170,11 @@ void testWaitWithDurationExpressionFromContext() throws IOException { void testWaitWithDurationExpressionInvalidValue() throws IOException { Workflow workflow = readWorkflowFromClasspath("workflows-samples/wait-expression-input.yaml"); - assertThatThrownBy( - () -> - appl.workflowDefinition(workflow) - .instance(Map.of("timeout", "not-a-duration")) - .start() - .join()) + assertThatThrownBy(() -> + appl.workflowDefinition(workflow) + .instance(Map.of("timeout", "not-a-duration")) + .start() + .join()) .hasCauseInstanceOf(DateTimeParseException.class); } diff --git a/impl/test/src/test/java/org/openworkflow/sdk/impl/test/junit/ProtocCheckCondition.java b/impl/test/src/test/java/org/openworkflow/sdk/impl/test/junit/ProtocCheckCondition.java index 61fa3be7c..426710e05 100644 --- a/impl/test/src/test/java/org/openworkflow/sdk/impl/test/junit/ProtocCheckCondition.java +++ b/impl/test/src/test/java/org/openworkflow/sdk/impl/test/junit/ProtocCheckCondition.java @@ -41,13 +41,11 @@ public class ProtocCheckCondition implements ExecutionCondition { @Override public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) { return AnnotationUtils.findAnnotation(context.getElement(), DisabledIfProtocUnavailable.class) - .map( - annotation -> - protocAvailable - ? ConditionEvaluationResult.enabled( - "Protoc is available for the current platform.") - : ConditionEvaluationResult.disabled( - "Test disabled: Protoc not currently available not found.")) + .map(annotation -> + protocAvailable + ? ConditionEvaluationResult.enabled("Protoc is available for the current platform.") + : ConditionEvaluationResult.disabled( + "Test disabled: Protoc not currently available not found.")) .orElse(ConditionEvaluationResult.enabled("No @DisabledIfProtocUnavailable found.")); } } diff --git a/impl/test/src/test/java/org/openworkflow/sdk/impl/test/junit/PythonCheckCondition.java b/impl/test/src/test/java/org/openworkflow/sdk/impl/test/junit/PythonCheckCondition.java index 0e016077e..97da682d0 100644 --- a/impl/test/src/test/java/org/openworkflow/sdk/impl/test/junit/PythonCheckCondition.java +++ b/impl/test/src/test/java/org/openworkflow/sdk/impl/test/junit/PythonCheckCondition.java @@ -27,11 +27,10 @@ public class PythonCheckCondition implements ExecutionCondition { @Override public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) { return AnnotationUtils.findAnnotation(context.getElement(), DisabledIfPythonUnavailable.class) - .map( - annotation -> - isBinaryAvailable("python", "--version") - ? ConditionEvaluationResult.enabled("Python is available.") - : ConditionEvaluationResult.disabled("Test disabled: Python not found.")) + .map(annotation -> + isBinaryAvailable("python", "--version") + ? ConditionEvaluationResult.enabled("Python is available.") + : ConditionEvaluationResult.disabled("Test disabled: Python not found.")) .orElse(ConditionEvaluationResult.enabled("No @DisabledIfBinaryUnavailable found.")); } } diff --git a/mermaid/src/test/java/org/openworkflow/sdk/mermaid/ClasspathYamlFinder.java b/mermaid/src/test/java/org/openworkflow/sdk/mermaid/ClasspathYamlFinder.java index a40729c8e..74c4ff62c 100644 --- a/mermaid/src/test/java/org/openworkflow/sdk/mermaid/ClasspathYamlFinder.java +++ b/mermaid/src/test/java/org/openworkflow/sdk/mermaid/ClasspathYamlFinder.java @@ -73,18 +73,16 @@ private static Collection scanFileUrl(URL url, String prefix) throws IOE try (Stream s = Files.walk(root)) { return s.filter(Files::isRegularFile) - .filter( - p -> { - String name = p.getFileName().toString().toLowerCase(Locale.ROOT); - return name.endsWith(".yaml") || name.endsWith(".yml"); - }) - .map( - p -> { - String rel = root.relativize(p).toString().replace(File.separatorChar, '/'); - // When scanning the specific prefix directory, add "prefix/" so callers get - // paths relative to the classpath root, e.g. "workflows-samples/foo.yaml". - return rootIsPrefixDir ? (prefix + "/" + rel) : rel; - }) + .filter(p -> { + String name = p.getFileName().toString().toLowerCase(Locale.ROOT); + return name.endsWith(".yaml") || name.endsWith(".yml"); + }) + .map(p -> { + String rel = root.relativize(p).toString().replace(File.separatorChar, '/'); + // When scanning the specific prefix directory, add "prefix/" so callers get + // paths relative to the classpath root, e.g. "workflows-samples/foo.yaml". + return rootIsPrefixDir ? (prefix + "/" + rel) : rel; + }) .collect(Collectors.toCollection(LinkedHashSet::new)); } } diff --git a/mermaid/src/test/java/org/openworkflow/sdk/mermaid/MermaidSmokeTest.java b/mermaid/src/test/java/org/openworkflow/sdk/mermaid/MermaidSmokeTest.java index e695f90d5..3496a4ad8 100644 --- a/mermaid/src/test/java/org/openworkflow/sdk/mermaid/MermaidSmokeTest.java +++ b/mermaid/src/test/java/org/openworkflow/sdk/mermaid/MermaidSmokeTest.java @@ -33,11 +33,11 @@ static Stream yamlSamples() throws IOException { if (list.isEmpty()) { throw new IllegalStateException( """ - No YAML resources found on the test classpath. - - Is openworkflow-impl-test built and its *-tests.jar on the test classpath? - - Are YAMLs under src/test/resources in that module? - - Path inside JAR may differ from '/'. - """); + No YAML resources found on the test classpath. + - Is openworkflow-impl-test built and its *-tests.jar on the test classpath? + - Are YAMLs under src/test/resources in that module? + - Path inside JAR may differ from '/'. + """); } return list.stream(); } diff --git a/pom.xml b/pom.xml index 1da1ad738..941d863f2 100644 --- a/pom.xml +++ b/pom.xml @@ -59,7 +59,7 @@ 3.3.1 3.6.0 - 3.10.4 + 3.11.0 3.16.0 3.11.4 4.36.2 @@ -84,8 +84,8 @@ 4.3.0 4.32.1 - 3.2.4 - 2.22 + 3.3.0 + 2.23 3.0.9 5.5.1 5.1.0